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->isLiteral())
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::HalfTyID: OS << "half"; break;
193 case Type::FloatTyID: OS << "float"; break;
194 case Type::DoubleTyID: OS << "double"; break;
195 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
196 case Type::FP128TyID: OS << "fp128"; break;
197 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
198 case Type::LabelTyID: OS << "label"; break;
199 case Type::MetadataTyID: OS << "metadata"; break;
200 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
201 case Type::IntegerTyID:
202 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
205 case Type::FunctionTyID: {
206 FunctionType *FTy = cast<FunctionType>(Ty);
207 print(FTy->getReturnType(), OS);
209 for (FunctionType::param_iterator I = FTy->param_begin(),
210 E = FTy->param_end(); I != E; ++I) {
211 if (I != FTy->param_begin())
215 if (FTy->isVarArg()) {
216 if (FTy->getNumParams()) OS << ", ";
222 case Type::StructTyID: {
223 StructType *STy = cast<StructType>(Ty);
225 if (STy->isLiteral())
226 return printStructBody(STy, OS);
228 if (!STy->getName().empty())
229 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
231 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
232 if (I != NumberedTypes.end())
233 OS << '%' << I->second;
234 else // Not enumerated, print the hex address.
235 OS << "%\"type " << STy << '\"';
238 case Type::PointerTyID: {
239 PointerType *PTy = cast<PointerType>(Ty);
240 print(PTy->getElementType(), OS);
241 if (unsigned AddressSpace = PTy->getAddressSpace())
242 OS << " addrspace(" << AddressSpace << ')';
246 case Type::ArrayTyID: {
247 ArrayType *ATy = cast<ArrayType>(Ty);
248 OS << '[' << ATy->getNumElements() << " x ";
249 print(ATy->getElementType(), OS);
253 case Type::VectorTyID: {
254 VectorType *PTy = cast<VectorType>(Ty);
255 OS << "<" << PTy->getNumElements() << " x ";
256 print(PTy->getElementType(), OS);
261 OS << "<unrecognized-type>";
266 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
267 if (STy->isOpaque()) {
275 if (STy->getNumElements() == 0) {
278 StructType::element_iterator I = STy->element_begin();
281 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
294 //===----------------------------------------------------------------------===//
295 // SlotTracker Class: Enumerate slot numbers for unnamed values
296 //===----------------------------------------------------------------------===//
300 /// This class provides computation of slot numbers for LLVM Assembly writing.
304 /// ValueMap - A mapping of Values to slot numbers.
305 typedef DenseMap<const Value*, unsigned> ValueMap;
308 /// TheModule - The module for which we are holding slot numbers.
309 const Module* TheModule;
311 /// TheFunction - The function for which we are holding slot numbers.
312 const Function* TheFunction;
313 bool FunctionProcessed;
315 /// mMap - The slot map for the module level data.
319 /// fMap - The slot map for the function level data.
323 /// mdnMap - Map for MDNodes.
324 DenseMap<const MDNode*, unsigned> mdnMap;
327 /// Construct from a module
328 explicit SlotTracker(const Module *M);
329 /// Construct from a function, starting out in incorp state.
330 explicit SlotTracker(const Function *F);
332 /// Return the slot number of the specified value in it's type
333 /// plane. If something is not in the SlotTracker, return -1.
334 int getLocalSlot(const Value *V);
335 int getGlobalSlot(const GlobalValue *V);
336 int getMetadataSlot(const MDNode *N);
338 /// If you'd like to deal with a function instead of just a module, use
339 /// this method to get its data into the SlotTracker.
340 void incorporateFunction(const Function *F) {
342 FunctionProcessed = false;
345 /// After calling incorporateFunction, use this method to remove the
346 /// most recently incorporated function from the SlotTracker. This
347 /// will reset the state of the machine back to just the module contents.
348 void purgeFunction();
350 /// MDNode map iterators.
351 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
352 mdn_iterator mdn_begin() { return mdnMap.begin(); }
353 mdn_iterator mdn_end() { return mdnMap.end(); }
354 unsigned mdn_size() const { return mdnMap.size(); }
355 bool mdn_empty() const { return mdnMap.empty(); }
357 /// This function does the actual initialization.
358 inline void initialize();
360 // Implementation Details
362 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
363 void CreateModuleSlot(const GlobalValue *V);
365 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
366 void CreateMetadataSlot(const MDNode *N);
368 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
369 void CreateFunctionSlot(const Value *V);
371 /// Add all of the module level global variables (and their initializers)
372 /// and function declarations, but not the contents of those functions.
373 void processModule();
375 /// Add all of the functions arguments, basic blocks, and instructions.
376 void processFunction();
378 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
379 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
382 } // end anonymous namespace
385 static SlotTracker *createSlotTracker(const Value *V) {
386 if (const Argument *FA = dyn_cast<Argument>(V))
387 return new SlotTracker(FA->getParent());
389 if (const Instruction *I = dyn_cast<Instruction>(V))
391 return new SlotTracker(I->getParent()->getParent());
393 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
394 return new SlotTracker(BB->getParent());
396 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
397 return new SlotTracker(GV->getParent());
399 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
400 return new SlotTracker(GA->getParent());
402 if (const Function *Func = dyn_cast<Function>(V))
403 return new SlotTracker(Func);
405 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
406 if (!MD->isFunctionLocal())
407 return new SlotTracker(MD->getFunction());
409 return new SlotTracker((Function *)0);
416 #define ST_DEBUG(X) dbgs() << X
421 // Module level constructor. Causes the contents of the Module (sans functions)
422 // to be added to the slot table.
423 SlotTracker::SlotTracker(const Module *M)
424 : TheModule(M), TheFunction(0), FunctionProcessed(false),
425 mNext(0), fNext(0), mdnNext(0) {
428 // Function level constructor. Causes the contents of the Module and the one
429 // function provided to be added to the slot table.
430 SlotTracker::SlotTracker(const Function *F)
431 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
432 mNext(0), fNext(0), mdnNext(0) {
435 inline void SlotTracker::initialize() {
438 TheModule = 0; ///< Prevent re-processing next time we're called.
441 if (TheFunction && !FunctionProcessed)
445 // Iterate through all the global variables, functions, and global
446 // variable initializers and create slots for them.
447 void SlotTracker::processModule() {
448 ST_DEBUG("begin processModule!\n");
450 // Add all of the unnamed global variables to the value table.
451 for (Module::const_global_iterator I = TheModule->global_begin(),
452 E = TheModule->global_end(); I != E; ++I) {
457 // Add metadata used by named metadata.
458 for (Module::const_named_metadata_iterator
459 I = TheModule->named_metadata_begin(),
460 E = TheModule->named_metadata_end(); I != E; ++I) {
461 const NamedMDNode *NMD = I;
462 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
463 CreateMetadataSlot(NMD->getOperand(i));
466 // Add all the unnamed functions to the table.
467 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
472 ST_DEBUG("end processModule!\n");
475 // Process the arguments, basic blocks, and instructions of a function.
476 void SlotTracker::processFunction() {
477 ST_DEBUG("begin processFunction!\n");
480 // Add all the function arguments with no names.
481 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
482 AE = TheFunction->arg_end(); AI != AE; ++AI)
484 CreateFunctionSlot(AI);
486 ST_DEBUG("Inserting Instructions:\n");
488 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
490 // Add all of the basic blocks and instructions with no names.
491 for (Function::const_iterator BB = TheFunction->begin(),
492 E = TheFunction->end(); BB != E; ++BB) {
494 CreateFunctionSlot(BB);
496 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
498 if (!I->getType()->isVoidTy() && !I->hasName())
499 CreateFunctionSlot(I);
501 // Intrinsics can directly use metadata. We allow direct calls to any
502 // llvm.foo function here, because the target may not be linked into the
504 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
505 if (Function *F = CI->getCalledFunction())
506 if (F->getName().startswith("llvm."))
507 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
508 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
509 CreateMetadataSlot(N);
512 // Process metadata attached with this instruction.
513 I->getAllMetadata(MDForInst);
514 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
515 CreateMetadataSlot(MDForInst[i].second);
520 FunctionProcessed = true;
522 ST_DEBUG("end processFunction!\n");
525 /// Clean up after incorporating a function. This is the only way to get out of
526 /// the function incorporation state that affects get*Slot/Create*Slot. Function
527 /// incorporation state is indicated by TheFunction != 0.
528 void SlotTracker::purgeFunction() {
529 ST_DEBUG("begin purgeFunction!\n");
530 fMap.clear(); // Simply discard the function level map
532 FunctionProcessed = false;
533 ST_DEBUG("end purgeFunction!\n");
536 /// getGlobalSlot - Get the slot number of a global value.
537 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
538 // Check for uninitialized state and do lazy initialization.
541 // Find the value in the module map
542 ValueMap::iterator MI = mMap.find(V);
543 return MI == mMap.end() ? -1 : (int)MI->second;
546 /// getMetadataSlot - Get the slot number of a MDNode.
547 int SlotTracker::getMetadataSlot(const MDNode *N) {
548 // Check for uninitialized state and do lazy initialization.
551 // Find the MDNode in the module map
552 mdn_iterator MI = mdnMap.find(N);
553 return MI == mdnMap.end() ? -1 : (int)MI->second;
557 /// getLocalSlot - Get the slot number for a value that is local to a function.
558 int SlotTracker::getLocalSlot(const Value *V) {
559 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
561 // Check for uninitialized state and do lazy initialization.
564 ValueMap::iterator FI = fMap.find(V);
565 return FI == fMap.end() ? -1 : (int)FI->second;
569 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
570 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
571 assert(V && "Can't insert a null Value into SlotTracker!");
572 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
573 assert(!V->hasName() && "Doesn't need a slot!");
575 unsigned DestSlot = mNext++;
578 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
580 // G = Global, F = Function, A = Alias, o = other
581 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
582 (isa<Function>(V) ? 'F' :
583 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
586 /// CreateSlot - Create a new slot for the specified value if it has no name.
587 void SlotTracker::CreateFunctionSlot(const Value *V) {
588 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
590 unsigned DestSlot = fNext++;
593 // G = Global, F = Function, o = other
594 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
595 DestSlot << " [o]\n");
598 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
599 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
600 assert(N && "Can't insert a null Value into SlotTracker!");
602 // Don't insert if N is a function-local metadata, these are always printed
604 if (!N->isFunctionLocal()) {
605 mdn_iterator I = mdnMap.find(N);
606 if (I != mdnMap.end())
609 unsigned DestSlot = mdnNext++;
610 mdnMap[N] = DestSlot;
613 // Recursively add any MDNodes referenced by operands.
614 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
615 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
616 CreateMetadataSlot(Op);
619 //===----------------------------------------------------------------------===//
620 // AsmWriter Implementation
621 //===----------------------------------------------------------------------===//
623 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
624 TypePrinting *TypePrinter,
625 SlotTracker *Machine,
626 const Module *Context);
630 static const char *getPredicateText(unsigned predicate) {
631 const char * pred = "unknown";
633 case FCmpInst::FCMP_FALSE: pred = "false"; break;
634 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
635 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
636 case FCmpInst::FCMP_OGE: pred = "oge"; break;
637 case FCmpInst::FCMP_OLT: pred = "olt"; break;
638 case FCmpInst::FCMP_OLE: pred = "ole"; break;
639 case FCmpInst::FCMP_ONE: pred = "one"; break;
640 case FCmpInst::FCMP_ORD: pred = "ord"; break;
641 case FCmpInst::FCMP_UNO: pred = "uno"; break;
642 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
643 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
644 case FCmpInst::FCMP_UGE: pred = "uge"; break;
645 case FCmpInst::FCMP_ULT: pred = "ult"; break;
646 case FCmpInst::FCMP_ULE: pred = "ule"; break;
647 case FCmpInst::FCMP_UNE: pred = "une"; break;
648 case FCmpInst::FCMP_TRUE: pred = "true"; break;
649 case ICmpInst::ICMP_EQ: pred = "eq"; break;
650 case ICmpInst::ICMP_NE: pred = "ne"; break;
651 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
652 case ICmpInst::ICMP_SGE: pred = "sge"; break;
653 case ICmpInst::ICMP_SLT: pred = "slt"; break;
654 case ICmpInst::ICMP_SLE: pred = "sle"; break;
655 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
656 case ICmpInst::ICMP_UGE: pred = "uge"; break;
657 case ICmpInst::ICMP_ULT: pred = "ult"; break;
658 case ICmpInst::ICMP_ULE: pred = "ule"; break;
663 static void writeAtomicRMWOperation(raw_ostream &Out,
664 AtomicRMWInst::BinOp Op) {
666 default: Out << " <unknown operation " << Op << ">"; break;
667 case AtomicRMWInst::Xchg: Out << " xchg"; break;
668 case AtomicRMWInst::Add: Out << " add"; break;
669 case AtomicRMWInst::Sub: Out << " sub"; break;
670 case AtomicRMWInst::And: Out << " and"; break;
671 case AtomicRMWInst::Nand: Out << " nand"; break;
672 case AtomicRMWInst::Or: Out << " or"; break;
673 case AtomicRMWInst::Xor: Out << " xor"; break;
674 case AtomicRMWInst::Max: Out << " max"; break;
675 case AtomicRMWInst::Min: Out << " min"; break;
676 case AtomicRMWInst::UMax: Out << " umax"; break;
677 case AtomicRMWInst::UMin: Out << " umin"; break;
681 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
682 if (const OverflowingBinaryOperator *OBO =
683 dyn_cast<OverflowingBinaryOperator>(U)) {
684 if (OBO->hasNoUnsignedWrap())
686 if (OBO->hasNoSignedWrap())
688 } else if (const PossiblyExactOperator *Div =
689 dyn_cast<PossiblyExactOperator>(U)) {
692 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
693 if (GEP->isInBounds())
698 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
699 TypePrinting &TypePrinter,
700 SlotTracker *Machine,
701 const Module *Context) {
702 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
703 if (CI->getType()->isIntegerTy(1)) {
704 Out << (CI->getZExtValue() ? "true" : "false");
707 Out << CI->getValue();
711 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
712 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf ||
713 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
714 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
715 // We would like to output the FP constant value in exponential notation,
716 // but we cannot do this if doing so will lose precision. Check here to
717 // make sure that we only output it in exponential format if we can parse
718 // the value back and get the same value.
721 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
722 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
724 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
725 CFP->getValueAPF().convertToFloat();
726 SmallString<128> StrVal;
727 raw_svector_ostream(StrVal) << Val;
729 // Check to make sure that the stringized number is not some string like
730 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
731 // that the string matches the "[-+]?[0-9]" regex.
733 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
734 ((StrVal[0] == '-' || StrVal[0] == '+') &&
735 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
736 // Reparse stringized version!
737 if (atof(StrVal.c_str()) == Val) {
743 // Otherwise we could not reparse it to exactly the same value, so we must
744 // output the string in hexadecimal format! Note that loading and storing
745 // floating point types changes the bits of NaNs on some hosts, notably
746 // x86, so we must not use these types.
747 assert(sizeof(double) == sizeof(uint64_t) &&
748 "assuming that double is 64 bits!");
750 APFloat apf = CFP->getValueAPF();
751 // Halves and floats are represented in ASCII IR as double, convert.
753 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
756 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
761 // Some form of long double. These appear as a magic letter identifying
762 // the type, then a fixed number of hex digits.
764 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
766 // api needed to prevent premature destruction
767 APInt api = CFP->getValueAPF().bitcastToAPInt();
768 const uint64_t* p = api.getRawData();
769 uint64_t word = p[1];
771 int width = api.getBitWidth();
772 for (int j=0; j<width; j+=4, shiftcount-=4) {
773 unsigned int nibble = (word>>shiftcount) & 15;
775 Out << (unsigned char)(nibble + '0');
777 Out << (unsigned char)(nibble - 10 + 'A');
778 if (shiftcount == 0 && j+4 < width) {
782 shiftcount = width-j-4;
786 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
788 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
791 llvm_unreachable("Unsupported floating point type");
792 // api needed to prevent premature destruction
793 APInt api = CFP->getValueAPF().bitcastToAPInt();
794 const uint64_t* p = api.getRawData();
797 int width = api.getBitWidth();
798 for (int j=0; j<width; j+=4, shiftcount-=4) {
799 unsigned int nibble = (word>>shiftcount) & 15;
801 Out << (unsigned char)(nibble + '0');
803 Out << (unsigned char)(nibble - 10 + 'A');
804 if (shiftcount == 0 && j+4 < width) {
808 shiftcount = width-j-4;
814 if (isa<ConstantAggregateZero>(CV)) {
815 Out << "zeroinitializer";
819 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
820 Out << "blockaddress(";
821 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
824 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
830 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
831 // As a special case, print the array as a string if it is an array of
832 // i8 with ConstantInt values.
834 Type *ETy = CA->getType()->getElementType();
835 if (CA->isString()) {
837 PrintEscapedString(CA->getAsString(), Out);
839 } else { // Cannot output in string format...
841 if (CA->getNumOperands()) {
842 TypePrinter.print(ETy, Out);
844 WriteAsOperandInternal(Out, CA->getOperand(0),
845 &TypePrinter, Machine,
847 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
849 TypePrinter.print(ETy, Out);
851 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
860 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
861 if (CS->getType()->isPacked())
864 unsigned N = CS->getNumOperands();
867 TypePrinter.print(CS->getOperand(0)->getType(), Out);
870 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
873 for (unsigned i = 1; i < N; i++) {
875 TypePrinter.print(CS->getOperand(i)->getType(), Out);
878 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
885 if (CS->getType()->isPacked())
890 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
891 Type *ETy = CP->getType()->getElementType();
892 assert(CP->getNumOperands() > 0 &&
893 "Number of operands for a PackedConst must be > 0");
895 TypePrinter.print(ETy, Out);
897 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
899 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
901 TypePrinter.print(ETy, Out);
903 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
910 if (isa<ConstantPointerNull>(CV)) {
915 if (isa<UndefValue>(CV)) {
920 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
921 Out << CE->getOpcodeName();
922 WriteOptimizationInfo(Out, CE);
924 Out << ' ' << getPredicateText(CE->getPredicate());
927 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
928 TypePrinter.print((*OI)->getType(), Out);
930 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
931 if (OI+1 != CE->op_end())
935 if (CE->hasIndices()) {
936 ArrayRef<unsigned> Indices = CE->getIndices();
937 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
938 Out << ", " << Indices[i];
943 TypePrinter.print(CE->getType(), Out);
950 Out << "<placeholder or erroneous Constant>";
953 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
954 TypePrinting *TypePrinter,
955 SlotTracker *Machine,
956 const Module *Context) {
958 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
959 const Value *V = Node->getOperand(mi);
963 TypePrinter->print(V->getType(), Out);
965 WriteAsOperandInternal(Out, Node->getOperand(mi),
966 TypePrinter, Machine, Context);
976 /// WriteAsOperand - Write the name of the specified value out to the specified
977 /// ostream. This can be useful when you just want to print int %reg126, not
978 /// the whole instruction that generated it.
980 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
981 TypePrinting *TypePrinter,
982 SlotTracker *Machine,
983 const Module *Context) {
985 PrintLLVMName(Out, V);
989 const Constant *CV = dyn_cast<Constant>(V);
990 if (CV && !isa<GlobalValue>(CV)) {
991 assert(TypePrinter && "Constants require TypePrinting!");
992 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
996 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
998 if (IA->hasSideEffects())
999 Out << "sideeffect ";
1000 if (IA->isAlignStack())
1001 Out << "alignstack ";
1003 PrintEscapedString(IA->getAsmString(), Out);
1005 PrintEscapedString(IA->getConstraintString(), Out);
1010 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1011 if (N->isFunctionLocal()) {
1012 // Print metadata inline, not via slot reference number.
1013 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1018 if (N->isFunctionLocal())
1019 Machine = new SlotTracker(N->getFunction());
1021 Machine = new SlotTracker(Context);
1023 int Slot = Machine->getMetadataSlot(N);
1031 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1033 PrintEscapedString(MDS->getString(), Out);
1038 if (V->getValueID() == Value::PseudoSourceValueVal ||
1039 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1046 // If we have a SlotTracker, use it.
1048 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1049 Slot = Machine->getGlobalSlot(GV);
1052 Slot = Machine->getLocalSlot(V);
1054 // If the local value didn't succeed, then we may be referring to a value
1055 // from a different function. Translate it, as this can happen when using
1056 // address of blocks.
1058 if ((Machine = createSlotTracker(V))) {
1059 Slot = Machine->getLocalSlot(V);
1063 } else if ((Machine = createSlotTracker(V))) {
1064 // Otherwise, create one to get the # and then destroy it.
1065 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1066 Slot = Machine->getGlobalSlot(GV);
1069 Slot = Machine->getLocalSlot(V);
1078 Out << Prefix << Slot;
1083 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1084 bool PrintType, const Module *Context) {
1086 // Fast path: Don't construct and populate a TypePrinting object if we
1087 // won't be needing any types printed.
1089 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1090 V->hasName() || isa<GlobalValue>(V))) {
1091 WriteAsOperandInternal(Out, V, 0, 0, Context);
1095 if (Context == 0) Context = getModuleFromVal(V);
1097 TypePrinting TypePrinter;
1099 TypePrinter.incorporateTypes(*Context);
1101 TypePrinter.print(V->getType(), Out);
1105 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1110 class AssemblyWriter {
1111 formatted_raw_ostream &Out;
1112 SlotTracker &Machine;
1113 const Module *TheModule;
1114 TypePrinting TypePrinter;
1115 AssemblyAnnotationWriter *AnnotationWriter;
1118 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1120 AssemblyAnnotationWriter *AAW)
1121 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1123 TypePrinter.incorporateTypes(*M);
1126 void printMDNodeBody(const MDNode *MD);
1127 void printNamedMDNode(const NamedMDNode *NMD);
1129 void printModule(const Module *M);
1131 void writeOperand(const Value *Op, bool PrintType);
1132 void writeParamOperand(const Value *Operand, Attributes Attrs);
1133 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1135 void writeAllMDNodes();
1137 void printTypeIdentities();
1138 void printGlobal(const GlobalVariable *GV);
1139 void printAlias(const GlobalAlias *GV);
1140 void printFunction(const Function *F);
1141 void printArgument(const Argument *FA, Attributes Attrs);
1142 void printBasicBlock(const BasicBlock *BB);
1143 void printInstruction(const Instruction &I);
1146 // printInfoComment - Print a little comment after the instruction indicating
1147 // which slot it occupies.
1148 void printInfoComment(const Value &V);
1150 } // end of anonymous namespace
1152 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1154 Out << "<null operand!>";
1158 TypePrinter.print(Operand->getType(), Out);
1161 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1164 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1165 SynchronizationScope SynchScope) {
1166 if (Ordering == NotAtomic)
1169 switch (SynchScope) {
1170 default: Out << " <bad scope " << int(SynchScope) << ">"; break;
1171 case SingleThread: Out << " singlethread"; break;
1172 case CrossThread: break;
1176 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1177 case Unordered: Out << " unordered"; break;
1178 case Monotonic: Out << " monotonic"; break;
1179 case Acquire: Out << " acquire"; break;
1180 case Release: Out << " release"; break;
1181 case AcquireRelease: Out << " acq_rel"; break;
1182 case SequentiallyConsistent: Out << " seq_cst"; break;
1186 void AssemblyWriter::writeParamOperand(const Value *Operand,
1189 Out << "<null operand!>";
1194 TypePrinter.print(Operand->getType(), Out);
1195 // Print parameter attributes list
1196 if (Attrs != Attribute::None)
1197 Out << ' ' << Attribute::getAsString(Attrs);
1199 // Print the operand
1200 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1203 void AssemblyWriter::printModule(const Module *M) {
1204 if (!M->getModuleIdentifier().empty() &&
1205 // Don't print the ID if it will start a new line (which would
1206 // require a comment char before it).
1207 M->getModuleIdentifier().find('\n') == std::string::npos)
1208 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1210 if (!M->getDataLayout().empty())
1211 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1212 if (!M->getTargetTriple().empty())
1213 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1215 if (!M->getModuleInlineAsm().empty()) {
1216 // Split the string into lines, to make it easier to read the .ll file.
1217 std::string Asm = M->getModuleInlineAsm();
1219 size_t NewLine = Asm.find_first_of('\n', CurPos);
1221 while (NewLine != std::string::npos) {
1222 // We found a newline, print the portion of the asm string from the
1223 // last newline up to this newline.
1224 Out << "module asm \"";
1225 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1229 NewLine = Asm.find_first_of('\n', CurPos);
1231 std::string rest(Asm.begin()+CurPos, Asm.end());
1232 if (!rest.empty()) {
1233 Out << "module asm \"";
1234 PrintEscapedString(rest, Out);
1239 // Loop over the dependent libraries and emit them.
1240 Module::lib_iterator LI = M->lib_begin();
1241 Module::lib_iterator LE = M->lib_end();
1244 Out << "deplibs = [ ";
1246 Out << '"' << *LI << '"';
1254 printTypeIdentities();
1256 // Output all globals.
1257 if (!M->global_empty()) Out << '\n';
1258 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1262 // Output all aliases.
1263 if (!M->alias_empty()) Out << "\n";
1264 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1268 // Output all of the functions.
1269 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1272 // Output named metadata.
1273 if (!M->named_metadata_empty()) Out << '\n';
1275 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1276 E = M->named_metadata_end(); I != E; ++I)
1277 printNamedMDNode(I);
1280 if (!Machine.mdn_empty()) {
1286 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1288 StringRef Name = NMD->getName();
1290 Out << "<empty name> ";
1292 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1293 Name[0] == '.' || Name[0] == '_')
1296 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1297 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1298 unsigned char C = Name[i];
1299 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1302 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1306 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1308 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1318 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1319 formatted_raw_ostream &Out) {
1321 case GlobalValue::ExternalLinkage: break;
1322 case GlobalValue::PrivateLinkage: Out << "private "; break;
1323 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1324 case GlobalValue::LinkerPrivateWeakLinkage:
1325 Out << "linker_private_weak ";
1327 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1328 Out << "linker_private_weak_def_auto ";
1330 case GlobalValue::InternalLinkage: Out << "internal "; break;
1331 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1332 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1333 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1334 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1335 case GlobalValue::CommonLinkage: Out << "common "; break;
1336 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1337 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1338 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1339 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1340 case GlobalValue::AvailableExternallyLinkage:
1341 Out << "available_externally ";
1347 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1348 formatted_raw_ostream &Out) {
1350 case GlobalValue::DefaultVisibility: break;
1351 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1352 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1356 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1357 if (GV->isMaterializable())
1358 Out << "; Materializable\n";
1360 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1363 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1366 PrintLinkage(GV->getLinkage(), Out);
1367 PrintVisibility(GV->getVisibility(), Out);
1369 if (GV->isThreadLocal()) Out << "thread_local ";
1370 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1371 Out << "addrspace(" << AddressSpace << ") ";
1372 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1373 Out << (GV->isConstant() ? "constant " : "global ");
1374 TypePrinter.print(GV->getType()->getElementType(), Out);
1376 if (GV->hasInitializer()) {
1378 writeOperand(GV->getInitializer(), false);
1381 if (GV->hasSection()) {
1382 Out << ", section \"";
1383 PrintEscapedString(GV->getSection(), Out);
1386 if (GV->getAlignment())
1387 Out << ", align " << GV->getAlignment();
1389 printInfoComment(*GV);
1393 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1394 if (GA->isMaterializable())
1395 Out << "; Materializable\n";
1397 // Don't crash when dumping partially built GA
1399 Out << "<<nameless>> = ";
1401 PrintLLVMName(Out, GA);
1404 PrintVisibility(GA->getVisibility(), Out);
1408 PrintLinkage(GA->getLinkage(), Out);
1410 const Constant *Aliasee = GA->getAliasee();
1413 TypePrinter.print(GA->getType(), Out);
1414 Out << " <<NULL ALIASEE>>";
1416 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1419 printInfoComment(*GA);
1423 void AssemblyWriter::printTypeIdentities() {
1424 if (TypePrinter.NumberedTypes.empty() &&
1425 TypePrinter.NamedTypes.empty())
1430 // We know all the numbers that each type is used and we know that it is a
1431 // dense assignment. Convert the map to an index table.
1432 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1433 for (DenseMap<StructType*, unsigned>::iterator I =
1434 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1436 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1437 NumberedTypes[I->second] = I->first;
1440 // Emit all numbered types.
1441 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1442 Out << '%' << i << " = type ";
1444 // Make sure we print out at least one level of the type structure, so
1445 // that we do not get %2 = type %2
1446 TypePrinter.printStructBody(NumberedTypes[i], Out);
1450 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1451 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1454 // Make sure we print out at least one level of the type structure, so
1455 // that we do not get %FILE = type %FILE
1456 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1461 /// printFunction - Print all aspects of a function.
1463 void AssemblyWriter::printFunction(const Function *F) {
1464 // Print out the return type and name.
1467 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1469 if (F->isMaterializable())
1470 Out << "; Materializable\n";
1472 if (F->isDeclaration())
1477 PrintLinkage(F->getLinkage(), Out);
1478 PrintVisibility(F->getVisibility(), Out);
1480 // Print the calling convention.
1481 switch (F->getCallingConv()) {
1482 case CallingConv::C: break; // default
1483 case CallingConv::Fast: Out << "fastcc "; break;
1484 case CallingConv::Cold: Out << "coldcc "; break;
1485 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1486 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1487 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1488 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1489 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1490 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1491 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1492 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1493 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1494 default: Out << "cc" << F->getCallingConv() << " "; break;
1497 FunctionType *FT = F->getFunctionType();
1498 const AttrListPtr &Attrs = F->getAttributes();
1499 Attributes RetAttrs = Attrs.getRetAttributes();
1500 if (RetAttrs != Attribute::None)
1501 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1502 TypePrinter.print(F->getReturnType(), Out);
1504 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1506 Machine.incorporateFunction(F);
1508 // Loop over the arguments, printing them...
1511 if (!F->isDeclaration()) {
1512 // If this isn't a declaration, print the argument names as well.
1513 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1515 // Insert commas as we go... the first arg doesn't get a comma
1516 if (I != F->arg_begin()) Out << ", ";
1517 printArgument(I, Attrs.getParamAttributes(Idx));
1521 // Otherwise, print the types from the function type.
1522 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1523 // Insert commas as we go... the first arg doesn't get a comma
1527 TypePrinter.print(FT->getParamType(i), Out);
1529 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1530 if (ArgAttrs != Attribute::None)
1531 Out << ' ' << Attribute::getAsString(ArgAttrs);
1535 // Finish printing arguments...
1536 if (FT->isVarArg()) {
1537 if (FT->getNumParams()) Out << ", ";
1538 Out << "..."; // Output varargs portion of signature!
1541 if (F->hasUnnamedAddr())
1542 Out << " unnamed_addr";
1543 Attributes FnAttrs = Attrs.getFnAttributes();
1544 if (FnAttrs != Attribute::None)
1545 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1546 if (F->hasSection()) {
1547 Out << " section \"";
1548 PrintEscapedString(F->getSection(), Out);
1551 if (F->getAlignment())
1552 Out << " align " << F->getAlignment();
1554 Out << " gc \"" << F->getGC() << '"';
1555 if (F->isDeclaration()) {
1559 // Output all of the function's basic blocks.
1560 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1566 Machine.purgeFunction();
1569 /// printArgument - This member is called for every argument that is passed into
1570 /// the function. Simply print it out
1572 void AssemblyWriter::printArgument(const Argument *Arg,
1575 TypePrinter.print(Arg->getType(), Out);
1577 // Output parameter attributes list
1578 if (Attrs != Attribute::None)
1579 Out << ' ' << Attribute::getAsString(Attrs);
1581 // Output name, if available...
1582 if (Arg->hasName()) {
1584 PrintLLVMName(Out, Arg);
1588 /// printBasicBlock - This member is called for each basic block in a method.
1590 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1591 if (BB->hasName()) { // Print out the label if it exists...
1593 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1595 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1596 Out << "\n; <label>:";
1597 int Slot = Machine.getLocalSlot(BB);
1604 if (BB->getParent() == 0) {
1605 Out.PadToColumn(50);
1606 Out << "; Error: Block without parent!";
1607 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1608 // Output predecessors for the block.
1609 Out.PadToColumn(50);
1611 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1614 Out << " No predecessors!";
1617 writeOperand(*PI, false);
1618 for (++PI; PI != PE; ++PI) {
1620 writeOperand(*PI, false);
1627 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1629 // Output all of the instructions in the basic block...
1630 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1631 printInstruction(*I);
1635 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1638 /// printInfoComment - Print a little comment after the instruction indicating
1639 /// which slot it occupies.
1641 void AssemblyWriter::printInfoComment(const Value &V) {
1642 if (AnnotationWriter) {
1643 AnnotationWriter->printInfoComment(V, Out);
1648 // This member is called for each Instruction in a function..
1649 void AssemblyWriter::printInstruction(const Instruction &I) {
1650 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1652 // Print out indentation for an instruction.
1655 // Print out name if it exists...
1657 PrintLLVMName(Out, &I);
1659 } else if (!I.getType()->isVoidTy()) {
1660 // Print out the def slot taken.
1661 int SlotNum = Machine.getLocalSlot(&I);
1663 Out << "<badref> = ";
1665 Out << '%' << SlotNum << " = ";
1668 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1671 // Print out the opcode...
1672 Out << I.getOpcodeName();
1674 // If this is an atomic load or store, print out the atomic marker.
1675 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1676 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1679 // If this is a volatile operation, print out the volatile marker.
1680 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1681 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1682 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1683 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1686 // Print out optimization information.
1687 WriteOptimizationInfo(Out, &I);
1689 // Print out the compare instruction predicates
1690 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1691 Out << ' ' << getPredicateText(CI->getPredicate());
1693 // Print out the atomicrmw operation
1694 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1695 writeAtomicRMWOperation(Out, RMWI->getOperation());
1697 // Print out the type of the operands...
1698 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1700 // Special case conditional branches to swizzle the condition out to the front
1701 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1702 BranchInst &BI(cast<BranchInst>(I));
1704 writeOperand(BI.getCondition(), true);
1706 writeOperand(BI.getSuccessor(0), true);
1708 writeOperand(BI.getSuccessor(1), true);
1710 } else if (isa<SwitchInst>(I)) {
1711 SwitchInst& SI(cast<SwitchInst>(I));
1712 // Special case switch instruction to get formatting nice and correct.
1714 writeOperand(SI.getCondition(), true);
1716 writeOperand(SI.getDefaultDest(), true);
1718 // Skip the first item since that's the default case.
1719 unsigned NumCases = SI.getNumCases();
1720 for (unsigned i = 1; i < NumCases; ++i) {
1722 writeOperand(SI.getCaseValue(i), true);
1724 writeOperand(SI.getSuccessor(i), true);
1727 } else if (isa<IndirectBrInst>(I)) {
1728 // Special case indirectbr instruction to get formatting nice and correct.
1730 writeOperand(Operand, true);
1733 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1736 writeOperand(I.getOperand(i), true);
1739 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1741 TypePrinter.print(I.getType(), Out);
1744 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1745 if (op) Out << ", ";
1747 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1748 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1750 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1752 writeOperand(I.getOperand(0), true);
1753 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1755 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1757 writeOperand(I.getOperand(0), true); Out << ", ";
1758 writeOperand(I.getOperand(1), true);
1759 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1761 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1763 TypePrinter.print(I.getType(), Out);
1764 Out << " personality ";
1765 writeOperand(I.getOperand(0), true); Out << '\n';
1767 if (LPI->isCleanup())
1770 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1771 if (i != 0 || LPI->isCleanup()) Out << "\n";
1772 if (LPI->isCatch(i))
1777 writeOperand(LPI->getClause(i), true);
1779 } else if (isa<ReturnInst>(I) && !Operand) {
1781 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1782 // Print the calling convention being used.
1783 switch (CI->getCallingConv()) {
1784 case CallingConv::C: break; // default
1785 case CallingConv::Fast: Out << " fastcc"; break;
1786 case CallingConv::Cold: Out << " coldcc"; break;
1787 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1788 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1789 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1790 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1791 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1792 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1793 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1794 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1795 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1796 default: Out << " cc" << CI->getCallingConv(); break;
1799 Operand = CI->getCalledValue();
1800 PointerType *PTy = cast<PointerType>(Operand->getType());
1801 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1802 Type *RetTy = FTy->getReturnType();
1803 const AttrListPtr &PAL = CI->getAttributes();
1805 if (PAL.getRetAttributes() != Attribute::None)
1806 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1808 // If possible, print out the short form of the call instruction. We can
1809 // only do this if the first argument is a pointer to a nonvararg function,
1810 // and if the return type is not a pointer to a function.
1813 if (!FTy->isVarArg() &&
1814 (!RetTy->isPointerTy() ||
1815 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1816 TypePrinter.print(RetTy, Out);
1818 writeOperand(Operand, false);
1820 writeOperand(Operand, true);
1823 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1826 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1829 if (PAL.getFnAttributes() != Attribute::None)
1830 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1831 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1832 Operand = II->getCalledValue();
1833 PointerType *PTy = cast<PointerType>(Operand->getType());
1834 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1835 Type *RetTy = FTy->getReturnType();
1836 const AttrListPtr &PAL = II->getAttributes();
1838 // Print the calling convention being used.
1839 switch (II->getCallingConv()) {
1840 case CallingConv::C: break; // default
1841 case CallingConv::Fast: Out << " fastcc"; break;
1842 case CallingConv::Cold: Out << " coldcc"; break;
1843 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1844 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1845 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1846 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1847 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1848 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1849 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1850 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1851 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1852 default: Out << " cc" << II->getCallingConv(); break;
1855 if (PAL.getRetAttributes() != Attribute::None)
1856 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1858 // If possible, print out the short form of the invoke instruction. We can
1859 // only do this if the first argument is a pointer to a nonvararg function,
1860 // and if the return type is not a pointer to a function.
1863 if (!FTy->isVarArg() &&
1864 (!RetTy->isPointerTy() ||
1865 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1866 TypePrinter.print(RetTy, Out);
1868 writeOperand(Operand, false);
1870 writeOperand(Operand, true);
1873 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1876 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1880 if (PAL.getFnAttributes() != Attribute::None)
1881 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1884 writeOperand(II->getNormalDest(), true);
1886 writeOperand(II->getUnwindDest(), true);
1888 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1890 TypePrinter.print(AI->getType()->getElementType(), Out);
1891 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1893 writeOperand(AI->getArraySize(), true);
1895 if (AI->getAlignment()) {
1896 Out << ", align " << AI->getAlignment();
1898 } else if (isa<CastInst>(I)) {
1901 writeOperand(Operand, true); // Work with broken code
1904 TypePrinter.print(I.getType(), Out);
1905 } else if (isa<VAArgInst>(I)) {
1908 writeOperand(Operand, true); // Work with broken code
1911 TypePrinter.print(I.getType(), Out);
1912 } else if (Operand) { // Print the normal way.
1914 // PrintAllTypes - Instructions who have operands of all the same type
1915 // omit the type from all but the first operand. If the instruction has
1916 // different type operands (for example br), then they are all printed.
1917 bool PrintAllTypes = false;
1918 Type *TheType = Operand->getType();
1920 // Select, Store and ShuffleVector always print all types.
1921 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1922 || isa<ReturnInst>(I)) {
1923 PrintAllTypes = true;
1925 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1926 Operand = I.getOperand(i);
1927 // note that Operand shouldn't be null, but the test helps make dump()
1928 // more tolerant of malformed IR
1929 if (Operand && Operand->getType() != TheType) {
1930 PrintAllTypes = true; // We have differing types! Print them all!
1936 if (!PrintAllTypes) {
1938 TypePrinter.print(TheType, Out);
1942 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1944 writeOperand(I.getOperand(i), PrintAllTypes);
1948 // Print atomic ordering/alignment for memory operations
1949 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1951 writeAtomic(LI->getOrdering(), LI->getSynchScope());
1952 if (LI->getAlignment())
1953 Out << ", align " << LI->getAlignment();
1954 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1956 writeAtomic(SI->getOrdering(), SI->getSynchScope());
1957 if (SI->getAlignment())
1958 Out << ", align " << SI->getAlignment();
1959 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
1960 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
1961 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
1962 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
1963 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
1964 writeAtomic(FI->getOrdering(), FI->getSynchScope());
1967 // Print Metadata info.
1968 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1969 I.getAllMetadata(InstMD);
1970 if (!InstMD.empty()) {
1971 SmallVector<StringRef, 8> MDNames;
1972 I.getType()->getContext().getMDKindNames(MDNames);
1973 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1974 unsigned Kind = InstMD[i].first;
1975 if (Kind < MDNames.size()) {
1976 Out << ", !" << MDNames[Kind];
1978 Out << ", !<unknown kind #" << Kind << ">";
1981 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
1985 printInfoComment(I);
1988 static void WriteMDNodeComment(const MDNode *Node,
1989 formatted_raw_ostream &Out) {
1990 if (Node->getNumOperands() < 1)
1992 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1994 APInt Val = CI->getValue();
1995 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
1996 if (Val.ult(LLVMDebugVersion))
1999 Out.PadToColumn(50);
2000 if (Tag == dwarf::DW_TAG_user_base)
2001 Out << "; [ DW_TAG_user_base ]";
2002 else if (Tag.isIntN(32)) {
2003 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2004 Out << "; [ " << TagName << " ]";
2008 void AssemblyWriter::writeAllMDNodes() {
2009 SmallVector<const MDNode *, 16> Nodes;
2010 Nodes.resize(Machine.mdn_size());
2011 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2013 Nodes[I->second] = cast<MDNode>(I->first);
2015 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2016 Out << '!' << i << " = metadata ";
2017 printMDNodeBody(Nodes[i]);
2021 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2022 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2023 WriteMDNodeComment(Node, Out);
2027 //===----------------------------------------------------------------------===//
2028 // External Interface declarations
2029 //===----------------------------------------------------------------------===//
2031 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2032 SlotTracker SlotTable(this);
2033 formatted_raw_ostream OS(ROS);
2034 AssemblyWriter W(OS, SlotTable, this, AAW);
2035 W.printModule(this);
2038 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2039 SlotTracker SlotTable(getParent());
2040 formatted_raw_ostream OS(ROS);
2041 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2042 W.printNamedMDNode(this);
2045 void Type::print(raw_ostream &OS) const {
2047 OS << "<null Type>";
2051 TP.print(const_cast<Type*>(this), OS);
2053 // If the type is a named struct type, print the body as well.
2054 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2055 if (!STy->isLiteral()) {
2057 TP.printStructBody(STy, OS);
2061 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2063 ROS << "printing a <null> value\n";
2066 formatted_raw_ostream OS(ROS);
2067 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2068 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2069 SlotTracker SlotTable(F);
2070 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2071 W.printInstruction(*I);
2072 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2073 SlotTracker SlotTable(BB->getParent());
2074 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2075 W.printBasicBlock(BB);
2076 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2077 SlotTracker SlotTable(GV->getParent());
2078 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2079 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2081 else if (const Function *F = dyn_cast<Function>(GV))
2084 W.printAlias(cast<GlobalAlias>(GV));
2085 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2086 const Function *F = N->getFunction();
2087 SlotTracker SlotTable(F);
2088 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2089 W.printMDNodeBody(N);
2090 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2091 TypePrinting TypePrinter;
2092 TypePrinter.print(C->getType(), OS);
2094 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2095 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2096 isa<Argument>(this)) {
2097 WriteAsOperand(OS, this, true, 0);
2099 // Otherwise we don't know what it is. Call the virtual function to
2100 // allow a subclass to print itself.
2105 // Value::printCustom - subclasses should override this to implement printing.
2106 void Value::printCustom(raw_ostream &OS) const {
2107 llvm_unreachable("Unknown value to print out!");
2110 // Value::dump - allow easy printing of Values from the debugger.
2111 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2113 // Type::dump - allow easy printing of Types from the debugger.
2114 void Type::dump() const { print(dbgs()); }
2116 // Module::dump() - Allow printing of Modules from the debugger.
2117 void Module::dump() const { print(dbgs(), 0); }
2119 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2120 void NamedMDNode::dump() const { print(dbgs(), 0); }