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/DebugInfo.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Module.h"
29 #include "llvm/TypeFinder.h"
30 #include "llvm/ValueSymbolTable.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/FormattedStream.h"
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static const Module *getModuleFromVal(const Value *V) {
53 if (const Argument *MA = dyn_cast<Argument>(V))
54 return MA->getParent() ? MA->getParent()->getParent() : 0;
56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57 return BB->getParent() ? BB->getParent()->getParent() : 0;
59 if (const Instruction *I = dyn_cast<Instruction>(V)) {
60 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61 return M ? M->getParent() : 0;
64 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65 return GV->getParent();
69 // PrintEscapedString - Print each character of the specified string, escaping
70 // it if it is not printable or if it is an escape char.
71 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
72 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
73 unsigned char C = Name[i];
74 if (isprint(C) && C != '\\' && C != '"')
77 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
88 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
89 /// prefixed with % (if the string only contains simple characters) or is
90 /// surrounded with ""'s (if it has special chars in it). Print it out.
91 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
92 assert(!Name.empty() && "Cannot get empty name!");
95 case GlobalPrefix: OS << '@'; break;
96 case LabelPrefix: break;
97 case LocalPrefix: OS << '%'; break;
100 // Scan the name to see if it needs quotes first.
101 bool NeedsQuotes = isdigit(Name[0]);
103 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
104 // By making this unsigned, the value passed in to isalnum will always be
105 // in the range 0-255. This is important when building with MSVC because
106 // its implementation will assert. This situation can arise when dealing
107 // with UTF-8 multibyte characters.
108 unsigned char C = Name[i];
109 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
116 // If we didn't need any quotes, just write out the name in one blast.
122 // Okay, we need quotes. Output the quotes and escape any scary characters as
125 PrintEscapedString(Name, OS);
129 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
130 /// prefixed with % (if the string only contains simple characters) or is
131 /// surrounded with ""'s (if it has special chars in it). Print it out.
132 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
133 PrintLLVMName(OS, V->getName(),
134 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
137 //===----------------------------------------------------------------------===//
138 // TypePrinting Class: Type printing machinery
139 //===----------------------------------------------------------------------===//
141 /// TypePrinting - Type printing machinery.
144 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
145 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
148 /// NamedTypes - The named types that are used by the current module.
149 TypeFinder NamedTypes;
151 /// NumberedTypes - The numbered types, along with their value.
152 DenseMap<StructType*, unsigned> NumberedTypes;
158 void incorporateTypes(const Module &M);
160 void print(Type *Ty, raw_ostream &OS);
162 void printStructBody(StructType *Ty, raw_ostream &OS);
164 } // end anonymous namespace.
167 void TypePrinting::incorporateTypes(const Module &M) {
168 NamedTypes.run(M, false);
170 // The list of struct types we got back includes all the struct types, split
171 // the unnamed ones out to a numbering and remove the anonymous structs.
172 unsigned NextNumber = 0;
174 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
175 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
176 StructType *STy = *I;
178 // Ignore anonymous types.
179 if (STy->isLiteral())
182 if (STy->getName().empty())
183 NumberedTypes[STy] = NextNumber++;
188 NamedTypes.erase(NextToUse, NamedTypes.end());
192 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
193 /// use of type names or up references to shorten the type name where possible.
194 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
195 switch (Ty->getTypeID()) {
196 case Type::VoidTyID: OS << "void"; break;
197 case Type::HalfTyID: OS << "half"; 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::X86_MMXTyID: OS << "x86_mmx"; break;
206 case Type::IntegerTyID:
207 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
210 case Type::FunctionTyID: {
211 FunctionType *FTy = cast<FunctionType>(Ty);
212 print(FTy->getReturnType(), OS);
214 for (FunctionType::param_iterator I = FTy->param_begin(),
215 E = FTy->param_end(); I != E; ++I) {
216 if (I != FTy->param_begin())
220 if (FTy->isVarArg()) {
221 if (FTy->getNumParams()) OS << ", ";
227 case Type::StructTyID: {
228 StructType *STy = cast<StructType>(Ty);
230 if (STy->isLiteral())
231 return printStructBody(STy, OS);
233 if (!STy->getName().empty())
234 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
236 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
237 if (I != NumberedTypes.end())
238 OS << '%' << I->second;
239 else // Not enumerated, print the hex address.
240 OS << "%\"type " << STy << '\"';
243 case Type::PointerTyID: {
244 PointerType *PTy = cast<PointerType>(Ty);
245 print(PTy->getElementType(), OS);
246 if (unsigned AddressSpace = PTy->getAddressSpace())
247 OS << " addrspace(" << AddressSpace << ')';
251 case Type::ArrayTyID: {
252 ArrayType *ATy = cast<ArrayType>(Ty);
253 OS << '[' << ATy->getNumElements() << " x ";
254 print(ATy->getElementType(), OS);
258 case Type::VectorTyID: {
259 VectorType *PTy = cast<VectorType>(Ty);
260 OS << "<" << PTy->getNumElements() << " x ";
261 print(PTy->getElementType(), OS);
266 OS << "<unrecognized-type>";
271 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
272 if (STy->isOpaque()) {
280 if (STy->getNumElements() == 0) {
283 StructType::element_iterator I = STy->element_begin();
286 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
299 //===----------------------------------------------------------------------===//
300 // SlotTracker Class: Enumerate slot numbers for unnamed values
301 //===----------------------------------------------------------------------===//
305 /// This class provides computation of slot numbers for LLVM Assembly writing.
309 /// ValueMap - A mapping of Values to slot numbers.
310 typedef DenseMap<const Value*, unsigned> ValueMap;
313 /// TheModule - The module for which we are holding slot numbers.
314 const Module* TheModule;
316 /// TheFunction - The function for which we are holding slot numbers.
317 const Function* TheFunction;
318 bool FunctionProcessed;
320 /// mMap - The slot map for the module level data.
324 /// fMap - The slot map for the function level data.
328 /// mdnMap - Map for MDNodes.
329 DenseMap<const MDNode*, unsigned> mdnMap;
332 /// Construct from a module
333 explicit SlotTracker(const Module *M);
334 /// Construct from a function, starting out in incorp state.
335 explicit SlotTracker(const Function *F);
337 /// Return the slot number of the specified value in it's type
338 /// plane. If something is not in the SlotTracker, return -1.
339 int getLocalSlot(const Value *V);
340 int getGlobalSlot(const GlobalValue *V);
341 int getMetadataSlot(const MDNode *N);
343 /// If you'd like to deal with a function instead of just a module, use
344 /// this method to get its data into the SlotTracker.
345 void incorporateFunction(const Function *F) {
347 FunctionProcessed = false;
350 /// After calling incorporateFunction, use this method to remove the
351 /// most recently incorporated function from the SlotTracker. This
352 /// will reset the state of the machine back to just the module contents.
353 void purgeFunction();
355 /// MDNode map iterators.
356 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
357 mdn_iterator mdn_begin() { return mdnMap.begin(); }
358 mdn_iterator mdn_end() { return mdnMap.end(); }
359 unsigned mdn_size() const { return mdnMap.size(); }
360 bool mdn_empty() const { return mdnMap.empty(); }
362 /// This function does the actual initialization.
363 inline void initialize();
365 // Implementation Details
367 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
368 void CreateModuleSlot(const GlobalValue *V);
370 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
371 void CreateMetadataSlot(const MDNode *N);
373 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
374 void CreateFunctionSlot(const Value *V);
376 /// Add all of the module level global variables (and their initializers)
377 /// and function declarations, but not the contents of those functions.
378 void processModule();
380 /// Add all of the functions arguments, basic blocks, and instructions.
381 void processFunction();
383 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
384 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
387 } // end anonymous namespace
390 static SlotTracker *createSlotTracker(const Value *V) {
391 if (const Argument *FA = dyn_cast<Argument>(V))
392 return new SlotTracker(FA->getParent());
394 if (const Instruction *I = dyn_cast<Instruction>(V))
396 return new SlotTracker(I->getParent()->getParent());
398 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
399 return new SlotTracker(BB->getParent());
401 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
402 return new SlotTracker(GV->getParent());
404 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
405 return new SlotTracker(GA->getParent());
407 if (const Function *Func = dyn_cast<Function>(V))
408 return new SlotTracker(Func);
410 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
411 if (!MD->isFunctionLocal())
412 return new SlotTracker(MD->getFunction());
414 return new SlotTracker((Function *)0);
421 #define ST_DEBUG(X) dbgs() << X
426 // Module level constructor. Causes the contents of the Module (sans functions)
427 // to be added to the slot table.
428 SlotTracker::SlotTracker(const Module *M)
429 : TheModule(M), TheFunction(0), FunctionProcessed(false),
430 mNext(0), fNext(0), mdnNext(0) {
433 // Function level constructor. Causes the contents of the Module and the one
434 // function provided to be added to the slot table.
435 SlotTracker::SlotTracker(const Function *F)
436 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
437 mNext(0), fNext(0), mdnNext(0) {
440 inline void SlotTracker::initialize() {
443 TheModule = 0; ///< Prevent re-processing next time we're called.
446 if (TheFunction && !FunctionProcessed)
450 // Iterate through all the global variables, functions, and global
451 // variable initializers and create slots for them.
452 void SlotTracker::processModule() {
453 ST_DEBUG("begin processModule!\n");
455 // Add all of the unnamed global variables to the value table.
456 for (Module::const_global_iterator I = TheModule->global_begin(),
457 E = TheModule->global_end(); I != E; ++I) {
462 // Add metadata used by named metadata.
463 for (Module::const_named_metadata_iterator
464 I = TheModule->named_metadata_begin(),
465 E = TheModule->named_metadata_end(); I != E; ++I) {
466 const NamedMDNode *NMD = I;
467 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
468 CreateMetadataSlot(NMD->getOperand(i));
471 // Add all the unnamed functions to the table.
472 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
477 ST_DEBUG("end processModule!\n");
480 // Process the arguments, basic blocks, and instructions of a function.
481 void SlotTracker::processFunction() {
482 ST_DEBUG("begin processFunction!\n");
485 // Add all the function arguments with no names.
486 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
487 AE = TheFunction->arg_end(); AI != AE; ++AI)
489 CreateFunctionSlot(AI);
491 ST_DEBUG("Inserting Instructions:\n");
493 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
495 // Add all of the basic blocks and instructions with no names.
496 for (Function::const_iterator BB = TheFunction->begin(),
497 E = TheFunction->end(); BB != E; ++BB) {
499 CreateFunctionSlot(BB);
501 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
503 if (!I->getType()->isVoidTy() && !I->hasName())
504 CreateFunctionSlot(I);
506 // Intrinsics can directly use metadata. We allow direct calls to any
507 // llvm.foo function here, because the target may not be linked into the
509 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
510 if (Function *F = CI->getCalledFunction())
511 if (F->getName().startswith("llvm."))
512 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
513 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
514 CreateMetadataSlot(N);
517 // Process metadata attached with this instruction.
518 I->getAllMetadata(MDForInst);
519 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
520 CreateMetadataSlot(MDForInst[i].second);
525 FunctionProcessed = true;
527 ST_DEBUG("end processFunction!\n");
530 /// Clean up after incorporating a function. This is the only way to get out of
531 /// the function incorporation state that affects get*Slot/Create*Slot. Function
532 /// incorporation state is indicated by TheFunction != 0.
533 void SlotTracker::purgeFunction() {
534 ST_DEBUG("begin purgeFunction!\n");
535 fMap.clear(); // Simply discard the function level map
537 FunctionProcessed = false;
538 ST_DEBUG("end purgeFunction!\n");
541 /// getGlobalSlot - Get the slot number of a global value.
542 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
543 // Check for uninitialized state and do lazy initialization.
546 // Find the value in the module map
547 ValueMap::iterator MI = mMap.find(V);
548 return MI == mMap.end() ? -1 : (int)MI->second;
551 /// getMetadataSlot - Get the slot number of a MDNode.
552 int SlotTracker::getMetadataSlot(const MDNode *N) {
553 // Check for uninitialized state and do lazy initialization.
556 // Find the MDNode in the module map
557 mdn_iterator MI = mdnMap.find(N);
558 return MI == mdnMap.end() ? -1 : (int)MI->second;
562 /// getLocalSlot - Get the slot number for a value that is local to a function.
563 int SlotTracker::getLocalSlot(const Value *V) {
564 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
566 // Check for uninitialized state and do lazy initialization.
569 ValueMap::iterator FI = fMap.find(V);
570 return FI == fMap.end() ? -1 : (int)FI->second;
574 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
575 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
576 assert(V && "Can't insert a null Value into SlotTracker!");
577 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
578 assert(!V->hasName() && "Doesn't need a slot!");
580 unsigned DestSlot = mNext++;
583 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
585 // G = Global, F = Function, A = Alias, o = other
586 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
587 (isa<Function>(V) ? 'F' :
588 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
591 /// CreateSlot - Create a new slot for the specified value if it has no name.
592 void SlotTracker::CreateFunctionSlot(const Value *V) {
593 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
595 unsigned DestSlot = fNext++;
598 // G = Global, F = Function, o = other
599 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
600 DestSlot << " [o]\n");
603 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
604 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
605 assert(N && "Can't insert a null Value into SlotTracker!");
607 // Don't insert if N is a function-local metadata, these are always printed
609 if (!N->isFunctionLocal()) {
610 mdn_iterator I = mdnMap.find(N);
611 if (I != mdnMap.end())
614 unsigned DestSlot = mdnNext++;
615 mdnMap[N] = DestSlot;
618 // Recursively add any MDNodes referenced by operands.
619 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
620 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
621 CreateMetadataSlot(Op);
624 //===----------------------------------------------------------------------===//
625 // AsmWriter Implementation
626 //===----------------------------------------------------------------------===//
628 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
629 TypePrinting *TypePrinter,
630 SlotTracker *Machine,
631 const Module *Context);
635 static const char *getPredicateText(unsigned predicate) {
636 const char * pred = "unknown";
638 case FCmpInst::FCMP_FALSE: pred = "false"; break;
639 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
640 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
641 case FCmpInst::FCMP_OGE: pred = "oge"; break;
642 case FCmpInst::FCMP_OLT: pred = "olt"; break;
643 case FCmpInst::FCMP_OLE: pred = "ole"; break;
644 case FCmpInst::FCMP_ONE: pred = "one"; break;
645 case FCmpInst::FCMP_ORD: pred = "ord"; break;
646 case FCmpInst::FCMP_UNO: pred = "uno"; break;
647 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
648 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
649 case FCmpInst::FCMP_UGE: pred = "uge"; break;
650 case FCmpInst::FCMP_ULT: pred = "ult"; break;
651 case FCmpInst::FCMP_ULE: pred = "ule"; break;
652 case FCmpInst::FCMP_UNE: pred = "une"; break;
653 case FCmpInst::FCMP_TRUE: pred = "true"; break;
654 case ICmpInst::ICMP_EQ: pred = "eq"; break;
655 case ICmpInst::ICMP_NE: pred = "ne"; break;
656 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
657 case ICmpInst::ICMP_SGE: pred = "sge"; break;
658 case ICmpInst::ICMP_SLT: pred = "slt"; break;
659 case ICmpInst::ICMP_SLE: pred = "sle"; break;
660 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
661 case ICmpInst::ICMP_UGE: pred = "uge"; break;
662 case ICmpInst::ICMP_ULT: pred = "ult"; break;
663 case ICmpInst::ICMP_ULE: pred = "ule"; break;
668 static void writeAtomicRMWOperation(raw_ostream &Out,
669 AtomicRMWInst::BinOp Op) {
671 default: Out << " <unknown operation " << Op << ">"; break;
672 case AtomicRMWInst::Xchg: Out << " xchg"; break;
673 case AtomicRMWInst::Add: Out << " add"; break;
674 case AtomicRMWInst::Sub: Out << " sub"; break;
675 case AtomicRMWInst::And: Out << " and"; break;
676 case AtomicRMWInst::Nand: Out << " nand"; break;
677 case AtomicRMWInst::Or: Out << " or"; break;
678 case AtomicRMWInst::Xor: Out << " xor"; break;
679 case AtomicRMWInst::Max: Out << " max"; break;
680 case AtomicRMWInst::Min: Out << " min"; break;
681 case AtomicRMWInst::UMax: Out << " umax"; break;
682 case AtomicRMWInst::UMin: Out << " umin"; break;
686 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
687 if (const OverflowingBinaryOperator *OBO =
688 dyn_cast<OverflowingBinaryOperator>(U)) {
689 if (OBO->hasNoUnsignedWrap())
691 if (OBO->hasNoSignedWrap())
693 } else if (const PossiblyExactOperator *Div =
694 dyn_cast<PossiblyExactOperator>(U)) {
697 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
698 if (GEP->isInBounds())
703 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
704 TypePrinting &TypePrinter,
705 SlotTracker *Machine,
706 const Module *Context) {
707 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
708 if (CI->getType()->isIntegerTy(1)) {
709 Out << (CI->getZExtValue() ? "true" : "false");
712 Out << CI->getValue();
716 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
717 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
718 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
719 // We would like to output the FP constant value in exponential notation,
720 // but we cannot do this if doing so will lose precision. Check here to
721 // make sure that we only output it in exponential format if we can parse
722 // the value back and get the same value.
725 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
726 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
727 bool isInf = CFP->getValueAPF().isInfinity();
728 bool isNaN = CFP->getValueAPF().isNaN();
729 if (!isHalf && !isInf && !isNaN) {
730 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
731 CFP->getValueAPF().convertToFloat();
732 SmallString<128> StrVal;
733 raw_svector_ostream(StrVal) << Val;
735 // Check to make sure that the stringized number is not some string like
736 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
737 // that the string matches the "[-+]?[0-9]" regex.
739 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
740 ((StrVal[0] == '-' || StrVal[0] == '+') &&
741 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
742 // Reparse stringized version!
743 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
749 // Otherwise we could not reparse it to exactly the same value, so we must
750 // output the string in hexadecimal format! Note that loading and storing
751 // floating point types changes the bits of NaNs on some hosts, notably
752 // x86, so we must not use these types.
753 assert(sizeof(double) == sizeof(uint64_t) &&
754 "assuming that double is 64 bits!");
756 APFloat apf = CFP->getValueAPF();
757 // Halves and floats are represented in ASCII IR as double, convert.
759 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
762 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
767 // Either half, or some form of long double.
768 // These appear as a magic letter identifying the type, then a
769 // fixed number of hex digits.
771 // Bit position, in the current word, of the next nibble to print.
774 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
776 // api needed to prevent premature destruction
777 APInt api = CFP->getValueAPF().bitcastToAPInt();
778 const uint64_t* p = api.getRawData();
779 uint64_t word = p[1];
781 int width = api.getBitWidth();
782 for (int j=0; j<width; j+=4, shiftcount-=4) {
783 unsigned int nibble = (word>>shiftcount) & 15;
785 Out << (unsigned char)(nibble + '0');
787 Out << (unsigned char)(nibble - 10 + 'A');
788 if (shiftcount == 0 && j+4 < width) {
792 shiftcount = width-j-4;
796 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
799 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
802 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
806 llvm_unreachable("Unsupported floating point type");
807 // api needed to prevent premature destruction
808 APInt api = CFP->getValueAPF().bitcastToAPInt();
809 const uint64_t* p = api.getRawData();
811 int width = api.getBitWidth();
812 for (int j=0; j<width; j+=4, shiftcount-=4) {
813 unsigned int nibble = (word>>shiftcount) & 15;
815 Out << (unsigned char)(nibble + '0');
817 Out << (unsigned char)(nibble - 10 + 'A');
818 if (shiftcount == 0 && j+4 < width) {
822 shiftcount = width-j-4;
828 if (isa<ConstantAggregateZero>(CV)) {
829 Out << "zeroinitializer";
833 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
834 Out << "blockaddress(";
835 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
838 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
844 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
845 Type *ETy = CA->getType()->getElementType();
847 TypePrinter.print(ETy, Out);
849 WriteAsOperandInternal(Out, CA->getOperand(0),
850 &TypePrinter, Machine,
852 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
854 TypePrinter.print(ETy, Out);
856 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
863 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
864 // As a special case, print the array as a string if it is an array of
865 // i8 with ConstantInt values.
866 if (CA->isString()) {
868 PrintEscapedString(CA->getAsString(), Out);
873 Type *ETy = CA->getType()->getElementType();
875 TypePrinter.print(ETy, Out);
877 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
878 &TypePrinter, Machine,
880 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
882 TypePrinter.print(ETy, Out);
884 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
892 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
893 if (CS->getType()->isPacked())
896 unsigned N = CS->getNumOperands();
899 TypePrinter.print(CS->getOperand(0)->getType(), Out);
902 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
905 for (unsigned i = 1; i < N; i++) {
907 TypePrinter.print(CS->getOperand(i)->getType(), Out);
910 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
917 if (CS->getType()->isPacked())
922 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
923 Type *ETy = CV->getType()->getVectorElementType();
925 TypePrinter.print(ETy, Out);
927 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
929 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
931 TypePrinter.print(ETy, Out);
933 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
940 if (isa<ConstantPointerNull>(CV)) {
945 if (isa<UndefValue>(CV)) {
950 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
951 Out << CE->getOpcodeName();
952 WriteOptimizationInfo(Out, CE);
954 Out << ' ' << getPredicateText(CE->getPredicate());
957 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
958 TypePrinter.print((*OI)->getType(), Out);
960 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
961 if (OI+1 != CE->op_end())
965 if (CE->hasIndices()) {
966 ArrayRef<unsigned> Indices = CE->getIndices();
967 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
968 Out << ", " << Indices[i];
973 TypePrinter.print(CE->getType(), Out);
980 Out << "<placeholder or erroneous Constant>";
983 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
984 TypePrinting *TypePrinter,
985 SlotTracker *Machine,
986 const Module *Context) {
988 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
989 const Value *V = Node->getOperand(mi);
993 TypePrinter->print(V->getType(), Out);
995 WriteAsOperandInternal(Out, Node->getOperand(mi),
996 TypePrinter, Machine, Context);
1006 /// WriteAsOperand - Write the name of the specified value out to the specified
1007 /// ostream. This can be useful when you just want to print int %reg126, not
1008 /// the whole instruction that generated it.
1010 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1011 TypePrinting *TypePrinter,
1012 SlotTracker *Machine,
1013 const Module *Context) {
1015 PrintLLVMName(Out, V);
1019 const Constant *CV = dyn_cast<Constant>(V);
1020 if (CV && !isa<GlobalValue>(CV)) {
1021 assert(TypePrinter && "Constants require TypePrinting!");
1022 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1026 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1028 if (IA->hasSideEffects())
1029 Out << "sideeffect ";
1030 if (IA->isAlignStack())
1031 Out << "alignstack ";
1033 PrintEscapedString(IA->getAsmString(), Out);
1035 PrintEscapedString(IA->getConstraintString(), Out);
1040 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1041 if (N->isFunctionLocal()) {
1042 // Print metadata inline, not via slot reference number.
1043 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1048 if (N->isFunctionLocal())
1049 Machine = new SlotTracker(N->getFunction());
1051 Machine = new SlotTracker(Context);
1053 int Slot = Machine->getMetadataSlot(N);
1061 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1063 PrintEscapedString(MDS->getString(), Out);
1068 if (V->getValueID() == Value::PseudoSourceValueVal ||
1069 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1076 // If we have a SlotTracker, use it.
1078 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1079 Slot = Machine->getGlobalSlot(GV);
1082 Slot = Machine->getLocalSlot(V);
1084 // If the local value didn't succeed, then we may be referring to a value
1085 // from a different function. Translate it, as this can happen when using
1086 // address of blocks.
1088 if ((Machine = createSlotTracker(V))) {
1089 Slot = Machine->getLocalSlot(V);
1093 } else if ((Machine = createSlotTracker(V))) {
1094 // Otherwise, create one to get the # and then destroy it.
1095 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1096 Slot = Machine->getGlobalSlot(GV);
1099 Slot = Machine->getLocalSlot(V);
1108 Out << Prefix << Slot;
1113 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1114 bool PrintType, const Module *Context) {
1116 // Fast path: Don't construct and populate a TypePrinting object if we
1117 // won't be needing any types printed.
1119 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1120 V->hasName() || isa<GlobalValue>(V))) {
1121 WriteAsOperandInternal(Out, V, 0, 0, Context);
1125 if (Context == 0) Context = getModuleFromVal(V);
1127 TypePrinting TypePrinter;
1129 TypePrinter.incorporateTypes(*Context);
1131 TypePrinter.print(V->getType(), Out);
1135 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1140 class AssemblyWriter {
1141 formatted_raw_ostream &Out;
1142 SlotTracker &Machine;
1143 const Module *TheModule;
1144 TypePrinting TypePrinter;
1145 AssemblyAnnotationWriter *AnnotationWriter;
1148 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1150 AssemblyAnnotationWriter *AAW)
1151 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1153 TypePrinter.incorporateTypes(*M);
1156 void printMDNodeBody(const MDNode *MD);
1157 void printNamedMDNode(const NamedMDNode *NMD);
1159 void printModule(const Module *M);
1161 void writeOperand(const Value *Op, bool PrintType);
1162 void writeParamOperand(const Value *Operand, Attributes Attrs);
1163 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1165 void writeAllMDNodes();
1167 void printTypeIdentities();
1168 void printGlobal(const GlobalVariable *GV);
1169 void printAlias(const GlobalAlias *GV);
1170 void printFunction(const Function *F);
1171 void printArgument(const Argument *FA, Attributes Attrs);
1172 void printBasicBlock(const BasicBlock *BB);
1173 void printInstruction(const Instruction &I);
1176 // printInfoComment - Print a little comment after the instruction indicating
1177 // which slot it occupies.
1178 void printInfoComment(const Value &V);
1180 } // end of anonymous namespace
1182 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1184 Out << "<null operand!>";
1188 TypePrinter.print(Operand->getType(), Out);
1191 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1194 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1195 SynchronizationScope SynchScope) {
1196 if (Ordering == NotAtomic)
1199 switch (SynchScope) {
1200 case SingleThread: Out << " singlethread"; break;
1201 case CrossThread: break;
1205 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1206 case Unordered: Out << " unordered"; break;
1207 case Monotonic: Out << " monotonic"; break;
1208 case Acquire: Out << " acquire"; break;
1209 case Release: Out << " release"; break;
1210 case AcquireRelease: Out << " acq_rel"; break;
1211 case SequentiallyConsistent: Out << " seq_cst"; break;
1215 void AssemblyWriter::writeParamOperand(const Value *Operand,
1218 Out << "<null operand!>";
1223 TypePrinter.print(Operand->getType(), Out);
1224 // Print parameter attributes list
1225 if (Attrs != Attribute::None)
1226 Out << ' ' << Attribute::getAsString(Attrs);
1228 // Print the operand
1229 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1232 void AssemblyWriter::printModule(const Module *M) {
1233 if (!M->getModuleIdentifier().empty() &&
1234 // Don't print the ID if it will start a new line (which would
1235 // require a comment char before it).
1236 M->getModuleIdentifier().find('\n') == std::string::npos)
1237 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1239 if (!M->getDataLayout().empty())
1240 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1241 if (!M->getTargetTriple().empty())
1242 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1244 if (!M->getModuleInlineAsm().empty()) {
1245 // Split the string into lines, to make it easier to read the .ll file.
1246 std::string Asm = M->getModuleInlineAsm();
1248 size_t NewLine = Asm.find_first_of('\n', CurPos);
1250 while (NewLine != std::string::npos) {
1251 // We found a newline, print the portion of the asm string from the
1252 // last newline up to this newline.
1253 Out << "module asm \"";
1254 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1258 NewLine = Asm.find_first_of('\n', CurPos);
1260 std::string rest(Asm.begin()+CurPos, Asm.end());
1261 if (!rest.empty()) {
1262 Out << "module asm \"";
1263 PrintEscapedString(rest, Out);
1268 // Loop over the dependent libraries and emit them.
1269 Module::lib_iterator LI = M->lib_begin();
1270 Module::lib_iterator LE = M->lib_end();
1273 Out << "deplibs = [ ";
1275 Out << '"' << *LI << '"';
1283 printTypeIdentities();
1285 // Output all globals.
1286 if (!M->global_empty()) Out << '\n';
1287 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1291 // Output all aliases.
1292 if (!M->alias_empty()) Out << "\n";
1293 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1297 // Output all of the functions.
1298 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1301 // Output named metadata.
1302 if (!M->named_metadata_empty()) Out << '\n';
1304 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1305 E = M->named_metadata_end(); I != E; ++I)
1306 printNamedMDNode(I);
1309 if (!Machine.mdn_empty()) {
1315 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1317 StringRef Name = NMD->getName();
1319 Out << "<empty name> ";
1321 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1322 Name[0] == '.' || Name[0] == '_')
1325 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1326 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1327 unsigned char C = Name[i];
1328 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1331 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1335 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1337 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1347 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1348 formatted_raw_ostream &Out) {
1350 case GlobalValue::ExternalLinkage: break;
1351 case GlobalValue::PrivateLinkage: Out << "private "; break;
1352 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1353 case GlobalValue::LinkerPrivateWeakLinkage:
1354 Out << "linker_private_weak ";
1356 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1357 Out << "linker_private_weak_def_auto ";
1359 case GlobalValue::InternalLinkage: Out << "internal "; break;
1360 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1361 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1362 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1363 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1364 case GlobalValue::CommonLinkage: Out << "common "; break;
1365 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1366 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1367 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1368 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1369 case GlobalValue::AvailableExternallyLinkage:
1370 Out << "available_externally ";
1376 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1377 formatted_raw_ostream &Out) {
1379 case GlobalValue::DefaultVisibility: break;
1380 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1381 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1385 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1386 formatted_raw_ostream &Out) {
1388 case GlobalVariable::NotThreadLocal:
1390 case GlobalVariable::GeneralDynamicTLSModel:
1391 Out << "thread_local ";
1393 case GlobalVariable::LocalDynamicTLSModel:
1394 Out << "thread_local(localdynamic) ";
1396 case GlobalVariable::InitialExecTLSModel:
1397 Out << "thread_local(initialexec) ";
1399 case GlobalVariable::LocalExecTLSModel:
1400 Out << "thread_local(localexec) ";
1405 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1406 if (GV->isMaterializable())
1407 Out << "; Materializable\n";
1409 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1412 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1415 PrintLinkage(GV->getLinkage(), Out);
1416 PrintVisibility(GV->getVisibility(), Out);
1417 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1419 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1420 Out << "addrspace(" << AddressSpace << ") ";
1421 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1422 Out << (GV->isConstant() ? "constant " : "global ");
1423 TypePrinter.print(GV->getType()->getElementType(), Out);
1425 if (GV->hasInitializer()) {
1427 writeOperand(GV->getInitializer(), false);
1430 if (GV->hasSection()) {
1431 Out << ", section \"";
1432 PrintEscapedString(GV->getSection(), Out);
1435 if (GV->getAlignment())
1436 Out << ", align " << GV->getAlignment();
1438 printInfoComment(*GV);
1442 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1443 if (GA->isMaterializable())
1444 Out << "; Materializable\n";
1446 // Don't crash when dumping partially built GA
1448 Out << "<<nameless>> = ";
1450 PrintLLVMName(Out, GA);
1453 PrintVisibility(GA->getVisibility(), Out);
1457 PrintLinkage(GA->getLinkage(), Out);
1459 const Constant *Aliasee = GA->getAliasee();
1462 TypePrinter.print(GA->getType(), Out);
1463 Out << " <<NULL ALIASEE>>";
1465 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1468 printInfoComment(*GA);
1472 void AssemblyWriter::printTypeIdentities() {
1473 if (TypePrinter.NumberedTypes.empty() &&
1474 TypePrinter.NamedTypes.empty())
1479 // We know all the numbers that each type is used and we know that it is a
1480 // dense assignment. Convert the map to an index table.
1481 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1482 for (DenseMap<StructType*, unsigned>::iterator I =
1483 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1485 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1486 NumberedTypes[I->second] = I->first;
1489 // Emit all numbered types.
1490 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1491 Out << '%' << i << " = type ";
1493 // Make sure we print out at least one level of the type structure, so
1494 // that we do not get %2 = type %2
1495 TypePrinter.printStructBody(NumberedTypes[i], Out);
1499 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1500 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1503 // Make sure we print out at least one level of the type structure, so
1504 // that we do not get %FILE = type %FILE
1505 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1510 /// printFunction - Print all aspects of a function.
1512 void AssemblyWriter::printFunction(const Function *F) {
1513 // Print out the return type and name.
1516 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1518 if (F->isMaterializable())
1519 Out << "; Materializable\n";
1521 if (F->isDeclaration())
1526 PrintLinkage(F->getLinkage(), Out);
1527 PrintVisibility(F->getVisibility(), Out);
1529 // Print the calling convention.
1530 switch (F->getCallingConv()) {
1531 case CallingConv::C: break; // default
1532 case CallingConv::Fast: Out << "fastcc "; break;
1533 case CallingConv::Cold: Out << "coldcc "; break;
1534 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1535 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1536 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1537 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1538 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1539 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1540 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1541 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1542 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1543 default: Out << "cc" << F->getCallingConv() << " "; break;
1546 FunctionType *FT = F->getFunctionType();
1547 const AttrListPtr &Attrs = F->getAttributes();
1548 Attributes RetAttrs = Attrs.getRetAttributes();
1549 if (RetAttrs != Attribute::None)
1550 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1551 TypePrinter.print(F->getReturnType(), Out);
1553 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1555 Machine.incorporateFunction(F);
1557 // Loop over the arguments, printing them...
1560 if (!F->isDeclaration()) {
1561 // If this isn't a declaration, print the argument names as well.
1562 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1564 // Insert commas as we go... the first arg doesn't get a comma
1565 if (I != F->arg_begin()) Out << ", ";
1566 printArgument(I, Attrs.getParamAttributes(Idx));
1570 // Otherwise, print the types from the function type.
1571 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1572 // Insert commas as we go... the first arg doesn't get a comma
1576 TypePrinter.print(FT->getParamType(i), Out);
1578 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1579 if (ArgAttrs != Attribute::None)
1580 Out << ' ' << Attribute::getAsString(ArgAttrs);
1584 // Finish printing arguments...
1585 if (FT->isVarArg()) {
1586 if (FT->getNumParams()) Out << ", ";
1587 Out << "..."; // Output varargs portion of signature!
1590 if (F->hasUnnamedAddr())
1591 Out << " unnamed_addr";
1592 Attributes FnAttrs = Attrs.getFnAttributes();
1593 if (FnAttrs != Attribute::None)
1594 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1595 if (F->hasSection()) {
1596 Out << " section \"";
1597 PrintEscapedString(F->getSection(), Out);
1600 if (F->getAlignment())
1601 Out << " align " << F->getAlignment();
1603 Out << " gc \"" << F->getGC() << '"';
1604 if (F->isDeclaration()) {
1608 // Output all of the function's basic blocks.
1609 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1615 Machine.purgeFunction();
1618 /// printArgument - This member is called for every argument that is passed into
1619 /// the function. Simply print it out
1621 void AssemblyWriter::printArgument(const Argument *Arg,
1624 TypePrinter.print(Arg->getType(), Out);
1626 // Output parameter attributes list
1627 if (Attrs != Attribute::None)
1628 Out << ' ' << Attribute::getAsString(Attrs);
1630 // Output name, if available...
1631 if (Arg->hasName()) {
1633 PrintLLVMName(Out, Arg);
1637 /// printBasicBlock - This member is called for each basic block in a method.
1639 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1640 if (BB->hasName()) { // Print out the label if it exists...
1642 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1644 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1645 Out << "\n; <label>:";
1646 int Slot = Machine.getLocalSlot(BB);
1653 if (BB->getParent() == 0) {
1654 Out.PadToColumn(50);
1655 Out << "; Error: Block without parent!";
1656 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1657 // Output predecessors for the block.
1658 Out.PadToColumn(50);
1660 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1663 Out << " No predecessors!";
1666 writeOperand(*PI, false);
1667 for (++PI; PI != PE; ++PI) {
1669 writeOperand(*PI, false);
1676 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1678 // Output all of the instructions in the basic block...
1679 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1680 printInstruction(*I);
1684 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1687 /// printInfoComment - Print a little comment after the instruction indicating
1688 /// which slot it occupies.
1690 void AssemblyWriter::printInfoComment(const Value &V) {
1691 if (AnnotationWriter) {
1692 AnnotationWriter->printInfoComment(V, Out);
1697 // This member is called for each Instruction in a function..
1698 void AssemblyWriter::printInstruction(const Instruction &I) {
1699 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1701 // Print out indentation for an instruction.
1704 // Print out name if it exists...
1706 PrintLLVMName(Out, &I);
1708 } else if (!I.getType()->isVoidTy()) {
1709 // Print out the def slot taken.
1710 int SlotNum = Machine.getLocalSlot(&I);
1712 Out << "<badref> = ";
1714 Out << '%' << SlotNum << " = ";
1717 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1720 // Print out the opcode...
1721 Out << I.getOpcodeName();
1723 // If this is an atomic load or store, print out the atomic marker.
1724 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1725 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1728 // If this is a volatile operation, print out the volatile marker.
1729 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1730 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1731 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1732 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1735 // Print out optimization information.
1736 WriteOptimizationInfo(Out, &I);
1738 // Print out the compare instruction predicates
1739 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1740 Out << ' ' << getPredicateText(CI->getPredicate());
1742 // Print out the atomicrmw operation
1743 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1744 writeAtomicRMWOperation(Out, RMWI->getOperation());
1746 // Print out the type of the operands...
1747 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1749 // Special case conditional branches to swizzle the condition out to the front
1750 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1751 BranchInst &BI(cast<BranchInst>(I));
1753 writeOperand(BI.getCondition(), true);
1755 writeOperand(BI.getSuccessor(0), true);
1757 writeOperand(BI.getSuccessor(1), true);
1759 } else if (isa<SwitchInst>(I)) {
1760 SwitchInst& SI(cast<SwitchInst>(I));
1761 // Special case switch instruction to get formatting nice and correct.
1763 writeOperand(SI.getCondition(), true);
1765 writeOperand(SI.getDefaultDest(), true);
1767 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1770 writeOperand(i.getCaseValue(), true);
1772 writeOperand(i.getCaseSuccessor(), true);
1775 } else if (isa<IndirectBrInst>(I)) {
1776 // Special case indirectbr instruction to get formatting nice and correct.
1778 writeOperand(Operand, true);
1781 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1784 writeOperand(I.getOperand(i), true);
1787 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1789 TypePrinter.print(I.getType(), Out);
1792 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1793 if (op) Out << ", ";
1795 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1796 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1798 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1800 writeOperand(I.getOperand(0), true);
1801 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1803 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1805 writeOperand(I.getOperand(0), true); Out << ", ";
1806 writeOperand(I.getOperand(1), true);
1807 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1809 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1811 TypePrinter.print(I.getType(), Out);
1812 Out << " personality ";
1813 writeOperand(I.getOperand(0), true); Out << '\n';
1815 if (LPI->isCleanup())
1818 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1819 if (i != 0 || LPI->isCleanup()) Out << "\n";
1820 if (LPI->isCatch(i))
1825 writeOperand(LPI->getClause(i), true);
1827 } else if (isa<ReturnInst>(I) && !Operand) {
1829 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1830 // Print the calling convention being used.
1831 switch (CI->getCallingConv()) {
1832 case CallingConv::C: break; // default
1833 case CallingConv::Fast: Out << " fastcc"; break;
1834 case CallingConv::Cold: Out << " coldcc"; break;
1835 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1836 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1837 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1838 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1839 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1840 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1841 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1842 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1843 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1844 default: Out << " cc" << CI->getCallingConv(); break;
1847 Operand = CI->getCalledValue();
1848 PointerType *PTy = cast<PointerType>(Operand->getType());
1849 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1850 Type *RetTy = FTy->getReturnType();
1851 const AttrListPtr &PAL = CI->getAttributes();
1853 if (PAL.getRetAttributes() != Attribute::None)
1854 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1856 // If possible, print out the short form of the call instruction. We can
1857 // only do this if the first argument is a pointer to a nonvararg function,
1858 // and if the return type is not a pointer to a function.
1861 if (!FTy->isVarArg() &&
1862 (!RetTy->isPointerTy() ||
1863 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1864 TypePrinter.print(RetTy, Out);
1866 writeOperand(Operand, false);
1868 writeOperand(Operand, true);
1871 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1874 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1877 if (PAL.getFnAttributes() != Attribute::None)
1878 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1879 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1880 Operand = II->getCalledValue();
1881 PointerType *PTy = cast<PointerType>(Operand->getType());
1882 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1883 Type *RetTy = FTy->getReturnType();
1884 const AttrListPtr &PAL = II->getAttributes();
1886 // Print the calling convention being used.
1887 switch (II->getCallingConv()) {
1888 case CallingConv::C: break; // default
1889 case CallingConv::Fast: Out << " fastcc"; break;
1890 case CallingConv::Cold: Out << " coldcc"; break;
1891 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1892 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1893 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1894 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1895 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1896 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1897 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1898 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1899 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1900 default: Out << " cc" << II->getCallingConv(); break;
1903 if (PAL.getRetAttributes() != Attribute::None)
1904 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1906 // If possible, print out the short form of the invoke instruction. We can
1907 // only do this if the first argument is a pointer to a nonvararg function,
1908 // and if the return type is not a pointer to a function.
1911 if (!FTy->isVarArg() &&
1912 (!RetTy->isPointerTy() ||
1913 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1914 TypePrinter.print(RetTy, Out);
1916 writeOperand(Operand, false);
1918 writeOperand(Operand, true);
1921 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1924 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1928 if (PAL.getFnAttributes() != Attribute::None)
1929 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1932 writeOperand(II->getNormalDest(), true);
1934 writeOperand(II->getUnwindDest(), true);
1936 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1938 TypePrinter.print(AI->getType()->getElementType(), Out);
1939 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1941 writeOperand(AI->getArraySize(), true);
1943 if (AI->getAlignment()) {
1944 Out << ", align " << AI->getAlignment();
1946 } else if (isa<CastInst>(I)) {
1949 writeOperand(Operand, true); // Work with broken code
1952 TypePrinter.print(I.getType(), Out);
1953 } else if (isa<VAArgInst>(I)) {
1956 writeOperand(Operand, true); // Work with broken code
1959 TypePrinter.print(I.getType(), Out);
1960 } else if (Operand) { // Print the normal way.
1962 // PrintAllTypes - Instructions who have operands of all the same type
1963 // omit the type from all but the first operand. If the instruction has
1964 // different type operands (for example br), then they are all printed.
1965 bool PrintAllTypes = false;
1966 Type *TheType = Operand->getType();
1968 // Select, Store and ShuffleVector always print all types.
1969 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1970 || isa<ReturnInst>(I)) {
1971 PrintAllTypes = true;
1973 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1974 Operand = I.getOperand(i);
1975 // note that Operand shouldn't be null, but the test helps make dump()
1976 // more tolerant of malformed IR
1977 if (Operand && Operand->getType() != TheType) {
1978 PrintAllTypes = true; // We have differing types! Print them all!
1984 if (!PrintAllTypes) {
1986 TypePrinter.print(TheType, Out);
1990 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1992 writeOperand(I.getOperand(i), PrintAllTypes);
1996 // Print atomic ordering/alignment for memory operations
1997 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1999 writeAtomic(LI->getOrdering(), LI->getSynchScope());
2000 if (LI->getAlignment())
2001 Out << ", align " << LI->getAlignment();
2002 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2004 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2005 if (SI->getAlignment())
2006 Out << ", align " << SI->getAlignment();
2007 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2008 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
2009 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2010 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2011 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2012 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2015 // Print Metadata info.
2016 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2017 I.getAllMetadata(InstMD);
2018 if (!InstMD.empty()) {
2019 SmallVector<StringRef, 8> MDNames;
2020 I.getType()->getContext().getMDKindNames(MDNames);
2021 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2022 unsigned Kind = InstMD[i].first;
2023 if (Kind < MDNames.size()) {
2024 Out << ", !" << MDNames[Kind];
2026 Out << ", !<unknown kind #" << Kind << ">";
2029 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2033 printInfoComment(I);
2036 static void WriteMDNodeComment(const MDNode *Node,
2037 formatted_raw_ostream &Out) {
2038 if (Node->getNumOperands() < 1)
2041 Value *Op = Node->getOperand(0);
2042 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2045 DIDescriptor Desc(Node);
2046 if (Desc.getVersion() < LLVMDebugVersion11)
2049 unsigned Tag = Desc.getTag();
2050 Out.PadToColumn(50);
2051 if (dwarf::TagString(Tag)) {
2054 } else if (Tag == dwarf::DW_TAG_user_base) {
2055 Out << "; [ DW_TAG_user_base ]";
2059 void AssemblyWriter::writeAllMDNodes() {
2060 SmallVector<const MDNode *, 16> Nodes;
2061 Nodes.resize(Machine.mdn_size());
2062 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2064 Nodes[I->second] = cast<MDNode>(I->first);
2066 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2067 Out << '!' << i << " = metadata ";
2068 printMDNodeBody(Nodes[i]);
2072 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2073 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2074 WriteMDNodeComment(Node, Out);
2078 //===----------------------------------------------------------------------===//
2079 // External Interface declarations
2080 //===----------------------------------------------------------------------===//
2082 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2083 SlotTracker SlotTable(this);
2084 formatted_raw_ostream OS(ROS);
2085 AssemblyWriter W(OS, SlotTable, this, AAW);
2086 W.printModule(this);
2089 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2090 SlotTracker SlotTable(getParent());
2091 formatted_raw_ostream OS(ROS);
2092 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2093 W.printNamedMDNode(this);
2096 void Type::print(raw_ostream &OS) const {
2098 OS << "<null Type>";
2102 TP.print(const_cast<Type*>(this), OS);
2104 // If the type is a named struct type, print the body as well.
2105 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2106 if (!STy->isLiteral()) {
2108 TP.printStructBody(STy, OS);
2112 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2114 ROS << "printing a <null> value\n";
2117 formatted_raw_ostream OS(ROS);
2118 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2119 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2120 SlotTracker SlotTable(F);
2121 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2122 W.printInstruction(*I);
2123 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2124 SlotTracker SlotTable(BB->getParent());
2125 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2126 W.printBasicBlock(BB);
2127 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2128 SlotTracker SlotTable(GV->getParent());
2129 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2130 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2132 else if (const Function *F = dyn_cast<Function>(GV))
2135 W.printAlias(cast<GlobalAlias>(GV));
2136 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2137 const Function *F = N->getFunction();
2138 SlotTracker SlotTable(F);
2139 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2140 W.printMDNodeBody(N);
2141 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2142 TypePrinting TypePrinter;
2143 TypePrinter.print(C->getType(), OS);
2145 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2146 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2147 isa<Argument>(this)) {
2148 WriteAsOperand(OS, this, true, 0);
2150 // Otherwise we don't know what it is. Call the virtual function to
2151 // allow a subclass to print itself.
2156 // Value::printCustom - subclasses should override this to implement printing.
2157 void Value::printCustom(raw_ostream &OS) const {
2158 llvm_unreachable("Unknown value to print out!");
2161 // Value::dump - allow easy printing of Values from the debugger.
2162 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2164 // Type::dump - allow easy printing of Types from the debugger.
2165 void Type::dump() const { print(dbgs()); }
2167 // Module::dump() - Allow printing of Modules from the debugger.
2168 void Module::dump() const { print(dbgs(), 0); }
2170 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2171 void NamedMDNode::dump() const { print(dbgs(), 0); }