1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AsmAnnotationWriter.h"
20 #include "llvm/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/TypeSymbolTable.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/FormattedStream.h"
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static const Module *getModuleFromVal(const Value *V) {
53 if (const Argument *MA = dyn_cast<Argument>(V))
54 return MA->getParent() ? MA->getParent()->getParent() : 0;
56 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57 return BB->getParent() ? BB->getParent()->getParent() : 0;
59 if (const Instruction *I = dyn_cast<Instruction>(V)) {
60 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61 return M ? M->getParent() : 0;
64 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65 return GV->getParent();
66 if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
67 return NMD->getParent();
71 // PrintEscapedString - Print each character of the specified string, escaping
72 // it if it is not printable or if it is an escape char.
73 static void PrintEscapedString(const StringRef &Name,
75 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
76 unsigned char C = Name[i];
77 if (isprint(C) && C != '\\' && C != '"')
80 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
91 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
92 /// prefixed with % (if the string only contains simple characters) or is
93 /// surrounded with ""'s (if it has special chars in it). Print it out.
94 static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
96 assert(Name.data() && "Cannot get empty name!");
98 default: llvm_unreachable("Bad prefix!");
100 case GlobalPrefix: OS << '@'; break;
101 case LabelPrefix: break;
102 case LocalPrefix: OS << '%'; break;
105 // Scan the name to see if it needs quotes first.
106 bool NeedsQuotes = isdigit(Name[0]);
108 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
110 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
117 // If we didn't need any quotes, just write out the name in one blast.
123 // Okay, we need quotes. Output the quotes and escape any scary characters as
126 PrintEscapedString(Name, OS);
130 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
131 /// prefixed with % (if the string only contains simple characters) or is
132 /// surrounded with ""'s (if it has special chars in it). Print it out.
133 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
134 PrintLLVMName(OS, V->getName(),
135 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
138 //===----------------------------------------------------------------------===//
139 // TypePrinting Class: Type printing machinery
140 //===----------------------------------------------------------------------===//
142 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
143 return *static_cast<DenseMap<const Type *, std::string>*>(M);
146 void TypePrinting::clear() {
147 getTypeNamesMap(TypeNames).clear();
150 bool TypePrinting::hasTypeName(const Type *Ty) const {
151 return getTypeNamesMap(TypeNames).count(Ty);
154 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
155 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
159 TypePrinting::TypePrinting() {
160 TypeNames = new DenseMap<const Type *, std::string>();
163 TypePrinting::~TypePrinting() {
164 delete &getTypeNamesMap(TypeNames);
167 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
168 /// use of type names or up references to shorten the type name where possible.
169 void TypePrinting::CalcTypeName(const Type *Ty,
170 SmallVectorImpl<const Type *> &TypeStack,
171 raw_ostream &OS, bool IgnoreTopLevelName) {
172 // Check to see if the type is named.
173 if (!IgnoreTopLevelName) {
174 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
175 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
182 // Check to see if the Type is already on the stack...
183 unsigned Slot = 0, CurSize = TypeStack.size();
184 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
186 // This is another base case for the recursion. In this case, we know
187 // that we have looped back to a type that we have previously visited.
188 // Generate the appropriate upreference to handle this.
189 if (Slot < CurSize) {
190 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
194 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
196 switch (Ty->getTypeID()) {
197 case Type::VoidTyID: OS << "void"; break;
198 case Type::FloatTyID: OS << "float"; break;
199 case Type::DoubleTyID: OS << "double"; break;
200 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
201 case Type::FP128TyID: OS << "fp128"; break;
202 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
203 case Type::LabelTyID: OS << "label"; break;
204 case Type::MetadataTyID: OS << "metadata"; break;
205 case Type::IntegerTyID:
206 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
209 case Type::FunctionTyID: {
210 const FunctionType *FTy = cast<FunctionType>(Ty);
211 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
213 for (FunctionType::param_iterator I = FTy->param_begin(),
214 E = FTy->param_end(); I != E; ++I) {
215 if (I != FTy->param_begin())
217 CalcTypeName(*I, TypeStack, OS);
219 if (FTy->isVarArg()) {
220 if (FTy->getNumParams()) OS << ", ";
226 case Type::StructTyID: {
227 const StructType *STy = cast<StructType>(Ty);
231 for (StructType::element_iterator I = STy->element_begin(),
232 E = STy->element_end(); I != E; ++I) {
233 CalcTypeName(*I, TypeStack, OS);
234 if (next(I) != STy->element_end())
243 case Type::UnionTyID: {
244 const UnionType *UTy = cast<UnionType>(Ty);
246 for (StructType::element_iterator I = UTy->element_begin(),
247 E = UTy->element_end(); I != E; ++I) {
248 CalcTypeName(*I, TypeStack, OS);
249 if (next(I) != UTy->element_end())
256 case Type::PointerTyID: {
257 const PointerType *PTy = cast<PointerType>(Ty);
258 CalcTypeName(PTy->getElementType(), TypeStack, OS);
259 if (unsigned AddressSpace = PTy->getAddressSpace())
260 OS << " addrspace(" << AddressSpace << ')';
264 case Type::ArrayTyID: {
265 const ArrayType *ATy = cast<ArrayType>(Ty);
266 OS << '[' << ATy->getNumElements() << " x ";
267 CalcTypeName(ATy->getElementType(), TypeStack, OS);
271 case Type::VectorTyID: {
272 const VectorType *PTy = cast<VectorType>(Ty);
273 OS << "<" << PTy->getNumElements() << " x ";
274 CalcTypeName(PTy->getElementType(), TypeStack, OS);
278 case Type::OpaqueTyID:
282 OS << "<unrecognized-type>";
286 TypeStack.pop_back(); // Remove self from stack.
289 /// printTypeInt - The internal guts of printing out a type that has a
290 /// potentially named portion.
292 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
293 bool IgnoreTopLevelName) {
294 // Check to see if the type is named.
295 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
296 if (!IgnoreTopLevelName) {
297 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
304 // Otherwise we have a type that has not been named but is a derived type.
305 // Carefully recurse the type hierarchy to print out any contained symbolic
307 SmallVector<const Type *, 16> TypeStack;
308 std::string TypeName;
310 raw_string_ostream TypeOS(TypeName);
311 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
314 // Cache type name for later use.
315 if (!IgnoreTopLevelName)
316 TM.insert(std::make_pair(Ty, TypeOS.str()));
321 // To avoid walking constant expressions multiple times and other IR
322 // objects, we keep several helper maps.
323 DenseSet<const Value*> VisitedConstants;
324 DenseSet<const Type*> VisitedTypes;
327 std::vector<const Type*> &NumberedTypes;
329 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
330 : TP(tp), NumberedTypes(numberedTypes) {}
332 void Run(const Module &M) {
333 // Get types from the type symbol table. This gets opaque types referened
334 // only through derived named types.
335 const TypeSymbolTable &ST = M.getTypeSymbolTable();
336 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
338 IncorporateType(TI->second);
340 // Get types from global variables.
341 for (Module::const_global_iterator I = M.global_begin(),
342 E = M.global_end(); I != E; ++I) {
343 IncorporateType(I->getType());
344 if (I->hasInitializer())
345 IncorporateValue(I->getInitializer());
348 // Get types from aliases.
349 for (Module::const_alias_iterator I = M.alias_begin(),
350 E = M.alias_end(); I != E; ++I) {
351 IncorporateType(I->getType());
352 IncorporateValue(I->getAliasee());
355 // Get types from functions.
356 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
357 IncorporateType(FI->getType());
359 for (Function::const_iterator BB = FI->begin(), E = FI->end();
361 for (BasicBlock::const_iterator II = BB->begin(),
362 E = BB->end(); II != E; ++II) {
363 const Instruction &I = *II;
364 // Incorporate the type of the instruction and all its operands.
365 IncorporateType(I.getType());
366 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
368 IncorporateValue(*OI);
374 void IncorporateType(const Type *Ty) {
375 // Check to see if we're already visited this type.
376 if (!VisitedTypes.insert(Ty).second)
379 // If this is a structure or opaque type, add a name for the type.
380 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
381 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
382 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
383 NumberedTypes.push_back(Ty);
386 // Recursively walk all contained types.
387 for (Type::subtype_iterator I = Ty->subtype_begin(),
388 E = Ty->subtype_end(); I != E; ++I)
392 /// IncorporateValue - This method is used to walk operand lists finding
393 /// types hiding in constant expressions and other operands that won't be
394 /// walked in other ways. GlobalValues, basic blocks, instructions, and
395 /// inst operands are all explicitly enumerated.
396 void IncorporateValue(const Value *V) {
397 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
400 if (!VisitedConstants.insert(V).second)
404 IncorporateType(V->getType());
406 // Look in operands for types.
407 const Constant *C = cast<Constant>(V);
408 for (Constant::const_op_iterator I = C->op_begin(),
409 E = C->op_end(); I != E;++I)
410 IncorporateValue(*I);
413 } // end anonymous namespace
416 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
417 /// the specified module to the TypePrinter and all numbered types to it and the
418 /// NumberedTypes table.
419 static void AddModuleTypesToPrinter(TypePrinting &TP,
420 std::vector<const Type*> &NumberedTypes,
424 // If the module has a symbol table, take all global types and stuff their
425 // names into the TypeNames map.
426 const TypeSymbolTable &ST = M->getTypeSymbolTable();
427 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
429 const Type *Ty = cast<Type>(TI->second);
431 // As a heuristic, don't insert pointer to primitive types, because
432 // they are used too often to have a single useful name.
433 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
434 const Type *PETy = PTy->getElementType();
435 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
440 // Likewise don't insert primitives either.
441 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
444 // Get the name as a string and insert it into TypeNames.
446 raw_string_ostream NameROS(NameStr);
447 formatted_raw_ostream NameOS(NameROS);
448 PrintLLVMName(NameOS, TI->first, LocalPrefix);
450 TP.addTypeName(Ty, NameStr);
453 // Walk the entire module to find references to unnamed structure and opaque
454 // types. This is required for correctness by opaque types (because multiple
455 // uses of an unnamed opaque type needs to be referred to by the same ID) and
456 // it shrinks complex recursive structure types substantially in some cases.
457 TypeFinder(TP, NumberedTypes).Run(*M);
461 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
462 /// type, iff there is an entry in the modules symbol table for the specified
463 /// type or one of it's component types.
465 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
466 TypePrinting Printer;
467 std::vector<const Type*> NumberedTypes;
468 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
469 Printer.print(Ty, OS);
472 //===----------------------------------------------------------------------===//
473 // SlotTracker Class: Enumerate slot numbers for unnamed values
474 //===----------------------------------------------------------------------===//
478 /// This class provides computation of slot numbers for LLVM Assembly writing.
482 /// ValueMap - A mapping of Values to slot numbers.
483 typedef DenseMap<const Value*, unsigned> ValueMap;
486 /// TheModule - The module for which we are holding slot numbers.
487 const Module* TheModule;
489 /// TheFunction - The function for which we are holding slot numbers.
490 const Function* TheFunction;
491 bool FunctionProcessed;
493 /// mMap - The TypePlanes map for the module level data.
497 /// fMap - The TypePlanes map for the function level data.
501 /// mdnMap - Map for MDNodes.
502 DenseMap<const MDNode*, unsigned> mdnMap;
505 /// Construct from a module
506 explicit SlotTracker(const Module *M);
507 /// Construct from a function, starting out in incorp state.
508 explicit SlotTracker(const Function *F);
510 /// Return the slot number of the specified value in it's type
511 /// plane. If something is not in the SlotTracker, return -1.
512 int getLocalSlot(const Value *V);
513 int getGlobalSlot(const GlobalValue *V);
514 int getMetadataSlot(const MDNode *N);
516 /// If you'd like to deal with a function instead of just a module, use
517 /// this method to get its data into the SlotTracker.
518 void incorporateFunction(const Function *F) {
520 FunctionProcessed = false;
523 /// After calling incorporateFunction, use this method to remove the
524 /// most recently incorporated function from the SlotTracker. This
525 /// will reset the state of the machine back to just the module contents.
526 void purgeFunction();
528 /// MDNode map iterators.
529 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
530 mdn_iterator mdn_begin() { return mdnMap.begin(); }
531 mdn_iterator mdn_end() { return mdnMap.end(); }
532 unsigned mdn_size() const { return mdnMap.size(); }
533 bool mdn_empty() const { return mdnMap.empty(); }
535 /// This function does the actual initialization.
536 inline void initialize();
538 // Implementation Details
540 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
541 void CreateModuleSlot(const GlobalValue *V);
543 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
544 void CreateMetadataSlot(const MDNode *N);
546 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
547 void CreateFunctionSlot(const Value *V);
549 /// Add all of the module level global variables (and their initializers)
550 /// and function declarations, but not the contents of those functions.
551 void processModule();
553 /// Add all of the functions arguments, basic blocks, and instructions.
554 void processFunction();
556 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
557 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
560 } // end anonymous namespace
563 static SlotTracker *createSlotTracker(const Value *V) {
564 if (const Argument *FA = dyn_cast<Argument>(V))
565 return new SlotTracker(FA->getParent());
567 if (const Instruction *I = dyn_cast<Instruction>(V))
568 return new SlotTracker(I->getParent()->getParent());
570 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
571 return new SlotTracker(BB->getParent());
573 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
574 return new SlotTracker(GV->getParent());
576 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
577 return new SlotTracker(GA->getParent());
579 if (const Function *Func = dyn_cast<Function>(V))
580 return new SlotTracker(Func);
583 return new SlotTracker((Function *)0);
589 #define ST_DEBUG(X) dbgs() << X
594 // Module level constructor. Causes the contents of the Module (sans functions)
595 // to be added to the slot table.
596 SlotTracker::SlotTracker(const Module *M)
597 : TheModule(M), TheFunction(0), FunctionProcessed(false),
598 mNext(0), fNext(0), mdnNext(0) {
601 // Function level constructor. Causes the contents of the Module and the one
602 // function provided to be added to the slot table.
603 SlotTracker::SlotTracker(const Function *F)
604 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
605 mNext(0), fNext(0), mdnNext(0) {
608 inline void SlotTracker::initialize() {
611 TheModule = 0; ///< Prevent re-processing next time we're called.
614 if (TheFunction && !FunctionProcessed)
618 // Iterate through all the global variables, functions, and global
619 // variable initializers and create slots for them.
620 void SlotTracker::processModule() {
621 ST_DEBUG("begin processModule!\n");
623 // Add all of the unnamed global variables to the value table.
624 for (Module::const_global_iterator I = TheModule->global_begin(),
625 E = TheModule->global_end(); I != E; ++I) {
630 // Add metadata used by named metadata.
631 for (Module::const_named_metadata_iterator
632 I = TheModule->named_metadata_begin(),
633 E = TheModule->named_metadata_end(); I != E; ++I) {
634 const NamedMDNode *NMD = I;
635 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
636 if (MDNode *MD = NMD->getOperand(i))
637 CreateMetadataSlot(MD);
641 // Add all the unnamed functions to the table.
642 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
647 ST_DEBUG("end processModule!\n");
650 // Process the arguments, basic blocks, and instructions of a function.
651 void SlotTracker::processFunction() {
652 ST_DEBUG("begin processFunction!\n");
655 // Add all the function arguments with no names.
656 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
657 AE = TheFunction->arg_end(); AI != AE; ++AI)
659 CreateFunctionSlot(AI);
661 ST_DEBUG("Inserting Instructions:\n");
663 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
665 // Add all of the basic blocks and instructions with no names.
666 for (Function::const_iterator BB = TheFunction->begin(),
667 E = TheFunction->end(); BB != E; ++BB) {
669 CreateFunctionSlot(BB);
671 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
673 if (!I->getType()->isVoidTy() && !I->hasName())
674 CreateFunctionSlot(I);
676 // Intrinsics can directly use metadata.
677 if (isa<IntrinsicInst>(I))
678 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
679 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
680 CreateMetadataSlot(N);
682 // Process metadata attached with this instruction.
683 I->getAllMetadata(MDForInst);
684 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
685 CreateMetadataSlot(MDForInst[i].second);
690 FunctionProcessed = true;
692 ST_DEBUG("end processFunction!\n");
695 /// Clean up after incorporating a function. This is the only way to get out of
696 /// the function incorporation state that affects get*Slot/Create*Slot. Function
697 /// incorporation state is indicated by TheFunction != 0.
698 void SlotTracker::purgeFunction() {
699 ST_DEBUG("begin purgeFunction!\n");
700 fMap.clear(); // Simply discard the function level map
702 FunctionProcessed = false;
703 ST_DEBUG("end purgeFunction!\n");
706 /// getGlobalSlot - Get the slot number of a global value.
707 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
708 // Check for uninitialized state and do lazy initialization.
711 // Find the type plane in the module map
712 ValueMap::iterator MI = mMap.find(V);
713 return MI == mMap.end() ? -1 : (int)MI->second;
716 /// getMetadataSlot - Get the slot number of a MDNode.
717 int SlotTracker::getMetadataSlot(const MDNode *N) {
718 // Check for uninitialized state and do lazy initialization.
721 // Find the type plane in the module map
722 mdn_iterator MI = mdnMap.find(N);
723 return MI == mdnMap.end() ? -1 : (int)MI->second;
727 /// getLocalSlot - Get the slot number for a value that is local to a function.
728 int SlotTracker::getLocalSlot(const Value *V) {
729 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
731 // Check for uninitialized state and do lazy initialization.
734 ValueMap::iterator FI = fMap.find(V);
735 return FI == fMap.end() ? -1 : (int)FI->second;
739 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
740 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
741 assert(V && "Can't insert a null Value into SlotTracker!");
742 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
743 assert(!V->hasName() && "Doesn't need a slot!");
745 unsigned DestSlot = mNext++;
748 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
750 // G = Global, F = Function, A = Alias, o = other
751 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
752 (isa<Function>(V) ? 'F' :
753 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
756 /// CreateSlot - Create a new slot for the specified value if it has no name.
757 void SlotTracker::CreateFunctionSlot(const Value *V) {
758 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
760 unsigned DestSlot = fNext++;
763 // G = Global, F = Function, o = other
764 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
765 DestSlot << " [o]\n");
768 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
769 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
770 assert(N && "Can't insert a null Value into SlotTracker!");
772 // Don't insert if N is a function-local metadata, these are always printed
774 if (N->isFunctionLocal())
777 mdn_iterator I = mdnMap.find(N);
778 if (I != mdnMap.end())
781 unsigned DestSlot = mdnNext++;
782 mdnMap[N] = DestSlot;
784 // Recursively add any MDNodes referenced by operands.
785 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
786 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
787 CreateMetadataSlot(Op);
790 //===----------------------------------------------------------------------===//
791 // AsmWriter Implementation
792 //===----------------------------------------------------------------------===//
794 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
795 TypePrinting *TypePrinter,
796 SlotTracker *Machine);
800 static const char *getPredicateText(unsigned predicate) {
801 const char * pred = "unknown";
803 case FCmpInst::FCMP_FALSE: pred = "false"; break;
804 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
805 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
806 case FCmpInst::FCMP_OGE: pred = "oge"; break;
807 case FCmpInst::FCMP_OLT: pred = "olt"; break;
808 case FCmpInst::FCMP_OLE: pred = "ole"; break;
809 case FCmpInst::FCMP_ONE: pred = "one"; break;
810 case FCmpInst::FCMP_ORD: pred = "ord"; break;
811 case FCmpInst::FCMP_UNO: pred = "uno"; break;
812 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
813 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
814 case FCmpInst::FCMP_UGE: pred = "uge"; break;
815 case FCmpInst::FCMP_ULT: pred = "ult"; break;
816 case FCmpInst::FCMP_ULE: pred = "ule"; break;
817 case FCmpInst::FCMP_UNE: pred = "une"; break;
818 case FCmpInst::FCMP_TRUE: pred = "true"; break;
819 case ICmpInst::ICMP_EQ: pred = "eq"; break;
820 case ICmpInst::ICMP_NE: pred = "ne"; break;
821 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
822 case ICmpInst::ICMP_SGE: pred = "sge"; break;
823 case ICmpInst::ICMP_SLT: pred = "slt"; break;
824 case ICmpInst::ICMP_SLE: pred = "sle"; break;
825 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
826 case ICmpInst::ICMP_UGE: pred = "uge"; break;
827 case ICmpInst::ICMP_ULT: pred = "ult"; break;
828 case ICmpInst::ICMP_ULE: pred = "ule"; break;
834 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
835 if (const OverflowingBinaryOperator *OBO =
836 dyn_cast<OverflowingBinaryOperator>(U)) {
837 if (OBO->hasNoUnsignedWrap())
839 if (OBO->hasNoSignedWrap())
841 } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
844 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
845 if (GEP->isInBounds())
850 static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
851 TypePrinting &TypePrinter, SlotTracker *Machine) {
852 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
853 if (CI->getType()->isIntegerTy(1)) {
854 Out << (CI->getZExtValue() ? "true" : "false");
857 Out << CI->getValue();
861 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
862 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
863 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
864 // We would like to output the FP constant value in exponential notation,
865 // but we cannot do this if doing so will lose precision. Check here to
866 // make sure that we only output it in exponential format if we can parse
867 // the value back and get the same value.
870 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
871 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
872 CFP->getValueAPF().convertToFloat();
873 SmallString<128> StrVal;
874 raw_svector_ostream(StrVal) << Val;
876 // Check to make sure that the stringized number is not some string like
877 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
878 // that the string matches the "[-+]?[0-9]" regex.
880 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
881 ((StrVal[0] == '-' || StrVal[0] == '+') &&
882 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
883 // Reparse stringized version!
884 if (atof(StrVal.c_str()) == Val) {
889 // Otherwise we could not reparse it to exactly the same value, so we must
890 // output the string in hexadecimal format! Note that loading and storing
891 // floating point types changes the bits of NaNs on some hosts, notably
892 // x86, so we must not use these types.
893 assert(sizeof(double) == sizeof(uint64_t) &&
894 "assuming that double is 64 bits!");
896 APFloat apf = CFP->getValueAPF();
897 // Floats are represented in ASCII IR as double, convert.
899 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
902 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
907 // Some form of long double. These appear as a magic letter identifying
908 // the type, then a fixed number of hex digits.
910 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
912 // api needed to prevent premature destruction
913 APInt api = CFP->getValueAPF().bitcastToAPInt();
914 const uint64_t* p = api.getRawData();
915 uint64_t word = p[1];
917 int width = api.getBitWidth();
918 for (int j=0; j<width; j+=4, shiftcount-=4) {
919 unsigned int nibble = (word>>shiftcount) & 15;
921 Out << (unsigned char)(nibble + '0');
923 Out << (unsigned char)(nibble - 10 + 'A');
924 if (shiftcount == 0 && j+4 < width) {
928 shiftcount = width-j-4;
932 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
934 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
937 llvm_unreachable("Unsupported floating point type");
938 // api needed to prevent premature destruction
939 APInt api = CFP->getValueAPF().bitcastToAPInt();
940 const uint64_t* p = api.getRawData();
943 int width = api.getBitWidth();
944 for (int j=0; j<width; j+=4, shiftcount-=4) {
945 unsigned int nibble = (word>>shiftcount) & 15;
947 Out << (unsigned char)(nibble + '0');
949 Out << (unsigned char)(nibble - 10 + 'A');
950 if (shiftcount == 0 && j+4 < width) {
954 shiftcount = width-j-4;
960 if (isa<ConstantAggregateZero>(CV)) {
961 Out << "zeroinitializer";
965 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
966 Out << "blockaddress(";
967 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
969 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
974 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
975 // As a special case, print the array as a string if it is an array of
976 // i8 with ConstantInt values.
978 const Type *ETy = CA->getType()->getElementType();
979 if (CA->isString()) {
981 PrintEscapedString(CA->getAsString(), Out);
983 } else { // Cannot output in string format...
985 if (CA->getNumOperands()) {
986 TypePrinter.print(ETy, Out);
988 WriteAsOperandInternal(Out, CA->getOperand(0),
989 &TypePrinter, Machine);
990 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
992 TypePrinter.print(ETy, Out);
994 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
1002 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1003 if (CS->getType()->isPacked())
1006 unsigned N = CS->getNumOperands();
1009 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1012 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1014 for (unsigned i = 1; i < N; i++) {
1016 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1019 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1025 if (CS->getType()->isPacked())
1030 if (const ConstantUnion *CU = dyn_cast<ConstantUnion>(CV)) {
1032 TypePrinter.print(CU->getOperand(0)->getType(), Out);
1034 WriteAsOperandInternal(Out, CU->getOperand(0), &TypePrinter, Machine);
1039 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1040 const Type *ETy = CP->getType()->getElementType();
1041 assert(CP->getNumOperands() > 0 &&
1042 "Number of operands for a PackedConst must be > 0");
1044 TypePrinter.print(ETy, Out);
1046 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1047 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1049 TypePrinter.print(ETy, Out);
1051 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1057 if (isa<ConstantPointerNull>(CV)) {
1062 if (isa<UndefValue>(CV)) {
1067 if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1068 Out << "!" << Machine->getMetadataSlot(Node);
1072 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1073 Out << CE->getOpcodeName();
1074 WriteOptimizationInfo(Out, CE);
1075 if (CE->isCompare())
1076 Out << ' ' << getPredicateText(CE->getPredicate());
1079 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1080 TypePrinter.print((*OI)->getType(), Out);
1082 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1083 if (OI+1 != CE->op_end())
1087 if (CE->hasIndices()) {
1088 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1089 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1090 Out << ", " << Indices[i];
1095 TypePrinter.print(CE->getType(), Out);
1102 Out << "<placeholder or erroneous Constant>";
1105 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1106 TypePrinting *TypePrinter,
1107 SlotTracker *Machine) {
1109 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1110 const Value *V = Node->getOperand(mi);
1114 TypePrinter->print(V->getType(), Out);
1116 WriteAsOperandInternal(Out, Node->getOperand(mi),
1117 TypePrinter, Machine);
1127 /// WriteAsOperand - Write the name of the specified value out to the specified
1128 /// ostream. This can be useful when you just want to print int %reg126, not
1129 /// the whole instruction that generated it.
1131 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1132 TypePrinting *TypePrinter,
1133 SlotTracker *Machine) {
1135 PrintLLVMName(Out, V);
1139 const Constant *CV = dyn_cast<Constant>(V);
1140 if (CV && !isa<GlobalValue>(CV)) {
1141 assert(TypePrinter && "Constants require TypePrinting!");
1142 WriteConstantInt(Out, CV, *TypePrinter, Machine);
1146 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1148 if (IA->hasSideEffects())
1149 Out << "sideeffect ";
1150 if (IA->isAlignStack())
1151 Out << "alignstack ";
1153 PrintEscapedString(IA->getAsmString(), Out);
1155 PrintEscapedString(IA->getConstraintString(), Out);
1160 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1161 if (N->isFunctionLocal()) {
1162 // Print metadata inline, not via slot reference number.
1163 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine);
1168 Machine = createSlotTracker(V);
1169 Out << '!' << Machine->getMetadataSlot(N);
1173 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1175 PrintEscapedString(MDS->getString(), Out);
1180 if (V->getValueID() == Value::PseudoSourceValueVal ||
1181 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1189 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1190 Slot = Machine->getGlobalSlot(GV);
1193 Slot = Machine->getLocalSlot(V);
1196 Machine = createSlotTracker(V);
1198 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1199 Slot = Machine->getGlobalSlot(GV);
1202 Slot = Machine->getLocalSlot(V);
1211 Out << Prefix << Slot;
1216 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1217 bool PrintType, const Module *Context) {
1219 // Fast path: Don't construct and populate a TypePrinting object if we
1220 // won't be needing any types printed.
1222 (!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1223 WriteAsOperandInternal(Out, V, 0, 0);
1227 if (Context == 0) Context = getModuleFromVal(V);
1229 TypePrinting TypePrinter;
1230 std::vector<const Type*> NumberedTypes;
1231 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1233 TypePrinter.print(V->getType(), Out);
1237 WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1242 class AssemblyWriter {
1243 formatted_raw_ostream &Out;
1244 SlotTracker &Machine;
1245 const Module *TheModule;
1246 TypePrinting TypePrinter;
1247 AssemblyAnnotationWriter *AnnotationWriter;
1248 std::vector<const Type*> NumberedTypes;
1251 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1253 AssemblyAnnotationWriter *AAW)
1254 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1255 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1258 void printMDNodeBody(const MDNode *MD);
1259 void printNamedMDNode(const NamedMDNode *NMD);
1261 void printModule(const Module *M);
1263 void writeOperand(const Value *Op, bool PrintType);
1264 void writeParamOperand(const Value *Operand, Attributes Attrs);
1266 void writeAllMDNodes();
1268 void printTypeSymbolTable(const TypeSymbolTable &ST);
1269 void printGlobal(const GlobalVariable *GV);
1270 void printAlias(const GlobalAlias *GV);
1271 void printFunction(const Function *F);
1272 void printArgument(const Argument *FA, Attributes Attrs);
1273 void printBasicBlock(const BasicBlock *BB);
1274 void printInstruction(const Instruction &I);
1277 // printInfoComment - Print a little comment after the instruction indicating
1278 // which slot it occupies.
1279 void printInfoComment(const Value &V);
1281 } // end of anonymous namespace
1283 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1285 Out << "<null operand!>";
1289 TypePrinter.print(Operand->getType(), Out);
1292 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1295 void AssemblyWriter::writeParamOperand(const Value *Operand,
1298 Out << "<null operand!>";
1303 TypePrinter.print(Operand->getType(), Out);
1304 // Print parameter attributes list
1305 if (Attrs != Attribute::None)
1306 Out << ' ' << Attribute::getAsString(Attrs);
1308 // Print the operand
1309 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1312 void AssemblyWriter::printModule(const Module *M) {
1313 if (!M->getModuleIdentifier().empty() &&
1314 // Don't print the ID if it will start a new line (which would
1315 // require a comment char before it).
1316 M->getModuleIdentifier().find('\n') == std::string::npos)
1317 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1319 if (!M->getDataLayout().empty())
1320 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1321 if (!M->getTargetTriple().empty())
1322 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1324 if (!M->getModuleInlineAsm().empty()) {
1325 // Split the string into lines, to make it easier to read the .ll file.
1326 std::string Asm = M->getModuleInlineAsm();
1328 size_t NewLine = Asm.find_first_of('\n', CurPos);
1330 while (NewLine != std::string::npos) {
1331 // We found a newline, print the portion of the asm string from the
1332 // last newline up to this newline.
1333 Out << "module asm \"";
1334 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1338 NewLine = Asm.find_first_of('\n', CurPos);
1340 Out << "module asm \"";
1341 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1345 // Loop over the dependent libraries and emit them.
1346 Module::lib_iterator LI = M->lib_begin();
1347 Module::lib_iterator LE = M->lib_end();
1350 Out << "deplibs = [ ";
1352 Out << '"' << *LI << '"';
1360 // Loop over the symbol table, emitting all id'd types.
1361 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1362 printTypeSymbolTable(M->getTypeSymbolTable());
1364 // Output all globals.
1365 if (!M->global_empty()) Out << '\n';
1366 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1370 // Output all aliases.
1371 if (!M->alias_empty()) Out << "\n";
1372 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1376 // Output all of the functions.
1377 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1380 // Output named metadata.
1381 if (!M->named_metadata_empty()) Out << '\n';
1383 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1384 E = M->named_metadata_end(); I != E; ++I)
1385 printNamedMDNode(I);
1388 if (!Machine.mdn_empty()) {
1394 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1395 Out << "!" << NMD->getName() << " = !{";
1396 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1398 if (MDNode *MD = NMD->getOperand(i))
1399 Out << '!' << Machine.getMetadataSlot(MD);
1407 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1408 formatted_raw_ostream &Out) {
1410 case GlobalValue::ExternalLinkage: break;
1411 case GlobalValue::PrivateLinkage: Out << "private "; break;
1412 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1413 case GlobalValue::InternalLinkage: Out << "internal "; break;
1414 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1415 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1416 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1417 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1418 case GlobalValue::CommonLinkage: Out << "common "; break;
1419 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1420 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1421 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1422 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1423 case GlobalValue::AvailableExternallyLinkage:
1424 Out << "available_externally ";
1430 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1431 formatted_raw_ostream &Out) {
1433 case GlobalValue::DefaultVisibility: break;
1434 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1435 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1439 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1440 if (GV->isMaterializable())
1441 Out << "; Materializable\n";
1443 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1446 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1449 PrintLinkage(GV->getLinkage(), Out);
1450 PrintVisibility(GV->getVisibility(), Out);
1452 if (GV->isThreadLocal()) Out << "thread_local ";
1453 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1454 Out << "addrspace(" << AddressSpace << ") ";
1455 Out << (GV->isConstant() ? "constant " : "global ");
1456 TypePrinter.print(GV->getType()->getElementType(), Out);
1458 if (GV->hasInitializer()) {
1460 writeOperand(GV->getInitializer(), false);
1463 if (GV->hasSection())
1464 Out << ", section \"" << GV->getSection() << '"';
1465 if (GV->getAlignment())
1466 Out << ", align " << GV->getAlignment();
1468 printInfoComment(*GV);
1472 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1473 if (GA->isMaterializable())
1474 Out << "; Materializable\n";
1476 // Don't crash when dumping partially built GA
1478 Out << "<<nameless>> = ";
1480 PrintLLVMName(Out, GA);
1483 PrintVisibility(GA->getVisibility(), Out);
1487 PrintLinkage(GA->getLinkage(), Out);
1489 const Constant *Aliasee = GA->getAliasee();
1491 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1492 TypePrinter.print(GV->getType(), Out);
1494 PrintLLVMName(Out, GV);
1495 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1496 TypePrinter.print(F->getFunctionType(), Out);
1499 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1500 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1501 TypePrinter.print(GA->getType(), Out);
1503 PrintLLVMName(Out, GA);
1505 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1506 // The only valid GEP is an all zero GEP.
1507 assert((CE->getOpcode() == Instruction::BitCast ||
1508 CE->getOpcode() == Instruction::GetElementPtr) &&
1509 "Unsupported aliasee");
1510 writeOperand(CE, false);
1513 printInfoComment(*GA);
1517 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1518 // Emit all numbered types.
1519 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1520 Out << '%' << i << " = type ";
1522 // Make sure we print out at least one level of the type structure, so
1523 // that we do not get %2 = type %2
1524 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1528 // Print the named types.
1529 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1531 PrintLLVMName(Out, TI->first, LocalPrefix);
1534 // Make sure we print out at least one level of the type structure, so
1535 // that we do not get %FILE = type %FILE
1536 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1541 /// printFunction - Print all aspects of a function.
1543 void AssemblyWriter::printFunction(const Function *F) {
1544 // Print out the return type and name.
1547 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1549 if (F->isMaterializable())
1550 Out << "; Materializable\n";
1552 if (F->isDeclaration())
1557 PrintLinkage(F->getLinkage(), Out);
1558 PrintVisibility(F->getVisibility(), Out);
1560 // Print the calling convention.
1561 switch (F->getCallingConv()) {
1562 case CallingConv::C: break; // default
1563 case CallingConv::Fast: Out << "fastcc "; break;
1564 case CallingConv::Cold: Out << "coldcc "; break;
1565 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1566 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1567 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1568 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1569 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1570 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1571 default: Out << "cc" << F->getCallingConv() << " "; break;
1574 const FunctionType *FT = F->getFunctionType();
1575 const AttrListPtr &Attrs = F->getAttributes();
1576 Attributes RetAttrs = Attrs.getRetAttributes();
1577 if (RetAttrs != Attribute::None)
1578 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1579 TypePrinter.print(F->getReturnType(), Out);
1581 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1583 Machine.incorporateFunction(F);
1585 // Loop over the arguments, printing them...
1588 if (!F->isDeclaration()) {
1589 // If this isn't a declaration, print the argument names as well.
1590 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1592 // Insert commas as we go... the first arg doesn't get a comma
1593 if (I != F->arg_begin()) Out << ", ";
1594 printArgument(I, Attrs.getParamAttributes(Idx));
1598 // Otherwise, print the types from the function type.
1599 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1600 // Insert commas as we go... the first arg doesn't get a comma
1604 TypePrinter.print(FT->getParamType(i), Out);
1606 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1607 if (ArgAttrs != Attribute::None)
1608 Out << ' ' << Attribute::getAsString(ArgAttrs);
1612 // Finish printing arguments...
1613 if (FT->isVarArg()) {
1614 if (FT->getNumParams()) Out << ", ";
1615 Out << "..."; // Output varargs portion of signature!
1618 Attributes FnAttrs = Attrs.getFnAttributes();
1619 if (FnAttrs != Attribute::None)
1620 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1621 if (F->hasSection())
1622 Out << " section \"" << F->getSection() << '"';
1623 if (F->getAlignment())
1624 Out << " align " << F->getAlignment();
1626 Out << " gc \"" << F->getGC() << '"';
1627 if (F->isDeclaration()) {
1632 // Output all of its basic blocks... for the function
1633 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1639 Machine.purgeFunction();
1642 /// printArgument - This member is called for every argument that is passed into
1643 /// the function. Simply print it out
1645 void AssemblyWriter::printArgument(const Argument *Arg,
1648 TypePrinter.print(Arg->getType(), Out);
1650 // Output parameter attributes list
1651 if (Attrs != Attribute::None)
1652 Out << ' ' << Attribute::getAsString(Attrs);
1654 // Output name, if available...
1655 if (Arg->hasName()) {
1657 PrintLLVMName(Out, Arg);
1661 /// printBasicBlock - This member is called for each basic block in a method.
1663 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1664 if (BB->hasName()) { // Print out the label if it exists...
1666 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1668 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1669 Out << "\n; <label>:";
1670 int Slot = Machine.getLocalSlot(BB);
1677 if (BB->getParent() == 0) {
1678 Out.PadToColumn(50);
1679 Out << "; Error: Block without parent!";
1680 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1681 // Output predecessors for the block...
1682 Out.PadToColumn(50);
1684 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1687 Out << " No predecessors!";
1690 writeOperand(*PI, false);
1691 for (++PI; PI != PE; ++PI) {
1693 writeOperand(*PI, false);
1700 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1702 // Output all of the instructions in the basic block...
1703 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1704 printInstruction(*I);
1708 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1711 /// printInfoComment - Print a little comment after the instruction indicating
1712 /// which slot it occupies.
1714 void AssemblyWriter::printInfoComment(const Value &V) {
1715 if (AnnotationWriter) {
1716 AnnotationWriter->printInfoComment(V, Out);
1720 if (V.getType()->isVoidTy()) return;
1722 Out.PadToColumn(50);
1724 TypePrinter.print(V.getType(), Out);
1725 Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1728 // This member is called for each Instruction in a function..
1729 void AssemblyWriter::printInstruction(const Instruction &I) {
1730 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1732 // Print out indentation for an instruction.
1735 // Print out name if it exists...
1737 PrintLLVMName(Out, &I);
1739 } else if (!I.getType()->isVoidTy()) {
1740 // Print out the def slot taken.
1741 int SlotNum = Machine.getLocalSlot(&I);
1743 Out << "<badref> = ";
1745 Out << '%' << SlotNum << " = ";
1748 // If this is a volatile load or store, print out the volatile marker.
1749 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1750 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1752 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1753 // If this is a call, check if it's a tail call.
1757 // Print out the opcode...
1758 Out << I.getOpcodeName();
1760 // Print out optimization information.
1761 WriteOptimizationInfo(Out, &I);
1763 // Print out the compare instruction predicates
1764 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1765 Out << ' ' << getPredicateText(CI->getPredicate());
1767 // Print out the type of the operands...
1768 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1770 // Special case conditional branches to swizzle the condition out to the front
1771 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1772 BranchInst &BI(cast<BranchInst>(I));
1774 writeOperand(BI.getCondition(), true);
1776 writeOperand(BI.getSuccessor(0), true);
1778 writeOperand(BI.getSuccessor(1), true);
1780 } else if (isa<SwitchInst>(I)) {
1781 // Special case switch instruction to get formatting nice and correct.
1783 writeOperand(Operand , true);
1785 writeOperand(I.getOperand(1), true);
1788 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1790 writeOperand(I.getOperand(op ), true);
1792 writeOperand(I.getOperand(op+1), true);
1795 } else if (isa<IndirectBrInst>(I)) {
1796 // Special case indirectbr instruction to get formatting nice and correct.
1798 writeOperand(Operand, true);
1801 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1804 writeOperand(I.getOperand(i), true);
1807 } else if (isa<PHINode>(I)) {
1809 TypePrinter.print(I.getType(), Out);
1812 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1813 if (op) Out << ", ";
1815 writeOperand(I.getOperand(op ), false); Out << ", ";
1816 writeOperand(I.getOperand(op+1), false); Out << " ]";
1818 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1820 writeOperand(I.getOperand(0), true);
1821 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1823 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1825 writeOperand(I.getOperand(0), true); Out << ", ";
1826 writeOperand(I.getOperand(1), true);
1827 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1829 } else if (isa<ReturnInst>(I) && !Operand) {
1831 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1832 // Print the calling convention being used.
1833 switch (CI->getCallingConv()) {
1834 case CallingConv::C: break; // default
1835 case CallingConv::Fast: Out << " fastcc"; break;
1836 case CallingConv::Cold: Out << " coldcc"; break;
1837 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1838 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1839 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1840 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1841 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1842 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1843 default: Out << " cc" << CI->getCallingConv(); break;
1846 const PointerType *PTy = cast<PointerType>(Operand->getType());
1847 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1848 const Type *RetTy = FTy->getReturnType();
1849 const AttrListPtr &PAL = CI->getAttributes();
1851 if (PAL.getRetAttributes() != Attribute::None)
1852 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1854 // If possible, print out the short form of the call instruction. We can
1855 // only do this if the first argument is a pointer to a nonvararg function,
1856 // and if the return type is not a pointer to a function.
1859 if (!FTy->isVarArg() &&
1860 (!RetTy->isPointerTy() ||
1861 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1862 TypePrinter.print(RetTy, Out);
1864 writeOperand(Operand, false);
1866 writeOperand(Operand, true);
1869 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1872 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1875 if (PAL.getFnAttributes() != Attribute::None)
1876 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1877 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1878 const PointerType *PTy = cast<PointerType>(Operand->getType());
1879 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1880 const Type *RetTy = FTy->getReturnType();
1881 const AttrListPtr &PAL = II->getAttributes();
1883 // Print the calling convention being used.
1884 switch (II->getCallingConv()) {
1885 case CallingConv::C: break; // default
1886 case CallingConv::Fast: Out << " fastcc"; break;
1887 case CallingConv::Cold: Out << " coldcc"; break;
1888 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1889 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1890 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1891 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1892 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1893 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1894 default: Out << " cc" << II->getCallingConv(); break;
1897 if (PAL.getRetAttributes() != Attribute::None)
1898 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1900 // If possible, print out the short form of the invoke instruction. We can
1901 // only do this if the first argument is a pointer to a nonvararg function,
1902 // and if the return type is not a pointer to a function.
1905 if (!FTy->isVarArg() &&
1906 (!RetTy->isPointerTy() ||
1907 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1908 TypePrinter.print(RetTy, Out);
1910 writeOperand(Operand, false);
1912 writeOperand(Operand, true);
1915 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1918 writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1922 if (PAL.getFnAttributes() != Attribute::None)
1923 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1926 writeOperand(II->getNormalDest(), true);
1928 writeOperand(II->getUnwindDest(), true);
1930 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1932 TypePrinter.print(AI->getType()->getElementType(), Out);
1933 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1935 writeOperand(AI->getArraySize(), true);
1937 if (AI->getAlignment()) {
1938 Out << ", align " << AI->getAlignment();
1940 } else if (isa<CastInst>(I)) {
1943 writeOperand(Operand, true); // Work with broken code
1946 TypePrinter.print(I.getType(), Out);
1947 } else if (isa<VAArgInst>(I)) {
1950 writeOperand(Operand, true); // Work with broken code
1953 TypePrinter.print(I.getType(), Out);
1954 } else if (Operand) { // Print the normal way.
1956 // PrintAllTypes - Instructions who have operands of all the same type
1957 // omit the type from all but the first operand. If the instruction has
1958 // different type operands (for example br), then they are all printed.
1959 bool PrintAllTypes = false;
1960 const Type *TheType = Operand->getType();
1962 // Select, Store and ShuffleVector always print all types.
1963 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1964 || isa<ReturnInst>(I)) {
1965 PrintAllTypes = true;
1967 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1968 Operand = I.getOperand(i);
1969 // note that Operand shouldn't be null, but the test helps make dump()
1970 // more tolerant of malformed IR
1971 if (Operand && Operand->getType() != TheType) {
1972 PrintAllTypes = true; // We have differing types! Print them all!
1978 if (!PrintAllTypes) {
1980 TypePrinter.print(TheType, Out);
1984 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1986 writeOperand(I.getOperand(i), PrintAllTypes);
1990 // Print post operand alignment for load/store.
1991 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1992 Out << ", align " << cast<LoadInst>(I).getAlignment();
1993 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1994 Out << ", align " << cast<StoreInst>(I).getAlignment();
1997 // Print Metadata info.
1998 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1999 I.getAllMetadata(InstMD);
2000 if (!InstMD.empty()) {
2001 SmallVector<StringRef, 8> MDNames;
2002 I.getType()->getContext().getMDKindNames(MDNames);
2003 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2004 unsigned Kind = InstMD[i].first;
2005 if (Kind < MDNames.size()) {
2006 Out << ", !" << MDNames[Kind];
2008 Out << ", !<unknown kind #" << Kind << ">";
2010 Out << " !" << Machine.getMetadataSlot(InstMD[i].second);
2013 printInfoComment(I);
2016 static void WriteMDNodeComment(const MDNode *Node,
2017 formatted_raw_ostream &Out) {
2018 if (Node->getNumOperands() < 1)
2020 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2022 unsigned Val = CI->getZExtValue();
2023 unsigned Tag = Val & ~LLVMDebugVersionMask;
2024 if (Val < LLVMDebugVersion)
2027 Out.PadToColumn(50);
2028 if (Tag == dwarf::DW_TAG_auto_variable)
2029 Out << "; [ DW_TAG_auto_variable ]";
2030 else if (Tag == dwarf::DW_TAG_arg_variable)
2031 Out << "; [ DW_TAG_arg_variable ]";
2032 else if (Tag == dwarf::DW_TAG_return_variable)
2033 Out << "; [ DW_TAG_return_variable ]";
2034 else if (Tag == dwarf::DW_TAG_vector_type)
2035 Out << "; [ DW_TAG_vector_type ]";
2036 else if (Tag == dwarf::DW_TAG_user_base)
2037 Out << "; [ DW_TAG_user_base ]";
2038 else if (const char *TagName = dwarf::TagString(Tag))
2039 Out << "; [ " << TagName << " ]";
2042 void AssemblyWriter::writeAllMDNodes() {
2043 SmallVector<const MDNode *, 16> Nodes;
2044 Nodes.resize(Machine.mdn_size());
2045 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2047 Nodes[I->second] = cast<MDNode>(I->first);
2049 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2050 Out << '!' << i << " = metadata ";
2051 printMDNodeBody(Nodes[i]);
2055 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2056 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2057 WriteMDNodeComment(Node, Out);
2061 //===----------------------------------------------------------------------===//
2062 // External Interface declarations
2063 //===----------------------------------------------------------------------===//
2065 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2066 SlotTracker SlotTable(this);
2067 formatted_raw_ostream OS(ROS);
2068 AssemblyWriter W(OS, SlotTable, this, AAW);
2069 W.printModule(this);
2072 void Type::print(raw_ostream &OS) const {
2074 OS << "<null Type>";
2077 TypePrinting().print(this, OS);
2080 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2082 ROS << "printing a <null> value\n";
2085 formatted_raw_ostream OS(ROS);
2086 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2087 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2088 SlotTracker SlotTable(F);
2089 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2090 W.printInstruction(*I);
2091 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2092 SlotTracker SlotTable(BB->getParent());
2093 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2094 W.printBasicBlock(BB);
2095 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2096 SlotTracker SlotTable(GV->getParent());
2097 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2098 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2100 else if (const Function *F = dyn_cast<Function>(GV))
2103 W.printAlias(cast<GlobalAlias>(GV));
2104 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2105 const Function *F = N->getFunction();
2106 SlotTracker SlotTable(F);
2107 AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2108 W.printMDNodeBody(N);
2109 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2110 SlotTracker SlotTable(N->getParent());
2111 AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2112 W.printNamedMDNode(N);
2113 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2114 TypePrinting TypePrinter;
2115 TypePrinter.print(C->getType(), OS);
2117 WriteConstantInt(OS, C, TypePrinter, 0);
2118 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2119 isa<Argument>(this)) {
2120 WriteAsOperand(OS, this, true, 0);
2122 // Otherwise we don't know what it is. Call the virtual function to
2123 // allow a subclass to print itself.
2128 // Value::printCustom - subclasses should override this to implement printing.
2129 void Value::printCustom(raw_ostream &OS) const {
2130 llvm_unreachable("Unknown value to print out!");
2133 // Value::dump - allow easy printing of Values from the debugger.
2134 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2136 // Type::dump - allow easy printing of Types from the debugger.
2137 // This one uses type names from the given context module
2138 void Type::dump(const Module *Context) const {
2139 WriteTypeSymbolic(dbgs(), this, Context);
2143 // Type::dump - allow easy printing of Types from the debugger.
2144 void Type::dump() const { dump(0); }
2146 // Module::dump() - Allow printing of Modules from the debugger.
2147 void Module::dump() const { print(dbgs(), 0); }