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!");
93 case GlobalPrefix: OS << '@'; break;
94 case LabelPrefix: break;
95 case LocalPrefix: OS << '%'; break;
98 // Scan the name to see if it needs quotes first.
99 bool NeedsQuotes = isdigit(Name[0]);
101 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
103 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
110 // If we didn't need any quotes, just write out the name in one blast.
116 // Okay, we need quotes. Output the quotes and escape any scary characters as
119 PrintEscapedString(Name, OS);
123 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
124 /// prefixed with % (if the string only contains simple characters) or is
125 /// surrounded with ""'s (if it has special chars in it). Print it out.
126 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
127 PrintLLVMName(OS, V->getName(),
128 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
131 //===----------------------------------------------------------------------===//
132 // TypePrinting Class: Type printing machinery
133 //===----------------------------------------------------------------------===//
135 /// TypePrinting - Type printing machinery.
138 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
139 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
142 /// NamedTypes - The named types that are used by the current module.
143 std::vector<StructType*> NamedTypes;
145 /// NumberedTypes - The numbered types, along with their value.
146 DenseMap<StructType*, unsigned> NumberedTypes;
152 void incorporateTypes(const Module &M);
154 void print(Type *Ty, raw_ostream &OS);
156 void printStructBody(StructType *Ty, raw_ostream &OS);
158 } // end anonymous namespace.
161 void TypePrinting::incorporateTypes(const Module &M) {
162 M.findUsedStructTypes(NamedTypes);
164 // The list of struct types we got back includes all the struct types, split
165 // the unnamed ones out to a numbering and remove the anonymous structs.
166 unsigned NextNumber = 0;
168 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
169 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
170 StructType *STy = *I;
172 // Ignore anonymous types.
173 if (STy->isLiteral())
176 if (STy->getName().empty())
177 NumberedTypes[STy] = NextNumber++;
182 NamedTypes.erase(NextToUse, NamedTypes.end());
186 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
187 /// use of type names or up references to shorten the type name where possible.
188 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
189 switch (Ty->getTypeID()) {
190 case Type::VoidTyID: OS << "void"; break;
191 case Type::HalfTyID: OS << "half"; break;
192 case Type::FloatTyID: OS << "float"; break;
193 case Type::DoubleTyID: OS << "double"; break;
194 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
195 case Type::FP128TyID: OS << "fp128"; break;
196 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
197 case Type::LabelTyID: OS << "label"; break;
198 case Type::MetadataTyID: OS << "metadata"; break;
199 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
200 case Type::IntegerTyID:
201 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
204 case Type::FunctionTyID: {
205 FunctionType *FTy = cast<FunctionType>(Ty);
206 print(FTy->getReturnType(), OS);
208 for (FunctionType::param_iterator I = FTy->param_begin(),
209 E = FTy->param_end(); I != E; ++I) {
210 if (I != FTy->param_begin())
214 if (FTy->isVarArg()) {
215 if (FTy->getNumParams()) OS << ", ";
221 case Type::StructTyID: {
222 StructType *STy = cast<StructType>(Ty);
224 if (STy->isLiteral())
225 return printStructBody(STy, OS);
227 if (!STy->getName().empty())
228 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
230 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
231 if (I != NumberedTypes.end())
232 OS << '%' << I->second;
233 else // Not enumerated, print the hex address.
234 OS << "%\"type " << STy << '\"';
237 case Type::PointerTyID: {
238 PointerType *PTy = cast<PointerType>(Ty);
239 print(PTy->getElementType(), OS);
240 if (unsigned AddressSpace = PTy->getAddressSpace())
241 OS << " addrspace(" << AddressSpace << ')';
245 case Type::ArrayTyID: {
246 ArrayType *ATy = cast<ArrayType>(Ty);
247 OS << '[' << ATy->getNumElements() << " x ";
248 print(ATy->getElementType(), OS);
252 case Type::VectorTyID: {
253 VectorType *PTy = cast<VectorType>(Ty);
254 OS << "<" << PTy->getNumElements() << " x ";
255 print(PTy->getElementType(), OS);
260 OS << "<unrecognized-type>";
265 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
266 if (STy->isOpaque()) {
274 if (STy->getNumElements() == 0) {
277 StructType::element_iterator I = STy->element_begin();
280 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
293 //===----------------------------------------------------------------------===//
294 // SlotTracker Class: Enumerate slot numbers for unnamed values
295 //===----------------------------------------------------------------------===//
299 /// This class provides computation of slot numbers for LLVM Assembly writing.
303 /// ValueMap - A mapping of Values to slot numbers.
304 typedef DenseMap<const Value*, unsigned> ValueMap;
307 /// TheModule - The module for which we are holding slot numbers.
308 const Module* TheModule;
310 /// TheFunction - The function for which we are holding slot numbers.
311 const Function* TheFunction;
312 bool FunctionProcessed;
314 /// mMap - The slot map for the module level data.
318 /// fMap - The slot map for the function level data.
322 /// mdnMap - Map for MDNodes.
323 DenseMap<const MDNode*, unsigned> mdnMap;
326 /// Construct from a module
327 explicit SlotTracker(const Module *M);
328 /// Construct from a function, starting out in incorp state.
329 explicit SlotTracker(const Function *F);
331 /// Return the slot number of the specified value in it's type
332 /// plane. If something is not in the SlotTracker, return -1.
333 int getLocalSlot(const Value *V);
334 int getGlobalSlot(const GlobalValue *V);
335 int getMetadataSlot(const MDNode *N);
337 /// If you'd like to deal with a function instead of just a module, use
338 /// this method to get its data into the SlotTracker.
339 void incorporateFunction(const Function *F) {
341 FunctionProcessed = false;
344 /// After calling incorporateFunction, use this method to remove the
345 /// most recently incorporated function from the SlotTracker. This
346 /// will reset the state of the machine back to just the module contents.
347 void purgeFunction();
349 /// MDNode map iterators.
350 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
351 mdn_iterator mdn_begin() { return mdnMap.begin(); }
352 mdn_iterator mdn_end() { return mdnMap.end(); }
353 unsigned mdn_size() const { return mdnMap.size(); }
354 bool mdn_empty() const { return mdnMap.empty(); }
356 /// This function does the actual initialization.
357 inline void initialize();
359 // Implementation Details
361 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
362 void CreateModuleSlot(const GlobalValue *V);
364 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
365 void CreateMetadataSlot(const MDNode *N);
367 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
368 void CreateFunctionSlot(const Value *V);
370 /// Add all of the module level global variables (and their initializers)
371 /// and function declarations, but not the contents of those functions.
372 void processModule();
374 /// Add all of the functions arguments, basic blocks, and instructions.
375 void processFunction();
377 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
378 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
381 } // end anonymous namespace
384 static SlotTracker *createSlotTracker(const Value *V) {
385 if (const Argument *FA = dyn_cast<Argument>(V))
386 return new SlotTracker(FA->getParent());
388 if (const Instruction *I = dyn_cast<Instruction>(V))
390 return new SlotTracker(I->getParent()->getParent());
392 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
393 return new SlotTracker(BB->getParent());
395 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
396 return new SlotTracker(GV->getParent());
398 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
399 return new SlotTracker(GA->getParent());
401 if (const Function *Func = dyn_cast<Function>(V))
402 return new SlotTracker(Func);
404 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
405 if (!MD->isFunctionLocal())
406 return new SlotTracker(MD->getFunction());
408 return new SlotTracker((Function *)0);
415 #define ST_DEBUG(X) dbgs() << X
420 // Module level constructor. Causes the contents of the Module (sans functions)
421 // to be added to the slot table.
422 SlotTracker::SlotTracker(const Module *M)
423 : TheModule(M), TheFunction(0), FunctionProcessed(false),
424 mNext(0), fNext(0), mdnNext(0) {
427 // Function level constructor. Causes the contents of the Module and the one
428 // function provided to be added to the slot table.
429 SlotTracker::SlotTracker(const Function *F)
430 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
431 mNext(0), fNext(0), mdnNext(0) {
434 inline void SlotTracker::initialize() {
437 TheModule = 0; ///< Prevent re-processing next time we're called.
440 if (TheFunction && !FunctionProcessed)
444 // Iterate through all the global variables, functions, and global
445 // variable initializers and create slots for them.
446 void SlotTracker::processModule() {
447 ST_DEBUG("begin processModule!\n");
449 // Add all of the unnamed global variables to the value table.
450 for (Module::const_global_iterator I = TheModule->global_begin(),
451 E = TheModule->global_end(); I != E; ++I) {
456 // Add metadata used by named metadata.
457 for (Module::const_named_metadata_iterator
458 I = TheModule->named_metadata_begin(),
459 E = TheModule->named_metadata_end(); I != E; ++I) {
460 const NamedMDNode *NMD = I;
461 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
462 CreateMetadataSlot(NMD->getOperand(i));
465 // Add all the unnamed functions to the table.
466 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
471 ST_DEBUG("end processModule!\n");
474 // Process the arguments, basic blocks, and instructions of a function.
475 void SlotTracker::processFunction() {
476 ST_DEBUG("begin processFunction!\n");
479 // Add all the function arguments with no names.
480 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
481 AE = TheFunction->arg_end(); AI != AE; ++AI)
483 CreateFunctionSlot(AI);
485 ST_DEBUG("Inserting Instructions:\n");
487 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
489 // Add all of the basic blocks and instructions with no names.
490 for (Function::const_iterator BB = TheFunction->begin(),
491 E = TheFunction->end(); BB != E; ++BB) {
493 CreateFunctionSlot(BB);
495 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
497 if (!I->getType()->isVoidTy() && !I->hasName())
498 CreateFunctionSlot(I);
500 // Intrinsics can directly use metadata. We allow direct calls to any
501 // llvm.foo function here, because the target may not be linked into the
503 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
504 if (Function *F = CI->getCalledFunction())
505 if (F->getName().startswith("llvm."))
506 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
507 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
508 CreateMetadataSlot(N);
511 // Process metadata attached with this instruction.
512 I->getAllMetadata(MDForInst);
513 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
514 CreateMetadataSlot(MDForInst[i].second);
519 FunctionProcessed = true;
521 ST_DEBUG("end processFunction!\n");
524 /// Clean up after incorporating a function. This is the only way to get out of
525 /// the function incorporation state that affects get*Slot/Create*Slot. Function
526 /// incorporation state is indicated by TheFunction != 0.
527 void SlotTracker::purgeFunction() {
528 ST_DEBUG("begin purgeFunction!\n");
529 fMap.clear(); // Simply discard the function level map
531 FunctionProcessed = false;
532 ST_DEBUG("end purgeFunction!\n");
535 /// getGlobalSlot - Get the slot number of a global value.
536 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
537 // Check for uninitialized state and do lazy initialization.
540 // Find the value in the module map
541 ValueMap::iterator MI = mMap.find(V);
542 return MI == mMap.end() ? -1 : (int)MI->second;
545 /// getMetadataSlot - Get the slot number of a MDNode.
546 int SlotTracker::getMetadataSlot(const MDNode *N) {
547 // Check for uninitialized state and do lazy initialization.
550 // Find the MDNode in the module map
551 mdn_iterator MI = mdnMap.find(N);
552 return MI == mdnMap.end() ? -1 : (int)MI->second;
556 /// getLocalSlot - Get the slot number for a value that is local to a function.
557 int SlotTracker::getLocalSlot(const Value *V) {
558 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
560 // Check for uninitialized state and do lazy initialization.
563 ValueMap::iterator FI = fMap.find(V);
564 return FI == fMap.end() ? -1 : (int)FI->second;
568 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
569 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
570 assert(V && "Can't insert a null Value into SlotTracker!");
571 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
572 assert(!V->hasName() && "Doesn't need a slot!");
574 unsigned DestSlot = mNext++;
577 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
579 // G = Global, F = Function, A = Alias, o = other
580 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
581 (isa<Function>(V) ? 'F' :
582 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
585 /// CreateSlot - Create a new slot for the specified value if it has no name.
586 void SlotTracker::CreateFunctionSlot(const Value *V) {
587 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
589 unsigned DestSlot = fNext++;
592 // G = Global, F = Function, o = other
593 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
594 DestSlot << " [o]\n");
597 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
598 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
599 assert(N && "Can't insert a null Value into SlotTracker!");
601 // Don't insert if N is a function-local metadata, these are always printed
603 if (!N->isFunctionLocal()) {
604 mdn_iterator I = mdnMap.find(N);
605 if (I != mdnMap.end())
608 unsigned DestSlot = mdnNext++;
609 mdnMap[N] = DestSlot;
612 // Recursively add any MDNodes referenced by operands.
613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
614 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
615 CreateMetadataSlot(Op);
618 //===----------------------------------------------------------------------===//
619 // AsmWriter Implementation
620 //===----------------------------------------------------------------------===//
622 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
623 TypePrinting *TypePrinter,
624 SlotTracker *Machine,
625 const Module *Context);
629 static const char *getPredicateText(unsigned predicate) {
630 const char * pred = "unknown";
632 case FCmpInst::FCMP_FALSE: pred = "false"; break;
633 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
634 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
635 case FCmpInst::FCMP_OGE: pred = "oge"; break;
636 case FCmpInst::FCMP_OLT: pred = "olt"; break;
637 case FCmpInst::FCMP_OLE: pred = "ole"; break;
638 case FCmpInst::FCMP_ONE: pred = "one"; break;
639 case FCmpInst::FCMP_ORD: pred = "ord"; break;
640 case FCmpInst::FCMP_UNO: pred = "uno"; break;
641 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
642 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
643 case FCmpInst::FCMP_UGE: pred = "uge"; break;
644 case FCmpInst::FCMP_ULT: pred = "ult"; break;
645 case FCmpInst::FCMP_ULE: pred = "ule"; break;
646 case FCmpInst::FCMP_UNE: pred = "une"; break;
647 case FCmpInst::FCMP_TRUE: pred = "true"; break;
648 case ICmpInst::ICMP_EQ: pred = "eq"; break;
649 case ICmpInst::ICMP_NE: pred = "ne"; break;
650 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
651 case ICmpInst::ICMP_SGE: pred = "sge"; break;
652 case ICmpInst::ICMP_SLT: pred = "slt"; break;
653 case ICmpInst::ICMP_SLE: pred = "sle"; break;
654 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
655 case ICmpInst::ICMP_UGE: pred = "uge"; break;
656 case ICmpInst::ICMP_ULT: pred = "ult"; break;
657 case ICmpInst::ICMP_ULE: pred = "ule"; break;
662 static void writeAtomicRMWOperation(raw_ostream &Out,
663 AtomicRMWInst::BinOp Op) {
665 default: Out << " <unknown operation " << Op << ">"; break;
666 case AtomicRMWInst::Xchg: Out << " xchg"; break;
667 case AtomicRMWInst::Add: Out << " add"; break;
668 case AtomicRMWInst::Sub: Out << " sub"; break;
669 case AtomicRMWInst::And: Out << " and"; break;
670 case AtomicRMWInst::Nand: Out << " nand"; break;
671 case AtomicRMWInst::Or: Out << " or"; break;
672 case AtomicRMWInst::Xor: Out << " xor"; break;
673 case AtomicRMWInst::Max: Out << " max"; break;
674 case AtomicRMWInst::Min: Out << " min"; break;
675 case AtomicRMWInst::UMax: Out << " umax"; break;
676 case AtomicRMWInst::UMin: Out << " umin"; break;
680 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
681 if (const OverflowingBinaryOperator *OBO =
682 dyn_cast<OverflowingBinaryOperator>(U)) {
683 if (OBO->hasNoUnsignedWrap())
685 if (OBO->hasNoSignedWrap())
687 } else if (const PossiblyExactOperator *Div =
688 dyn_cast<PossiblyExactOperator>(U)) {
691 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
692 if (GEP->isInBounds())
697 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
698 TypePrinting &TypePrinter,
699 SlotTracker *Machine,
700 const Module *Context) {
701 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
702 if (CI->getType()->isIntegerTy(1)) {
703 Out << (CI->getZExtValue() ? "true" : "false");
706 Out << CI->getValue();
710 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
711 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf ||
712 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
713 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
714 // We would like to output the FP constant value in exponential notation,
715 // but we cannot do this if doing so will lose precision. Check here to
716 // make sure that we only output it in exponential format if we can parse
717 // the value back and get the same value.
720 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
721 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
723 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
724 CFP->getValueAPF().convertToFloat();
725 SmallString<128> StrVal;
726 raw_svector_ostream(StrVal) << Val;
728 // Check to make sure that the stringized number is not some string like
729 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
730 // that the string matches the "[-+]?[0-9]" regex.
732 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
733 ((StrVal[0] == '-' || StrVal[0] == '+') &&
734 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
735 // Reparse stringized version!
736 if (atof(StrVal.c_str()) == Val) {
742 // Otherwise we could not reparse it to exactly the same value, so we must
743 // output the string in hexadecimal format! Note that loading and storing
744 // floating point types changes the bits of NaNs on some hosts, notably
745 // x86, so we must not use these types.
746 assert(sizeof(double) == sizeof(uint64_t) &&
747 "assuming that double is 64 bits!");
749 APFloat apf = CFP->getValueAPF();
750 // Halves and floats are represented in ASCII IR as double, convert.
752 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
755 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
760 // Some form of long double. These appear as a magic letter identifying
761 // the type, then a fixed number of hex digits.
763 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
765 // api needed to prevent premature destruction
766 APInt api = CFP->getValueAPF().bitcastToAPInt();
767 const uint64_t* p = api.getRawData();
768 uint64_t word = p[1];
770 int width = api.getBitWidth();
771 for (int j=0; j<width; j+=4, shiftcount-=4) {
772 unsigned int nibble = (word>>shiftcount) & 15;
774 Out << (unsigned char)(nibble + '0');
776 Out << (unsigned char)(nibble - 10 + 'A');
777 if (shiftcount == 0 && j+4 < width) {
781 shiftcount = width-j-4;
785 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
787 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
790 llvm_unreachable("Unsupported floating point type");
791 // api needed to prevent premature destruction
792 APInt api = CFP->getValueAPF().bitcastToAPInt();
793 const uint64_t* p = api.getRawData();
796 int width = api.getBitWidth();
797 for (int j=0; j<width; j+=4, shiftcount-=4) {
798 unsigned int nibble = (word>>shiftcount) & 15;
800 Out << (unsigned char)(nibble + '0');
802 Out << (unsigned char)(nibble - 10 + 'A');
803 if (shiftcount == 0 && j+4 < width) {
807 shiftcount = width-j-4;
813 if (isa<ConstantAggregateZero>(CV)) {
814 Out << "zeroinitializer";
818 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
819 Out << "blockaddress(";
820 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
823 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
829 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
830 Type *ETy = CA->getType()->getElementType();
832 TypePrinter.print(ETy, Out);
834 WriteAsOperandInternal(Out, CA->getOperand(0),
835 &TypePrinter, Machine,
837 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
839 TypePrinter.print(ETy, Out);
841 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
848 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
849 // As a special case, print the array as a string if it is an array of
850 // i8 with ConstantInt values.
851 if (CA->isString()) {
853 PrintEscapedString(CA->getAsString(), Out);
858 Type *ETy = CA->getType()->getElementType();
860 TypePrinter.print(ETy, Out);
862 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
863 &TypePrinter, Machine,
865 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
867 TypePrinter.print(ETy, Out);
869 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
877 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
878 if (CS->getType()->isPacked())
881 unsigned N = CS->getNumOperands();
884 TypePrinter.print(CS->getOperand(0)->getType(), Out);
887 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
890 for (unsigned i = 1; i < N; i++) {
892 TypePrinter.print(CS->getOperand(i)->getType(), Out);
895 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
902 if (CS->getType()->isPacked())
907 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
908 Type *ETy = CV->getType()->getVectorElementType();
910 TypePrinter.print(ETy, Out);
912 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
914 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
916 TypePrinter.print(ETy, Out);
918 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
925 if (isa<ConstantPointerNull>(CV)) {
930 if (isa<UndefValue>(CV)) {
935 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
936 Out << CE->getOpcodeName();
937 WriteOptimizationInfo(Out, CE);
939 Out << ' ' << getPredicateText(CE->getPredicate());
942 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
943 TypePrinter.print((*OI)->getType(), Out);
945 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
946 if (OI+1 != CE->op_end())
950 if (CE->hasIndices()) {
951 ArrayRef<unsigned> Indices = CE->getIndices();
952 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
953 Out << ", " << Indices[i];
958 TypePrinter.print(CE->getType(), Out);
965 Out << "<placeholder or erroneous Constant>";
968 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
969 TypePrinting *TypePrinter,
970 SlotTracker *Machine,
971 const Module *Context) {
973 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
974 const Value *V = Node->getOperand(mi);
978 TypePrinter->print(V->getType(), Out);
980 WriteAsOperandInternal(Out, Node->getOperand(mi),
981 TypePrinter, Machine, Context);
991 /// WriteAsOperand - Write the name of the specified value out to the specified
992 /// ostream. This can be useful when you just want to print int %reg126, not
993 /// the whole instruction that generated it.
995 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
996 TypePrinting *TypePrinter,
997 SlotTracker *Machine,
998 const Module *Context) {
1000 PrintLLVMName(Out, V);
1004 const Constant *CV = dyn_cast<Constant>(V);
1005 if (CV && !isa<GlobalValue>(CV)) {
1006 assert(TypePrinter && "Constants require TypePrinting!");
1007 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1011 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1013 if (IA->hasSideEffects())
1014 Out << "sideeffect ";
1015 if (IA->isAlignStack())
1016 Out << "alignstack ";
1018 PrintEscapedString(IA->getAsmString(), Out);
1020 PrintEscapedString(IA->getConstraintString(), Out);
1025 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1026 if (N->isFunctionLocal()) {
1027 // Print metadata inline, not via slot reference number.
1028 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1033 if (N->isFunctionLocal())
1034 Machine = new SlotTracker(N->getFunction());
1036 Machine = new SlotTracker(Context);
1038 int Slot = Machine->getMetadataSlot(N);
1046 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1048 PrintEscapedString(MDS->getString(), Out);
1053 if (V->getValueID() == Value::PseudoSourceValueVal ||
1054 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1061 // If we have a SlotTracker, use it.
1063 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1064 Slot = Machine->getGlobalSlot(GV);
1067 Slot = Machine->getLocalSlot(V);
1069 // If the local value didn't succeed, then we may be referring to a value
1070 // from a different function. Translate it, as this can happen when using
1071 // address of blocks.
1073 if ((Machine = createSlotTracker(V))) {
1074 Slot = Machine->getLocalSlot(V);
1078 } else if ((Machine = createSlotTracker(V))) {
1079 // Otherwise, create one to get the # and then destroy it.
1080 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1081 Slot = Machine->getGlobalSlot(GV);
1084 Slot = Machine->getLocalSlot(V);
1093 Out << Prefix << Slot;
1098 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1099 bool PrintType, const Module *Context) {
1101 // Fast path: Don't construct and populate a TypePrinting object if we
1102 // won't be needing any types printed.
1104 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1105 V->hasName() || isa<GlobalValue>(V))) {
1106 WriteAsOperandInternal(Out, V, 0, 0, Context);
1110 if (Context == 0) Context = getModuleFromVal(V);
1112 TypePrinting TypePrinter;
1114 TypePrinter.incorporateTypes(*Context);
1116 TypePrinter.print(V->getType(), Out);
1120 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1125 class AssemblyWriter {
1126 formatted_raw_ostream &Out;
1127 SlotTracker &Machine;
1128 const Module *TheModule;
1129 TypePrinting TypePrinter;
1130 AssemblyAnnotationWriter *AnnotationWriter;
1133 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1135 AssemblyAnnotationWriter *AAW)
1136 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1138 TypePrinter.incorporateTypes(*M);
1141 void printMDNodeBody(const MDNode *MD);
1142 void printNamedMDNode(const NamedMDNode *NMD);
1144 void printModule(const Module *M);
1146 void writeOperand(const Value *Op, bool PrintType);
1147 void writeParamOperand(const Value *Operand, Attributes Attrs);
1148 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1150 void writeAllMDNodes();
1152 void printTypeIdentities();
1153 void printGlobal(const GlobalVariable *GV);
1154 void printAlias(const GlobalAlias *GV);
1155 void printFunction(const Function *F);
1156 void printArgument(const Argument *FA, Attributes Attrs);
1157 void printBasicBlock(const BasicBlock *BB);
1158 void printInstruction(const Instruction &I);
1161 // printInfoComment - Print a little comment after the instruction indicating
1162 // which slot it occupies.
1163 void printInfoComment(const Value &V);
1165 } // end of anonymous namespace
1167 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1169 Out << "<null operand!>";
1173 TypePrinter.print(Operand->getType(), Out);
1176 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1179 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1180 SynchronizationScope SynchScope) {
1181 if (Ordering == NotAtomic)
1184 switch (SynchScope) {
1185 case SingleThread: Out << " singlethread"; break;
1186 case CrossThread: break;
1190 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1191 case Unordered: Out << " unordered"; break;
1192 case Monotonic: Out << " monotonic"; break;
1193 case Acquire: Out << " acquire"; break;
1194 case Release: Out << " release"; break;
1195 case AcquireRelease: Out << " acq_rel"; break;
1196 case SequentiallyConsistent: Out << " seq_cst"; break;
1200 void AssemblyWriter::writeParamOperand(const Value *Operand,
1203 Out << "<null operand!>";
1208 TypePrinter.print(Operand->getType(), Out);
1209 // Print parameter attributes list
1210 if (Attrs != Attribute::None)
1211 Out << ' ' << Attribute::getAsString(Attrs);
1213 // Print the operand
1214 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1217 void AssemblyWriter::printModule(const Module *M) {
1218 if (!M->getModuleIdentifier().empty() &&
1219 // Don't print the ID if it will start a new line (which would
1220 // require a comment char before it).
1221 M->getModuleIdentifier().find('\n') == std::string::npos)
1222 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1224 if (!M->getDataLayout().empty())
1225 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1226 if (!M->getTargetTriple().empty())
1227 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1229 if (!M->getModuleInlineAsm().empty()) {
1230 // Split the string into lines, to make it easier to read the .ll file.
1231 std::string Asm = M->getModuleInlineAsm();
1233 size_t NewLine = Asm.find_first_of('\n', CurPos);
1235 while (NewLine != std::string::npos) {
1236 // We found a newline, print the portion of the asm string from the
1237 // last newline up to this newline.
1238 Out << "module asm \"";
1239 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1243 NewLine = Asm.find_first_of('\n', CurPos);
1245 std::string rest(Asm.begin()+CurPos, Asm.end());
1246 if (!rest.empty()) {
1247 Out << "module asm \"";
1248 PrintEscapedString(rest, Out);
1253 // Loop over the dependent libraries and emit them.
1254 Module::lib_iterator LI = M->lib_begin();
1255 Module::lib_iterator LE = M->lib_end();
1258 Out << "deplibs = [ ";
1260 Out << '"' << *LI << '"';
1268 printTypeIdentities();
1270 // Output all globals.
1271 if (!M->global_empty()) Out << '\n';
1272 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1276 // Output all aliases.
1277 if (!M->alias_empty()) Out << "\n";
1278 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1282 // Output all of the functions.
1283 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1286 // Output named metadata.
1287 if (!M->named_metadata_empty()) Out << '\n';
1289 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1290 E = M->named_metadata_end(); I != E; ++I)
1291 printNamedMDNode(I);
1294 if (!Machine.mdn_empty()) {
1300 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1302 StringRef Name = NMD->getName();
1304 Out << "<empty name> ";
1306 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1307 Name[0] == '.' || Name[0] == '_')
1310 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1311 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1312 unsigned char C = Name[i];
1313 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1316 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1320 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1322 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1332 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1333 formatted_raw_ostream &Out) {
1335 case GlobalValue::ExternalLinkage: break;
1336 case GlobalValue::PrivateLinkage: Out << "private "; break;
1337 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1338 case GlobalValue::LinkerPrivateWeakLinkage:
1339 Out << "linker_private_weak ";
1341 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1342 Out << "linker_private_weak_def_auto ";
1344 case GlobalValue::InternalLinkage: Out << "internal "; break;
1345 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1346 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1347 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1348 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1349 case GlobalValue::CommonLinkage: Out << "common "; break;
1350 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1351 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1352 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1353 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1354 case GlobalValue::AvailableExternallyLinkage:
1355 Out << "available_externally ";
1361 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1362 formatted_raw_ostream &Out) {
1364 case GlobalValue::DefaultVisibility: break;
1365 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1366 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1370 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1371 if (GV->isMaterializable())
1372 Out << "; Materializable\n";
1374 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1377 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1380 PrintLinkage(GV->getLinkage(), Out);
1381 PrintVisibility(GV->getVisibility(), Out);
1383 if (GV->isThreadLocal()) Out << "thread_local ";
1384 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1385 Out << "addrspace(" << AddressSpace << ") ";
1386 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1387 Out << (GV->isConstant() ? "constant " : "global ");
1388 TypePrinter.print(GV->getType()->getElementType(), Out);
1390 if (GV->hasInitializer()) {
1392 writeOperand(GV->getInitializer(), false);
1395 if (GV->hasSection()) {
1396 Out << ", section \"";
1397 PrintEscapedString(GV->getSection(), Out);
1400 if (GV->getAlignment())
1401 Out << ", align " << GV->getAlignment();
1403 printInfoComment(*GV);
1407 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1408 if (GA->isMaterializable())
1409 Out << "; Materializable\n";
1411 // Don't crash when dumping partially built GA
1413 Out << "<<nameless>> = ";
1415 PrintLLVMName(Out, GA);
1418 PrintVisibility(GA->getVisibility(), Out);
1422 PrintLinkage(GA->getLinkage(), Out);
1424 const Constant *Aliasee = GA->getAliasee();
1427 TypePrinter.print(GA->getType(), Out);
1428 Out << " <<NULL ALIASEE>>";
1430 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1433 printInfoComment(*GA);
1437 void AssemblyWriter::printTypeIdentities() {
1438 if (TypePrinter.NumberedTypes.empty() &&
1439 TypePrinter.NamedTypes.empty())
1444 // We know all the numbers that each type is used and we know that it is a
1445 // dense assignment. Convert the map to an index table.
1446 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1447 for (DenseMap<StructType*, unsigned>::iterator I =
1448 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1450 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1451 NumberedTypes[I->second] = I->first;
1454 // Emit all numbered types.
1455 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1456 Out << '%' << i << " = type ";
1458 // Make sure we print out at least one level of the type structure, so
1459 // that we do not get %2 = type %2
1460 TypePrinter.printStructBody(NumberedTypes[i], Out);
1464 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1465 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1468 // Make sure we print out at least one level of the type structure, so
1469 // that we do not get %FILE = type %FILE
1470 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1475 /// printFunction - Print all aspects of a function.
1477 void AssemblyWriter::printFunction(const Function *F) {
1478 // Print out the return type and name.
1481 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1483 if (F->isMaterializable())
1484 Out << "; Materializable\n";
1486 if (F->isDeclaration())
1491 PrintLinkage(F->getLinkage(), Out);
1492 PrintVisibility(F->getVisibility(), Out);
1494 // Print the calling convention.
1495 switch (F->getCallingConv()) {
1496 case CallingConv::C: break; // default
1497 case CallingConv::Fast: Out << "fastcc "; break;
1498 case CallingConv::Cold: Out << "coldcc "; break;
1499 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1500 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1501 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1502 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1503 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1504 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1505 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1506 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1507 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1508 default: Out << "cc" << F->getCallingConv() << " "; break;
1511 FunctionType *FT = F->getFunctionType();
1512 const AttrListPtr &Attrs = F->getAttributes();
1513 Attributes RetAttrs = Attrs.getRetAttributes();
1514 if (RetAttrs != Attribute::None)
1515 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1516 TypePrinter.print(F->getReturnType(), Out);
1518 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1520 Machine.incorporateFunction(F);
1522 // Loop over the arguments, printing them...
1525 if (!F->isDeclaration()) {
1526 // If this isn't a declaration, print the argument names as well.
1527 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1529 // Insert commas as we go... the first arg doesn't get a comma
1530 if (I != F->arg_begin()) Out << ", ";
1531 printArgument(I, Attrs.getParamAttributes(Idx));
1535 // Otherwise, print the types from the function type.
1536 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1537 // Insert commas as we go... the first arg doesn't get a comma
1541 TypePrinter.print(FT->getParamType(i), Out);
1543 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1544 if (ArgAttrs != Attribute::None)
1545 Out << ' ' << Attribute::getAsString(ArgAttrs);
1549 // Finish printing arguments...
1550 if (FT->isVarArg()) {
1551 if (FT->getNumParams()) Out << ", ";
1552 Out << "..."; // Output varargs portion of signature!
1555 if (F->hasUnnamedAddr())
1556 Out << " unnamed_addr";
1557 Attributes FnAttrs = Attrs.getFnAttributes();
1558 if (FnAttrs != Attribute::None)
1559 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1560 if (F->hasSection()) {
1561 Out << " section \"";
1562 PrintEscapedString(F->getSection(), Out);
1565 if (F->getAlignment())
1566 Out << " align " << F->getAlignment();
1568 Out << " gc \"" << F->getGC() << '"';
1569 if (F->isDeclaration()) {
1573 // Output all of the function's basic blocks.
1574 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1580 Machine.purgeFunction();
1583 /// printArgument - This member is called for every argument that is passed into
1584 /// the function. Simply print it out
1586 void AssemblyWriter::printArgument(const Argument *Arg,
1589 TypePrinter.print(Arg->getType(), Out);
1591 // Output parameter attributes list
1592 if (Attrs != Attribute::None)
1593 Out << ' ' << Attribute::getAsString(Attrs);
1595 // Output name, if available...
1596 if (Arg->hasName()) {
1598 PrintLLVMName(Out, Arg);
1602 /// printBasicBlock - This member is called for each basic block in a method.
1604 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1605 if (BB->hasName()) { // Print out the label if it exists...
1607 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1609 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1610 Out << "\n; <label>:";
1611 int Slot = Machine.getLocalSlot(BB);
1618 if (BB->getParent() == 0) {
1619 Out.PadToColumn(50);
1620 Out << "; Error: Block without parent!";
1621 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1622 // Output predecessors for the block.
1623 Out.PadToColumn(50);
1625 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1628 Out << " No predecessors!";
1631 writeOperand(*PI, false);
1632 for (++PI; PI != PE; ++PI) {
1634 writeOperand(*PI, false);
1641 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1643 // Output all of the instructions in the basic block...
1644 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1645 printInstruction(*I);
1649 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1652 /// printInfoComment - Print a little comment after the instruction indicating
1653 /// which slot it occupies.
1655 void AssemblyWriter::printInfoComment(const Value &V) {
1656 if (AnnotationWriter) {
1657 AnnotationWriter->printInfoComment(V, Out);
1662 // This member is called for each Instruction in a function..
1663 void AssemblyWriter::printInstruction(const Instruction &I) {
1664 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1666 // Print out indentation for an instruction.
1669 // Print out name if it exists...
1671 PrintLLVMName(Out, &I);
1673 } else if (!I.getType()->isVoidTy()) {
1674 // Print out the def slot taken.
1675 int SlotNum = Machine.getLocalSlot(&I);
1677 Out << "<badref> = ";
1679 Out << '%' << SlotNum << " = ";
1682 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1685 // Print out the opcode...
1686 Out << I.getOpcodeName();
1688 // If this is an atomic load or store, print out the atomic marker.
1689 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1690 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1693 // If this is a volatile operation, print out the volatile marker.
1694 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1695 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1696 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1697 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1700 // Print out optimization information.
1701 WriteOptimizationInfo(Out, &I);
1703 // Print out the compare instruction predicates
1704 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1705 Out << ' ' << getPredicateText(CI->getPredicate());
1707 // Print out the atomicrmw operation
1708 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1709 writeAtomicRMWOperation(Out, RMWI->getOperation());
1711 // Print out the type of the operands...
1712 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1714 // Special case conditional branches to swizzle the condition out to the front
1715 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1716 BranchInst &BI(cast<BranchInst>(I));
1718 writeOperand(BI.getCondition(), true);
1720 writeOperand(BI.getSuccessor(0), true);
1722 writeOperand(BI.getSuccessor(1), true);
1724 } else if (isa<SwitchInst>(I)) {
1725 SwitchInst& SI(cast<SwitchInst>(I));
1726 // Special case switch instruction to get formatting nice and correct.
1728 writeOperand(SI.getCondition(), true);
1730 writeOperand(SI.getDefaultDest(), true);
1732 unsigned NumCases = SI.getNumCases();
1733 for (unsigned i = 0; i < NumCases; ++i) {
1735 writeOperand(SI.getCaseValue(i), true);
1737 writeOperand(SI.getCaseSuccessor(i), true);
1740 } else if (isa<IndirectBrInst>(I)) {
1741 // Special case indirectbr instruction to get formatting nice and correct.
1743 writeOperand(Operand, true);
1746 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1749 writeOperand(I.getOperand(i), true);
1752 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1754 TypePrinter.print(I.getType(), Out);
1757 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1758 if (op) Out << ", ";
1760 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1761 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1763 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1765 writeOperand(I.getOperand(0), true);
1766 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1768 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1770 writeOperand(I.getOperand(0), true); Out << ", ";
1771 writeOperand(I.getOperand(1), true);
1772 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1774 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1776 TypePrinter.print(I.getType(), Out);
1777 Out << " personality ";
1778 writeOperand(I.getOperand(0), true); Out << '\n';
1780 if (LPI->isCleanup())
1783 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1784 if (i != 0 || LPI->isCleanup()) Out << "\n";
1785 if (LPI->isCatch(i))
1790 writeOperand(LPI->getClause(i), true);
1792 } else if (isa<ReturnInst>(I) && !Operand) {
1794 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1795 // Print the calling convention being used.
1796 switch (CI->getCallingConv()) {
1797 case CallingConv::C: break; // default
1798 case CallingConv::Fast: Out << " fastcc"; break;
1799 case CallingConv::Cold: Out << " coldcc"; break;
1800 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1801 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1802 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1803 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1804 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1805 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1806 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1807 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1808 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1809 default: Out << " cc" << CI->getCallingConv(); break;
1812 Operand = CI->getCalledValue();
1813 PointerType *PTy = cast<PointerType>(Operand->getType());
1814 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1815 Type *RetTy = FTy->getReturnType();
1816 const AttrListPtr &PAL = CI->getAttributes();
1818 if (PAL.getRetAttributes() != Attribute::None)
1819 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1821 // If possible, print out the short form of the call instruction. We can
1822 // only do this if the first argument is a pointer to a nonvararg function,
1823 // and if the return type is not a pointer to a function.
1826 if (!FTy->isVarArg() &&
1827 (!RetTy->isPointerTy() ||
1828 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1829 TypePrinter.print(RetTy, Out);
1831 writeOperand(Operand, false);
1833 writeOperand(Operand, true);
1836 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1839 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1842 if (PAL.getFnAttributes() != Attribute::None)
1843 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1844 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1845 Operand = II->getCalledValue();
1846 PointerType *PTy = cast<PointerType>(Operand->getType());
1847 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1848 Type *RetTy = FTy->getReturnType();
1849 const AttrListPtr &PAL = II->getAttributes();
1851 // Print the calling convention being used.
1852 switch (II->getCallingConv()) {
1853 case CallingConv::C: break; // default
1854 case CallingConv::Fast: Out << " fastcc"; break;
1855 case CallingConv::Cold: Out << " coldcc"; break;
1856 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1857 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1858 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1859 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1860 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1861 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1862 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1863 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1864 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1865 default: Out << " cc" << II->getCallingConv(); break;
1868 if (PAL.getRetAttributes() != Attribute::None)
1869 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1871 // If possible, print out the short form of the invoke instruction. We can
1872 // only do this if the first argument is a pointer to a nonvararg function,
1873 // and if the return type is not a pointer to a function.
1876 if (!FTy->isVarArg() &&
1877 (!RetTy->isPointerTy() ||
1878 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1879 TypePrinter.print(RetTy, Out);
1881 writeOperand(Operand, false);
1883 writeOperand(Operand, true);
1886 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1889 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1893 if (PAL.getFnAttributes() != Attribute::None)
1894 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1897 writeOperand(II->getNormalDest(), true);
1899 writeOperand(II->getUnwindDest(), true);
1901 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1903 TypePrinter.print(AI->getType()->getElementType(), Out);
1904 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1906 writeOperand(AI->getArraySize(), true);
1908 if (AI->getAlignment()) {
1909 Out << ", align " << AI->getAlignment();
1911 } else if (isa<CastInst>(I)) {
1914 writeOperand(Operand, true); // Work with broken code
1917 TypePrinter.print(I.getType(), Out);
1918 } else if (isa<VAArgInst>(I)) {
1921 writeOperand(Operand, true); // Work with broken code
1924 TypePrinter.print(I.getType(), Out);
1925 } else if (Operand) { // Print the normal way.
1927 // PrintAllTypes - Instructions who have operands of all the same type
1928 // omit the type from all but the first operand. If the instruction has
1929 // different type operands (for example br), then they are all printed.
1930 bool PrintAllTypes = false;
1931 Type *TheType = Operand->getType();
1933 // Select, Store and ShuffleVector always print all types.
1934 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1935 || isa<ReturnInst>(I)) {
1936 PrintAllTypes = true;
1938 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1939 Operand = I.getOperand(i);
1940 // note that Operand shouldn't be null, but the test helps make dump()
1941 // more tolerant of malformed IR
1942 if (Operand && Operand->getType() != TheType) {
1943 PrintAllTypes = true; // We have differing types! Print them all!
1949 if (!PrintAllTypes) {
1951 TypePrinter.print(TheType, Out);
1955 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1957 writeOperand(I.getOperand(i), PrintAllTypes);
1961 // Print atomic ordering/alignment for memory operations
1962 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1964 writeAtomic(LI->getOrdering(), LI->getSynchScope());
1965 if (LI->getAlignment())
1966 Out << ", align " << LI->getAlignment();
1967 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1969 writeAtomic(SI->getOrdering(), SI->getSynchScope());
1970 if (SI->getAlignment())
1971 Out << ", align " << SI->getAlignment();
1972 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
1973 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
1974 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
1975 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
1976 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
1977 writeAtomic(FI->getOrdering(), FI->getSynchScope());
1980 // Print Metadata info.
1981 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1982 I.getAllMetadata(InstMD);
1983 if (!InstMD.empty()) {
1984 SmallVector<StringRef, 8> MDNames;
1985 I.getType()->getContext().getMDKindNames(MDNames);
1986 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1987 unsigned Kind = InstMD[i].first;
1988 if (Kind < MDNames.size()) {
1989 Out << ", !" << MDNames[Kind];
1991 Out << ", !<unknown kind #" << Kind << ">";
1994 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
1998 printInfoComment(I);
2001 static void WriteMDNodeComment(const MDNode *Node,
2002 formatted_raw_ostream &Out) {
2003 if (Node->getNumOperands() < 1)
2005 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2007 APInt Val = CI->getValue();
2008 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2009 if (Val.ult(LLVMDebugVersion11))
2012 Out.PadToColumn(50);
2013 if (Tag == dwarf::DW_TAG_user_base)
2014 Out << "; [ DW_TAG_user_base ]";
2015 else if (Tag.isIntN(32)) {
2016 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2017 Out << "; [ " << TagName << " ]";
2021 void AssemblyWriter::writeAllMDNodes() {
2022 SmallVector<const MDNode *, 16> Nodes;
2023 Nodes.resize(Machine.mdn_size());
2024 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2026 Nodes[I->second] = cast<MDNode>(I->first);
2028 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2029 Out << '!' << i << " = metadata ";
2030 printMDNodeBody(Nodes[i]);
2034 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2035 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2036 WriteMDNodeComment(Node, Out);
2040 //===----------------------------------------------------------------------===//
2041 // External Interface declarations
2042 //===----------------------------------------------------------------------===//
2044 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2045 SlotTracker SlotTable(this);
2046 formatted_raw_ostream OS(ROS);
2047 AssemblyWriter W(OS, SlotTable, this, AAW);
2048 W.printModule(this);
2051 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2052 SlotTracker SlotTable(getParent());
2053 formatted_raw_ostream OS(ROS);
2054 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2055 W.printNamedMDNode(this);
2058 void Type::print(raw_ostream &OS) const {
2060 OS << "<null Type>";
2064 TP.print(const_cast<Type*>(this), OS);
2066 // If the type is a named struct type, print the body as well.
2067 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2068 if (!STy->isLiteral()) {
2070 TP.printStructBody(STy, OS);
2074 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2076 ROS << "printing a <null> value\n";
2079 formatted_raw_ostream OS(ROS);
2080 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2081 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2082 SlotTracker SlotTable(F);
2083 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2084 W.printInstruction(*I);
2085 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2086 SlotTracker SlotTable(BB->getParent());
2087 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2088 W.printBasicBlock(BB);
2089 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2090 SlotTracker SlotTable(GV->getParent());
2091 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2092 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2094 else if (const Function *F = dyn_cast<Function>(GV))
2097 W.printAlias(cast<GlobalAlias>(GV));
2098 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2099 const Function *F = N->getFunction();
2100 SlotTracker SlotTable(F);
2101 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2102 W.printMDNodeBody(N);
2103 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2104 TypePrinting TypePrinter;
2105 TypePrinter.print(C->getType(), OS);
2107 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2108 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2109 isa<Argument>(this)) {
2110 WriteAsOperand(OS, this, true, 0);
2112 // Otherwise we don't know what it is. Call the virtual function to
2113 // allow a subclass to print itself.
2118 // Value::printCustom - subclasses should override this to implement printing.
2119 void Value::printCustom(raw_ostream &OS) const {
2120 llvm_unreachable("Unknown value to print out!");
2123 // Value::dump - allow easy printing of Values from the debugger.
2124 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2126 // Type::dump - allow easy printing of Types from the debugger.
2127 void Type::dump() const { print(dbgs()); }
2129 // Module::dump() - Allow printing of Modules from the debugger.
2130 void Module::dump() const { print(dbgs(), 0); }
2132 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2133 void NamedMDNode::dump() const { print(dbgs(), 0); }