Revert r131155 for now. It makes VMCore depend on Analysis and Transforms
[llvm/stm8.git] / lib / VMCore / AsmWriter.cpp
blob844284d09c72fdda23c0c8fdef0b565521b9f972
1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/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/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include <algorithm>
42 #include <cctype>
43 using namespace llvm;
45 static cl::opt<bool>
46 EnableDebugInfoComment("enable-debug-info-comment", cl::Hidden,
47 cl::desc("Enable debug info comments"));
50 // Make virtual table appear in this compilation unit.
51 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
53 //===----------------------------------------------------------------------===//
54 // Helper Functions
55 //===----------------------------------------------------------------------===//
57 static const Module *getModuleFromVal(const Value *V) {
58 if (const Argument *MA = dyn_cast<Argument>(V))
59 return MA->getParent() ? MA->getParent()->getParent() : 0;
61 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
62 return BB->getParent() ? BB->getParent()->getParent() : 0;
64 if (const Instruction *I = dyn_cast<Instruction>(V)) {
65 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
66 return M ? M->getParent() : 0;
69 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
70 return GV->getParent();
71 return 0;
74 // PrintEscapedString - Print each character of the specified string, escaping
75 // it if it is not printable or if it is an escape char.
76 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
77 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
78 unsigned char C = Name[i];
79 if (isprint(C) && C != '\\' && C != '"')
80 Out << C;
81 else
82 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
86 enum PrefixType {
87 GlobalPrefix,
88 LabelPrefix,
89 LocalPrefix,
90 NoPrefix
93 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
94 /// prefixed with % (if the string only contains simple characters) or is
95 /// surrounded with ""'s (if it has special chars in it). Print it out.
96 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
97 assert(!Name.empty() && "Cannot get empty name!");
98 switch (Prefix) {
99 default: llvm_unreachable("Bad prefix!");
100 case NoPrefix: break;
101 case GlobalPrefix: OS << '@'; break;
102 case LabelPrefix: break;
103 case LocalPrefix: OS << '%'; break;
106 // Scan the name to see if it needs quotes first.
107 bool NeedsQuotes = isdigit(Name[0]);
108 if (!NeedsQuotes) {
109 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
110 char C = Name[i];
111 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
112 NeedsQuotes = true;
113 break;
118 // If we didn't need any quotes, just write out the name in one blast.
119 if (!NeedsQuotes) {
120 OS << Name;
121 return;
124 // Okay, we need quotes. Output the quotes and escape any scary characters as
125 // needed.
126 OS << '"';
127 PrintEscapedString(Name, OS);
128 OS << '"';
131 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
132 /// prefixed with % (if the string only contains simple characters) or is
133 /// surrounded with ""'s (if it has special chars in it). Print it out.
134 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
135 PrintLLVMName(OS, V->getName(),
136 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
139 //===----------------------------------------------------------------------===//
140 // TypePrinting Class: Type printing machinery
141 //===----------------------------------------------------------------------===//
143 static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
144 return *static_cast<DenseMap<const Type *, std::string>*>(M);
147 void TypePrinting::clear() {
148 getTypeNamesMap(TypeNames).clear();
151 bool TypePrinting::hasTypeName(const Type *Ty) const {
152 return getTypeNamesMap(TypeNames).count(Ty);
155 void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
156 getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
160 TypePrinting::TypePrinting() {
161 TypeNames = new DenseMap<const Type *, std::string>();
164 TypePrinting::~TypePrinting() {
165 delete &getTypeNamesMap(TypeNames);
168 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
169 /// use of type names or up references to shorten the type name where possible.
170 void TypePrinting::CalcTypeName(const Type *Ty,
171 SmallVectorImpl<const Type *> &TypeStack,
172 raw_ostream &OS, bool IgnoreTopLevelName) {
173 // Check to see if the type is named.
174 if (!IgnoreTopLevelName) {
175 DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
176 DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
177 if (I != TM.end()) {
178 OS << I->second;
179 return;
183 // Check to see if the Type is already on the stack...
184 unsigned Slot = 0, CurSize = TypeStack.size();
185 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
187 // This is another base case for the recursion. In this case, we know
188 // that we have looped back to a type that we have previously visited.
189 // Generate the appropriate upreference to handle this.
190 if (Slot < CurSize) {
191 OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
192 return;
195 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
197 switch (Ty->getTypeID()) {
198 case Type::VoidTyID: OS << "void"; break;
199 case Type::FloatTyID: OS << "float"; break;
200 case Type::DoubleTyID: OS << "double"; break;
201 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
202 case Type::FP128TyID: OS << "fp128"; break;
203 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
204 case Type::LabelTyID: OS << "label"; break;
205 case Type::MetadataTyID: OS << "metadata"; break;
206 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
207 case Type::IntegerTyID:
208 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
209 break;
211 case Type::FunctionTyID: {
212 const FunctionType *FTy = cast<FunctionType>(Ty);
213 CalcTypeName(FTy->getReturnType(), TypeStack, OS);
214 OS << " (";
215 for (FunctionType::param_iterator I = FTy->param_begin(),
216 E = FTy->param_end(); I != E; ++I) {
217 if (I != FTy->param_begin())
218 OS << ", ";
219 CalcTypeName(*I, TypeStack, OS);
221 if (FTy->isVarArg()) {
222 if (FTy->getNumParams()) OS << ", ";
223 OS << "...";
225 OS << ')';
226 break;
228 case Type::StructTyID: {
229 const StructType *STy = cast<StructType>(Ty);
230 if (STy->isPacked())
231 OS << '<';
232 OS << '{';
233 for (StructType::element_iterator I = STy->element_begin(),
234 E = STy->element_end(); I != E; ++I) {
235 OS << ' ';
236 CalcTypeName(*I, TypeStack, OS);
237 if (llvm::next(I) == STy->element_end())
238 OS << ' ';
239 else
240 OS << ',';
242 OS << '}';
243 if (STy->isPacked())
244 OS << '>';
245 break;
247 case Type::PointerTyID: {
248 const PointerType *PTy = cast<PointerType>(Ty);
249 CalcTypeName(PTy->getElementType(), TypeStack, OS);
250 if (unsigned AddressSpace = PTy->getAddressSpace())
251 OS << " addrspace(" << AddressSpace << ')';
252 OS << '*';
253 break;
255 case Type::ArrayTyID: {
256 const ArrayType *ATy = cast<ArrayType>(Ty);
257 OS << '[' << ATy->getNumElements() << " x ";
258 CalcTypeName(ATy->getElementType(), TypeStack, OS);
259 OS << ']';
260 break;
262 case Type::VectorTyID: {
263 const VectorType *PTy = cast<VectorType>(Ty);
264 OS << "<" << PTy->getNumElements() << " x ";
265 CalcTypeName(PTy->getElementType(), TypeStack, OS);
266 OS << '>';
267 break;
269 case Type::OpaqueTyID:
270 OS << "opaque";
271 break;
272 default:
273 OS << "<unrecognized-type>";
274 break;
277 TypeStack.pop_back(); // Remove self from stack.
280 /// printTypeInt - The internal guts of printing out a type that has a
281 /// potentially named portion.
283 void TypePrinting::print(const Type *Ty, raw_ostream &OS,
284 bool IgnoreTopLevelName) {
285 // Check to see if the type is named.
286 DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
287 if (!IgnoreTopLevelName) {
288 DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
289 if (I != TM.end()) {
290 OS << I->second;
291 return;
295 // Otherwise we have a type that has not been named but is a derived type.
296 // Carefully recurse the type hierarchy to print out any contained symbolic
297 // names.
298 SmallVector<const Type *, 16> TypeStack;
299 std::string TypeName;
301 raw_string_ostream TypeOS(TypeName);
302 CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
303 OS << TypeOS.str();
305 // Cache type name for later use.
306 if (!IgnoreTopLevelName)
307 TM.insert(std::make_pair(Ty, TypeOS.str()));
310 namespace {
311 class TypeFinder {
312 // To avoid walking constant expressions multiple times and other IR
313 // objects, we keep several helper maps.
314 DenseSet<const Value*> VisitedConstants;
315 DenseSet<const Type*> VisitedTypes;
317 TypePrinting &TP;
318 std::vector<const Type*> &NumberedTypes;
319 public:
320 TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
321 : TP(tp), NumberedTypes(numberedTypes) {}
323 void Run(const Module &M) {
324 // Get types from the type symbol table. This gets opaque types referened
325 // only through derived named types.
326 const TypeSymbolTable &ST = M.getTypeSymbolTable();
327 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
328 TI != E; ++TI)
329 IncorporateType(TI->second);
331 // Get types from global variables.
332 for (Module::const_global_iterator I = M.global_begin(),
333 E = M.global_end(); I != E; ++I) {
334 IncorporateType(I->getType());
335 if (I->hasInitializer())
336 IncorporateValue(I->getInitializer());
339 // Get types from aliases.
340 for (Module::const_alias_iterator I = M.alias_begin(),
341 E = M.alias_end(); I != E; ++I) {
342 IncorporateType(I->getType());
343 IncorporateValue(I->getAliasee());
346 // Get types from functions.
347 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
348 IncorporateType(FI->getType());
350 for (Function::const_iterator BB = FI->begin(), E = FI->end();
351 BB != E;++BB)
352 for (BasicBlock::const_iterator II = BB->begin(),
353 E = BB->end(); II != E; ++II) {
354 const Instruction &I = *II;
355 // Incorporate the type of the instruction and all its operands.
356 IncorporateType(I.getType());
357 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
358 OI != OE; ++OI)
359 IncorporateValue(*OI);
364 private:
365 void IncorporateType(const Type *Ty) {
366 // Check to see if we're already visited this type.
367 if (!VisitedTypes.insert(Ty).second)
368 return;
370 // If this is a structure or opaque type, add a name for the type.
371 if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
372 || Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
373 TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
374 NumberedTypes.push_back(Ty);
377 // Recursively walk all contained types.
378 for (Type::subtype_iterator I = Ty->subtype_begin(),
379 E = Ty->subtype_end(); I != E; ++I)
380 IncorporateType(*I);
383 /// IncorporateValue - This method is used to walk operand lists finding
384 /// types hiding in constant expressions and other operands that won't be
385 /// walked in other ways. GlobalValues, basic blocks, instructions, and
386 /// inst operands are all explicitly enumerated.
387 void IncorporateValue(const Value *V) {
388 if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
390 // Already visited?
391 if (!VisitedConstants.insert(V).second)
392 return;
394 // Check this type.
395 IncorporateType(V->getType());
397 // Look in operands for types.
398 const Constant *C = cast<Constant>(V);
399 for (Constant::const_op_iterator I = C->op_begin(),
400 E = C->op_end(); I != E;++I)
401 IncorporateValue(*I);
404 } // end anonymous namespace
407 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
408 /// the specified module to the TypePrinter and all numbered types to it and the
409 /// NumberedTypes table.
410 static void AddModuleTypesToPrinter(TypePrinting &TP,
411 std::vector<const Type*> &NumberedTypes,
412 const Module *M) {
413 if (M == 0) return;
415 // If the module has a symbol table, take all global types and stuff their
416 // names into the TypeNames map.
417 const TypeSymbolTable &ST = M->getTypeSymbolTable();
418 for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
419 TI != E; ++TI) {
420 const Type *Ty = cast<Type>(TI->second);
422 // As a heuristic, don't insert pointer to primitive types, because
423 // they are used too often to have a single useful name.
424 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
425 const Type *PETy = PTy->getElementType();
426 if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
427 !PETy->isOpaqueTy())
428 continue;
431 // Likewise don't insert primitives either.
432 if (Ty->isIntegerTy() || Ty->isPrimitiveType())
433 continue;
435 // Get the name as a string and insert it into TypeNames.
436 std::string NameStr;
437 raw_string_ostream NameROS(NameStr);
438 formatted_raw_ostream NameOS(NameROS);
439 PrintLLVMName(NameOS, TI->first, LocalPrefix);
440 NameOS.flush();
441 TP.addTypeName(Ty, NameStr);
444 // Walk the entire module to find references to unnamed structure and opaque
445 // types. This is required for correctness by opaque types (because multiple
446 // uses of an unnamed opaque type needs to be referred to by the same ID) and
447 // it shrinks complex recursive structure types substantially in some cases.
448 TypeFinder(TP, NumberedTypes).Run(*M);
452 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
453 /// type, iff there is an entry in the modules symbol table for the specified
454 /// type or one of it's component types.
456 void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
457 TypePrinting Printer;
458 std::vector<const Type*> NumberedTypes;
459 AddModuleTypesToPrinter(Printer, NumberedTypes, M);
460 Printer.print(Ty, OS);
463 //===----------------------------------------------------------------------===//
464 // SlotTracker Class: Enumerate slot numbers for unnamed values
465 //===----------------------------------------------------------------------===//
467 namespace {
469 /// This class provides computation of slot numbers for LLVM Assembly writing.
471 class SlotTracker {
472 public:
473 /// ValueMap - A mapping of Values to slot numbers.
474 typedef DenseMap<const Value*, unsigned> ValueMap;
476 private:
477 /// TheModule - The module for which we are holding slot numbers.
478 const Module* TheModule;
480 /// TheFunction - The function for which we are holding slot numbers.
481 const Function* TheFunction;
482 bool FunctionProcessed;
484 /// mMap - The TypePlanes map for the module level data.
485 ValueMap mMap;
486 unsigned mNext;
488 /// fMap - The TypePlanes map for the function level data.
489 ValueMap fMap;
490 unsigned fNext;
492 /// mdnMap - Map for MDNodes.
493 DenseMap<const MDNode*, unsigned> mdnMap;
494 unsigned mdnNext;
495 public:
496 /// Construct from a module
497 explicit SlotTracker(const Module *M);
498 /// Construct from a function, starting out in incorp state.
499 explicit SlotTracker(const Function *F);
501 /// Return the slot number of the specified value in it's type
502 /// plane. If something is not in the SlotTracker, return -1.
503 int getLocalSlot(const Value *V);
504 int getGlobalSlot(const GlobalValue *V);
505 int getMetadataSlot(const MDNode *N);
507 /// If you'd like to deal with a function instead of just a module, use
508 /// this method to get its data into the SlotTracker.
509 void incorporateFunction(const Function *F) {
510 TheFunction = F;
511 FunctionProcessed = false;
514 /// After calling incorporateFunction, use this method to remove the
515 /// most recently incorporated function from the SlotTracker. This
516 /// will reset the state of the machine back to just the module contents.
517 void purgeFunction();
519 /// MDNode map iterators.
520 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
521 mdn_iterator mdn_begin() { return mdnMap.begin(); }
522 mdn_iterator mdn_end() { return mdnMap.end(); }
523 unsigned mdn_size() const { return mdnMap.size(); }
524 bool mdn_empty() const { return mdnMap.empty(); }
526 /// This function does the actual initialization.
527 inline void initialize();
529 // Implementation Details
530 private:
531 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
532 void CreateModuleSlot(const GlobalValue *V);
534 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
535 void CreateMetadataSlot(const MDNode *N);
537 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
538 void CreateFunctionSlot(const Value *V);
540 /// Add all of the module level global variables (and their initializers)
541 /// and function declarations, but not the contents of those functions.
542 void processModule();
544 /// Add all of the functions arguments, basic blocks, and instructions.
545 void processFunction();
547 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
548 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
551 } // end anonymous namespace
554 static SlotTracker *createSlotTracker(const Value *V) {
555 if (const Argument *FA = dyn_cast<Argument>(V))
556 return new SlotTracker(FA->getParent());
558 if (const Instruction *I = dyn_cast<Instruction>(V))
559 return new SlotTracker(I->getParent()->getParent());
561 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
562 return new SlotTracker(BB->getParent());
564 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
565 return new SlotTracker(GV->getParent());
567 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
568 return new SlotTracker(GA->getParent());
570 if (const Function *Func = dyn_cast<Function>(V))
571 return new SlotTracker(Func);
573 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
574 if (!MD->isFunctionLocal())
575 return new SlotTracker(MD->getFunction());
577 return new SlotTracker((Function *)0);
580 return 0;
583 #if 0
584 #define ST_DEBUG(X) dbgs() << X
585 #else
586 #define ST_DEBUG(X)
587 #endif
589 // Module level constructor. Causes the contents of the Module (sans functions)
590 // to be added to the slot table.
591 SlotTracker::SlotTracker(const Module *M)
592 : TheModule(M), TheFunction(0), FunctionProcessed(false),
593 mNext(0), fNext(0), mdnNext(0) {
596 // Function level constructor. Causes the contents of the Module and the one
597 // function provided to be added to the slot table.
598 SlotTracker::SlotTracker(const Function *F)
599 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
600 mNext(0), fNext(0), mdnNext(0) {
603 inline void SlotTracker::initialize() {
604 if (TheModule) {
605 processModule();
606 TheModule = 0; ///< Prevent re-processing next time we're called.
609 if (TheFunction && !FunctionProcessed)
610 processFunction();
613 // Iterate through all the global variables, functions, and global
614 // variable initializers and create slots for them.
615 void SlotTracker::processModule() {
616 ST_DEBUG("begin processModule!\n");
618 // Add all of the unnamed global variables to the value table.
619 for (Module::const_global_iterator I = TheModule->global_begin(),
620 E = TheModule->global_end(); I != E; ++I) {
621 if (!I->hasName())
622 CreateModuleSlot(I);
625 // Add metadata used by named metadata.
626 for (Module::const_named_metadata_iterator
627 I = TheModule->named_metadata_begin(),
628 E = TheModule->named_metadata_end(); I != E; ++I) {
629 const NamedMDNode *NMD = I;
630 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
631 CreateMetadataSlot(NMD->getOperand(i));
634 // Add all the unnamed functions to the table.
635 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
636 I != E; ++I)
637 if (!I->hasName())
638 CreateModuleSlot(I);
640 ST_DEBUG("end processModule!\n");
643 // Process the arguments, basic blocks, and instructions of a function.
644 void SlotTracker::processFunction() {
645 ST_DEBUG("begin processFunction!\n");
646 fNext = 0;
648 // Add all the function arguments with no names.
649 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
650 AE = TheFunction->arg_end(); AI != AE; ++AI)
651 if (!AI->hasName())
652 CreateFunctionSlot(AI);
654 ST_DEBUG("Inserting Instructions:\n");
656 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
658 // Add all of the basic blocks and instructions with no names.
659 for (Function::const_iterator BB = TheFunction->begin(),
660 E = TheFunction->end(); BB != E; ++BB) {
661 if (!BB->hasName())
662 CreateFunctionSlot(BB);
664 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
665 ++I) {
666 if (!I->getType()->isVoidTy() && !I->hasName())
667 CreateFunctionSlot(I);
669 // Intrinsics can directly use metadata. We allow direct calls to any
670 // llvm.foo function here, because the target may not be linked into the
671 // optimizer.
672 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
673 if (Function *F = CI->getCalledFunction())
674 if (F->getName().startswith("llvm."))
675 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
676 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
677 CreateMetadataSlot(N);
680 // Process metadata attached with this instruction.
681 I->getAllMetadata(MDForInst);
682 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
683 CreateMetadataSlot(MDForInst[i].second);
684 MDForInst.clear();
688 FunctionProcessed = true;
690 ST_DEBUG("end processFunction!\n");
693 /// Clean up after incorporating a function. This is the only way to get out of
694 /// the function incorporation state that affects get*Slot/Create*Slot. Function
695 /// incorporation state is indicated by TheFunction != 0.
696 void SlotTracker::purgeFunction() {
697 ST_DEBUG("begin purgeFunction!\n");
698 fMap.clear(); // Simply discard the function level map
699 TheFunction = 0;
700 FunctionProcessed = false;
701 ST_DEBUG("end purgeFunction!\n");
704 /// getGlobalSlot - Get the slot number of a global value.
705 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
706 // Check for uninitialized state and do lazy initialization.
707 initialize();
709 // Find the type plane in the module map
710 ValueMap::iterator MI = mMap.find(V);
711 return MI == mMap.end() ? -1 : (int)MI->second;
714 /// getMetadataSlot - Get the slot number of a MDNode.
715 int SlotTracker::getMetadataSlot(const MDNode *N) {
716 // Check for uninitialized state and do lazy initialization.
717 initialize();
719 // Find the type plane in the module map
720 mdn_iterator MI = mdnMap.find(N);
721 return MI == mdnMap.end() ? -1 : (int)MI->second;
725 /// getLocalSlot - Get the slot number for a value that is local to a function.
726 int SlotTracker::getLocalSlot(const Value *V) {
727 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
729 // Check for uninitialized state and do lazy initialization.
730 initialize();
732 ValueMap::iterator FI = fMap.find(V);
733 return FI == fMap.end() ? -1 : (int)FI->second;
737 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
738 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
739 assert(V && "Can't insert a null Value into SlotTracker!");
740 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
741 assert(!V->hasName() && "Doesn't need a slot!");
743 unsigned DestSlot = mNext++;
744 mMap[V] = DestSlot;
746 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
747 DestSlot << " [");
748 // G = Global, F = Function, A = Alias, o = other
749 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
750 (isa<Function>(V) ? 'F' :
751 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
754 /// CreateSlot - Create a new slot for the specified value if it has no name.
755 void SlotTracker::CreateFunctionSlot(const Value *V) {
756 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
758 unsigned DestSlot = fNext++;
759 fMap[V] = DestSlot;
761 // G = Global, F = Function, o = other
762 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
763 DestSlot << " [o]\n");
766 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
767 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
768 assert(N && "Can't insert a null Value into SlotTracker!");
770 // Don't insert if N is a function-local metadata, these are always printed
771 // inline.
772 if (!N->isFunctionLocal()) {
773 mdn_iterator I = mdnMap.find(N);
774 if (I != mdnMap.end())
775 return;
777 unsigned DestSlot = mdnNext++;
778 mdnMap[N] = DestSlot;
781 // Recursively add any MDNodes referenced by operands.
782 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
783 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
784 CreateMetadataSlot(Op);
787 //===----------------------------------------------------------------------===//
788 // AsmWriter Implementation
789 //===----------------------------------------------------------------------===//
791 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
792 TypePrinting *TypePrinter,
793 SlotTracker *Machine,
794 const Module *Context);
798 static const char *getPredicateText(unsigned predicate) {
799 const char * pred = "unknown";
800 switch (predicate) {
801 case FCmpInst::FCMP_FALSE: pred = "false"; break;
802 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
803 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
804 case FCmpInst::FCMP_OGE: pred = "oge"; break;
805 case FCmpInst::FCMP_OLT: pred = "olt"; break;
806 case FCmpInst::FCMP_OLE: pred = "ole"; break;
807 case FCmpInst::FCMP_ONE: pred = "one"; break;
808 case FCmpInst::FCMP_ORD: pred = "ord"; break;
809 case FCmpInst::FCMP_UNO: pred = "uno"; break;
810 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
811 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
812 case FCmpInst::FCMP_UGE: pred = "uge"; break;
813 case FCmpInst::FCMP_ULT: pred = "ult"; break;
814 case FCmpInst::FCMP_ULE: pred = "ule"; break;
815 case FCmpInst::FCMP_UNE: pred = "une"; break;
816 case FCmpInst::FCMP_TRUE: pred = "true"; break;
817 case ICmpInst::ICMP_EQ: pred = "eq"; break;
818 case ICmpInst::ICMP_NE: pred = "ne"; break;
819 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
820 case ICmpInst::ICMP_SGE: pred = "sge"; break;
821 case ICmpInst::ICMP_SLT: pred = "slt"; break;
822 case ICmpInst::ICMP_SLE: pred = "sle"; break;
823 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
824 case ICmpInst::ICMP_UGE: pred = "uge"; break;
825 case ICmpInst::ICMP_ULT: pred = "ult"; break;
826 case ICmpInst::ICMP_ULE: pred = "ule"; break;
828 return pred;
832 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
833 if (const OverflowingBinaryOperator *OBO =
834 dyn_cast<OverflowingBinaryOperator>(U)) {
835 if (OBO->hasNoUnsignedWrap())
836 Out << " nuw";
837 if (OBO->hasNoSignedWrap())
838 Out << " nsw";
839 } else if (const PossiblyExactOperator *Div =
840 dyn_cast<PossiblyExactOperator>(U)) {
841 if (Div->isExact())
842 Out << " exact";
843 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
844 if (GEP->isInBounds())
845 Out << " inbounds";
849 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
850 TypePrinting &TypePrinter,
851 SlotTracker *Machine,
852 const Module *Context) {
853 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
854 if (CI->getType()->isIntegerTy(1)) {
855 Out << (CI->getZExtValue() ? "true" : "false");
856 return;
858 Out << CI->getValue();
859 return;
862 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
863 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
864 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
865 // We would like to output the FP constant value in exponential notation,
866 // but we cannot do this if doing so will lose precision. Check here to
867 // make sure that we only output it in exponential format if we can parse
868 // the value back and get the same value.
870 bool ignored;
871 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
872 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
873 CFP->getValueAPF().convertToFloat();
874 SmallString<128> StrVal;
875 raw_svector_ostream(StrVal) << Val;
877 // Check to make sure that the stringized number is not some string like
878 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
879 // that the string matches the "[-+]?[0-9]" regex.
881 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
882 ((StrVal[0] == '-' || StrVal[0] == '+') &&
883 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
884 // Reparse stringized version!
885 if (atof(StrVal.c_str()) == Val) {
886 Out << StrVal.str();
887 return;
890 // Otherwise we could not reparse it to exactly the same value, so we must
891 // output the string in hexadecimal format! Note that loading and storing
892 // floating point types changes the bits of NaNs on some hosts, notably
893 // x86, so we must not use these types.
894 assert(sizeof(double) == sizeof(uint64_t) &&
895 "assuming that double is 64 bits!");
896 char Buffer[40];
897 APFloat apf = CFP->getValueAPF();
898 // Floats are represented in ASCII IR as double, convert.
899 if (!isDouble)
900 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
901 &ignored);
902 Out << "0x" <<
903 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
904 Buffer+40);
905 return;
908 // Some form of long double. These appear as a magic letter identifying
909 // the type, then a fixed number of hex digits.
910 Out << "0x";
911 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
912 Out << 'K';
913 // api needed to prevent premature destruction
914 APInt api = CFP->getValueAPF().bitcastToAPInt();
915 const uint64_t* p = api.getRawData();
916 uint64_t word = p[1];
917 int shiftcount=12;
918 int width = api.getBitWidth();
919 for (int j=0; j<width; j+=4, shiftcount-=4) {
920 unsigned int nibble = (word>>shiftcount) & 15;
921 if (nibble < 10)
922 Out << (unsigned char)(nibble + '0');
923 else
924 Out << (unsigned char)(nibble - 10 + 'A');
925 if (shiftcount == 0 && j+4 < width) {
926 word = *p;
927 shiftcount = 64;
928 if (width-j-4 < 64)
929 shiftcount = width-j-4;
932 return;
933 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
934 Out << 'L';
935 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
936 Out << 'M';
937 else
938 llvm_unreachable("Unsupported floating point type");
939 // api needed to prevent premature destruction
940 APInt api = CFP->getValueAPF().bitcastToAPInt();
941 const uint64_t* p = api.getRawData();
942 uint64_t word = *p;
943 int shiftcount=60;
944 int width = api.getBitWidth();
945 for (int j=0; j<width; j+=4, shiftcount-=4) {
946 unsigned int nibble = (word>>shiftcount) & 15;
947 if (nibble < 10)
948 Out << (unsigned char)(nibble + '0');
949 else
950 Out << (unsigned char)(nibble - 10 + 'A');
951 if (shiftcount == 0 && j+4 < width) {
952 word = *(++p);
953 shiftcount = 64;
954 if (width-j-4 < 64)
955 shiftcount = width-j-4;
958 return;
961 if (isa<ConstantAggregateZero>(CV)) {
962 Out << "zeroinitializer";
963 return;
966 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
967 Out << "blockaddress(";
968 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
969 Context);
970 Out << ", ";
971 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
972 Context);
973 Out << ")";
974 return;
977 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
978 // As a special case, print the array as a string if it is an array of
979 // i8 with ConstantInt values.
981 const Type *ETy = CA->getType()->getElementType();
982 if (CA->isString()) {
983 Out << "c\"";
984 PrintEscapedString(CA->getAsString(), Out);
985 Out << '"';
986 } else { // Cannot output in string format...
987 Out << '[';
988 if (CA->getNumOperands()) {
989 TypePrinter.print(ETy, Out);
990 Out << ' ';
991 WriteAsOperandInternal(Out, CA->getOperand(0),
992 &TypePrinter, Machine,
993 Context);
994 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
995 Out << ", ";
996 TypePrinter.print(ETy, Out);
997 Out << ' ';
998 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
999 Context);
1002 Out << ']';
1004 return;
1007 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1008 if (CS->getType()->isPacked())
1009 Out << '<';
1010 Out << '{';
1011 unsigned N = CS->getNumOperands();
1012 if (N) {
1013 Out << ' ';
1014 TypePrinter.print(CS->getOperand(0)->getType(), Out);
1015 Out << ' ';
1017 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
1018 Context);
1020 for (unsigned i = 1; i < N; i++) {
1021 Out << ", ";
1022 TypePrinter.print(CS->getOperand(i)->getType(), Out);
1023 Out << ' ';
1025 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
1026 Context);
1028 Out << ' ';
1031 Out << '}';
1032 if (CS->getType()->isPacked())
1033 Out << '>';
1034 return;
1037 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1038 const Type *ETy = CP->getType()->getElementType();
1039 assert(CP->getNumOperands() > 0 &&
1040 "Number of operands for a PackedConst must be > 0");
1041 Out << '<';
1042 TypePrinter.print(ETy, Out);
1043 Out << ' ';
1044 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
1045 Context);
1046 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1047 Out << ", ";
1048 TypePrinter.print(ETy, Out);
1049 Out << ' ';
1050 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
1051 Context);
1053 Out << '>';
1054 return;
1057 if (isa<ConstantPointerNull>(CV)) {
1058 Out << "null";
1059 return;
1062 if (isa<UndefValue>(CV)) {
1063 Out << "undef";
1064 return;
1067 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1068 Out << CE->getOpcodeName();
1069 WriteOptimizationInfo(Out, CE);
1070 if (CE->isCompare())
1071 Out << ' ' << getPredicateText(CE->getPredicate());
1072 Out << " (";
1074 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1075 TypePrinter.print((*OI)->getType(), Out);
1076 Out << ' ';
1077 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
1078 if (OI+1 != CE->op_end())
1079 Out << ", ";
1082 if (CE->hasIndices()) {
1083 ArrayRef<unsigned> Indices = CE->getIndices();
1084 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1085 Out << ", " << Indices[i];
1088 if (CE->isCast()) {
1089 Out << " to ";
1090 TypePrinter.print(CE->getType(), Out);
1093 Out << ')';
1094 return;
1097 Out << "<placeholder or erroneous Constant>";
1100 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1101 TypePrinting *TypePrinter,
1102 SlotTracker *Machine,
1103 const Module *Context) {
1104 Out << "!{";
1105 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1106 const Value *V = Node->getOperand(mi);
1107 if (V == 0)
1108 Out << "null";
1109 else {
1110 TypePrinter->print(V->getType(), Out);
1111 Out << ' ';
1112 WriteAsOperandInternal(Out, Node->getOperand(mi),
1113 TypePrinter, Machine, Context);
1115 if (mi + 1 != me)
1116 Out << ", ";
1119 Out << "}";
1123 /// WriteAsOperand - Write the name of the specified value out to the specified
1124 /// ostream. This can be useful when you just want to print int %reg126, not
1125 /// the whole instruction that generated it.
1127 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1128 TypePrinting *TypePrinter,
1129 SlotTracker *Machine,
1130 const Module *Context) {
1131 if (V->hasName()) {
1132 PrintLLVMName(Out, V);
1133 return;
1136 const Constant *CV = dyn_cast<Constant>(V);
1137 if (CV && !isa<GlobalValue>(CV)) {
1138 assert(TypePrinter && "Constants require TypePrinting!");
1139 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1140 return;
1143 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1144 Out << "asm ";
1145 if (IA->hasSideEffects())
1146 Out << "sideeffect ";
1147 if (IA->isAlignStack())
1148 Out << "alignstack ";
1149 Out << '"';
1150 PrintEscapedString(IA->getAsmString(), Out);
1151 Out << "\", \"";
1152 PrintEscapedString(IA->getConstraintString(), Out);
1153 Out << '"';
1154 return;
1157 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1158 if (N->isFunctionLocal()) {
1159 // Print metadata inline, not via slot reference number.
1160 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1161 return;
1164 if (!Machine) {
1165 if (N->isFunctionLocal())
1166 Machine = new SlotTracker(N->getFunction());
1167 else
1168 Machine = new SlotTracker(Context);
1170 int Slot = Machine->getMetadataSlot(N);
1171 if (Slot == -1)
1172 Out << "<badref>";
1173 else
1174 Out << '!' << Slot;
1175 return;
1178 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1179 Out << "!\"";
1180 PrintEscapedString(MDS->getString(), Out);
1181 Out << '"';
1182 return;
1185 if (V->getValueID() == Value::PseudoSourceValueVal ||
1186 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1187 V->print(Out);
1188 return;
1191 char Prefix = '%';
1192 int Slot;
1193 if (Machine) {
1194 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1195 Slot = Machine->getGlobalSlot(GV);
1196 Prefix = '@';
1197 } else {
1198 Slot = Machine->getLocalSlot(V);
1200 } else {
1201 Machine = createSlotTracker(V);
1202 if (Machine) {
1203 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1204 Slot = Machine->getGlobalSlot(GV);
1205 Prefix = '@';
1206 } else {
1207 Slot = Machine->getLocalSlot(V);
1209 delete Machine;
1210 } else {
1211 Slot = -1;
1215 if (Slot != -1)
1216 Out << Prefix << Slot;
1217 else
1218 Out << "<badref>";
1221 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1222 bool PrintType, const Module *Context) {
1224 // Fast path: Don't construct and populate a TypePrinting object if we
1225 // won't be needing any types printed.
1226 if (!PrintType &&
1227 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1228 V->hasName() || isa<GlobalValue>(V))) {
1229 WriteAsOperandInternal(Out, V, 0, 0, Context);
1230 return;
1233 if (Context == 0) Context = getModuleFromVal(V);
1235 TypePrinting TypePrinter;
1236 std::vector<const Type*> NumberedTypes;
1237 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1238 if (PrintType) {
1239 TypePrinter.print(V->getType(), Out);
1240 Out << ' ';
1243 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1246 namespace {
1248 class AssemblyWriter {
1249 formatted_raw_ostream &Out;
1250 SlotTracker &Machine;
1251 const Module *TheModule;
1252 TypePrinting TypePrinter;
1253 AssemblyAnnotationWriter *AnnotationWriter;
1254 std::vector<const Type*> NumberedTypes;
1256 public:
1257 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1258 const Module *M,
1259 AssemblyAnnotationWriter *AAW)
1260 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1261 AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1264 void printMDNodeBody(const MDNode *MD);
1265 void printNamedMDNode(const NamedMDNode *NMD);
1267 void printModule(const Module *M);
1269 void writeOperand(const Value *Op, bool PrintType);
1270 void writeParamOperand(const Value *Operand, Attributes Attrs);
1272 void writeAllMDNodes();
1274 void printTypeSymbolTable(const TypeSymbolTable &ST);
1275 void printGlobal(const GlobalVariable *GV);
1276 void printAlias(const GlobalAlias *GV);
1277 void printFunction(const Function *F);
1278 void printArgument(const Argument *FA, Attributes Attrs);
1279 void printBasicBlock(const BasicBlock *BB);
1280 void printInstruction(const Instruction &I);
1282 private:
1283 // printInfoComment - Print a little comment after the instruction indicating
1284 // which slot it occupies.
1285 void printInfoComment(const Value &V);
1287 } // end of anonymous namespace
1289 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1290 if (Operand == 0) {
1291 Out << "<null operand!>";
1292 return;
1294 if (PrintType) {
1295 TypePrinter.print(Operand->getType(), Out);
1296 Out << ' ';
1298 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1301 void AssemblyWriter::writeParamOperand(const Value *Operand,
1302 Attributes Attrs) {
1303 if (Operand == 0) {
1304 Out << "<null operand!>";
1305 return;
1308 // Print the type
1309 TypePrinter.print(Operand->getType(), Out);
1310 // Print parameter attributes list
1311 if (Attrs != Attribute::None)
1312 Out << ' ' << Attribute::getAsString(Attrs);
1313 Out << ' ';
1314 // Print the operand
1315 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1318 void AssemblyWriter::printModule(const Module *M) {
1319 if (!M->getModuleIdentifier().empty() &&
1320 // Don't print the ID if it will start a new line (which would
1321 // require a comment char before it).
1322 M->getModuleIdentifier().find('\n') == std::string::npos)
1323 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1325 if (!M->getDataLayout().empty())
1326 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1327 if (!M->getTargetTriple().empty())
1328 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1330 if (!M->getModuleInlineAsm().empty()) {
1331 // Split the string into lines, to make it easier to read the .ll file.
1332 std::string Asm = M->getModuleInlineAsm();
1333 size_t CurPos = 0;
1334 size_t NewLine = Asm.find_first_of('\n', CurPos);
1335 Out << '\n';
1336 while (NewLine != std::string::npos) {
1337 // We found a newline, print the portion of the asm string from the
1338 // last newline up to this newline.
1339 Out << "module asm \"";
1340 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1341 Out);
1342 Out << "\"\n";
1343 CurPos = NewLine+1;
1344 NewLine = Asm.find_first_of('\n', CurPos);
1346 std::string rest(Asm.begin()+CurPos, Asm.end());
1347 if (!rest.empty()) {
1348 Out << "module asm \"";
1349 PrintEscapedString(rest, Out);
1350 Out << "\"\n";
1354 // Loop over the dependent libraries and emit them.
1355 Module::lib_iterator LI = M->lib_begin();
1356 Module::lib_iterator LE = M->lib_end();
1357 if (LI != LE) {
1358 Out << '\n';
1359 Out << "deplibs = [ ";
1360 while (LI != LE) {
1361 Out << '"' << *LI << '"';
1362 ++LI;
1363 if (LI != LE)
1364 Out << ", ";
1366 Out << " ]";
1369 // Loop over the symbol table, emitting all id'd types.
1370 if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1371 printTypeSymbolTable(M->getTypeSymbolTable());
1373 // Output all globals.
1374 if (!M->global_empty()) Out << '\n';
1375 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1376 I != E; ++I)
1377 printGlobal(I);
1379 // Output all aliases.
1380 if (!M->alias_empty()) Out << "\n";
1381 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1382 I != E; ++I)
1383 printAlias(I);
1385 // Output all of the functions.
1386 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1387 printFunction(I);
1389 // Output named metadata.
1390 if (!M->named_metadata_empty()) Out << '\n';
1392 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1393 E = M->named_metadata_end(); I != E; ++I)
1394 printNamedMDNode(I);
1396 // Output metadata.
1397 if (!Machine.mdn_empty()) {
1398 Out << '\n';
1399 writeAllMDNodes();
1403 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1404 Out << "!" << NMD->getName() << " = !{";
1405 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1406 if (i) Out << ", ";
1407 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1408 if (Slot == -1)
1409 Out << "<badref>";
1410 else
1411 Out << '!' << Slot;
1413 Out << "}\n";
1417 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1418 formatted_raw_ostream &Out) {
1419 switch (LT) {
1420 case GlobalValue::ExternalLinkage: break;
1421 case GlobalValue::PrivateLinkage: Out << "private "; break;
1422 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1423 case GlobalValue::LinkerPrivateWeakLinkage:
1424 Out << "linker_private_weak ";
1425 break;
1426 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1427 Out << "linker_private_weak_def_auto ";
1428 break;
1429 case GlobalValue::InternalLinkage: Out << "internal "; break;
1430 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1431 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1432 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1433 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1434 case GlobalValue::CommonLinkage: Out << "common "; break;
1435 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1436 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1437 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1438 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1439 case GlobalValue::AvailableExternallyLinkage:
1440 Out << "available_externally ";
1441 break;
1446 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1447 formatted_raw_ostream &Out) {
1448 switch (Vis) {
1449 case GlobalValue::DefaultVisibility: break;
1450 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1451 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1455 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1456 if (GV->isMaterializable())
1457 Out << "; Materializable\n";
1459 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1460 Out << " = ";
1462 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1463 Out << "external ";
1465 PrintLinkage(GV->getLinkage(), Out);
1466 PrintVisibility(GV->getVisibility(), Out);
1468 if (GV->isThreadLocal()) Out << "thread_local ";
1469 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1470 Out << "addrspace(" << AddressSpace << ") ";
1471 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1472 Out << (GV->isConstant() ? "constant " : "global ");
1473 TypePrinter.print(GV->getType()->getElementType(), Out);
1475 if (GV->hasInitializer()) {
1476 Out << ' ';
1477 writeOperand(GV->getInitializer(), false);
1480 if (GV->hasSection()) {
1481 Out << ", section \"";
1482 PrintEscapedString(GV->getSection(), Out);
1483 Out << '"';
1485 if (GV->getAlignment())
1486 Out << ", align " << GV->getAlignment();
1488 printInfoComment(*GV);
1489 Out << '\n';
1492 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1493 if (GA->isMaterializable())
1494 Out << "; Materializable\n";
1496 // Don't crash when dumping partially built GA
1497 if (!GA->hasName())
1498 Out << "<<nameless>> = ";
1499 else {
1500 PrintLLVMName(Out, GA);
1501 Out << " = ";
1503 PrintVisibility(GA->getVisibility(), Out);
1505 Out << "alias ";
1507 PrintLinkage(GA->getLinkage(), Out);
1509 const Constant *Aliasee = GA->getAliasee();
1511 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1512 TypePrinter.print(GV->getType(), Out);
1513 Out << ' ';
1514 PrintLLVMName(Out, GV);
1515 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1516 TypePrinter.print(F->getFunctionType(), Out);
1517 Out << "* ";
1519 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1520 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1521 TypePrinter.print(GA->getType(), Out);
1522 Out << ' ';
1523 PrintLLVMName(Out, GA);
1524 } else {
1525 const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1526 // The only valid GEP is an all zero GEP.
1527 assert((CE->getOpcode() == Instruction::BitCast ||
1528 CE->getOpcode() == Instruction::GetElementPtr) &&
1529 "Unsupported aliasee");
1530 writeOperand(CE, false);
1533 printInfoComment(*GA);
1534 Out << '\n';
1537 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1538 // Emit all numbered types.
1539 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1540 Out << '%' << i << " = type ";
1542 // Make sure we print out at least one level of the type structure, so
1543 // that we do not get %2 = type %2
1544 TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1545 Out << '\n';
1548 // Print the named types.
1549 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1550 TI != TE; ++TI) {
1551 PrintLLVMName(Out, TI->first, LocalPrefix);
1552 Out << " = type ";
1554 // Make sure we print out at least one level of the type structure, so
1555 // that we do not get %FILE = type %FILE
1556 TypePrinter.printAtLeastOneLevel(TI->second, Out);
1557 Out << '\n';
1561 /// printFunction - Print all aspects of a function.
1563 void AssemblyWriter::printFunction(const Function *F) {
1564 // Print out the return type and name.
1565 Out << '\n';
1567 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1569 if (F->isMaterializable())
1570 Out << "; Materializable\n";
1572 if (F->isDeclaration())
1573 Out << "declare ";
1574 else
1575 Out << "define ";
1577 PrintLinkage(F->getLinkage(), Out);
1578 PrintVisibility(F->getVisibility(), Out);
1580 // Print the calling convention.
1581 switch (F->getCallingConv()) {
1582 case CallingConv::C: break; // default
1583 case CallingConv::Fast: Out << "fastcc "; break;
1584 case CallingConv::Cold: Out << "coldcc "; break;
1585 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1586 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1587 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1588 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1589 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1590 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1591 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1592 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1593 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1594 default: Out << "cc" << F->getCallingConv() << " "; break;
1597 const FunctionType *FT = F->getFunctionType();
1598 const AttrListPtr &Attrs = F->getAttributes();
1599 Attributes RetAttrs = Attrs.getRetAttributes();
1600 if (RetAttrs != Attribute::None)
1601 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1602 TypePrinter.print(F->getReturnType(), Out);
1603 Out << ' ';
1604 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1605 Out << '(';
1606 Machine.incorporateFunction(F);
1608 // Loop over the arguments, printing them...
1610 unsigned Idx = 1;
1611 if (!F->isDeclaration()) {
1612 // If this isn't a declaration, print the argument names as well.
1613 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1614 I != E; ++I) {
1615 // Insert commas as we go... the first arg doesn't get a comma
1616 if (I != F->arg_begin()) Out << ", ";
1617 printArgument(I, Attrs.getParamAttributes(Idx));
1618 Idx++;
1620 } else {
1621 // Otherwise, print the types from the function type.
1622 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1623 // Insert commas as we go... the first arg doesn't get a comma
1624 if (i) Out << ", ";
1626 // Output type...
1627 TypePrinter.print(FT->getParamType(i), Out);
1629 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1630 if (ArgAttrs != Attribute::None)
1631 Out << ' ' << Attribute::getAsString(ArgAttrs);
1635 // Finish printing arguments...
1636 if (FT->isVarArg()) {
1637 if (FT->getNumParams()) Out << ", ";
1638 Out << "..."; // Output varargs portion of signature!
1640 Out << ')';
1641 if (F->hasUnnamedAddr())
1642 Out << " unnamed_addr";
1643 Attributes FnAttrs = Attrs.getFnAttributes();
1644 if (FnAttrs != Attribute::None)
1645 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1646 if (F->hasSection()) {
1647 Out << " section \"";
1648 PrintEscapedString(F->getSection(), Out);
1649 Out << '"';
1651 if (F->getAlignment())
1652 Out << " align " << F->getAlignment();
1653 if (F->hasGC())
1654 Out << " gc \"" << F->getGC() << '"';
1655 if (F->isDeclaration()) {
1656 Out << '\n';
1657 } else {
1658 Out << " {";
1659 // Output all of the function's basic blocks.
1660 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1661 printBasicBlock(I);
1663 Out << "}\n";
1666 Machine.purgeFunction();
1669 /// printArgument - This member is called for every argument that is passed into
1670 /// the function. Simply print it out
1672 void AssemblyWriter::printArgument(const Argument *Arg,
1673 Attributes Attrs) {
1674 // Output type...
1675 TypePrinter.print(Arg->getType(), Out);
1677 // Output parameter attributes list
1678 if (Attrs != Attribute::None)
1679 Out << ' ' << Attribute::getAsString(Attrs);
1681 // Output name, if available...
1682 if (Arg->hasName()) {
1683 Out << ' ';
1684 PrintLLVMName(Out, Arg);
1688 /// printBasicBlock - This member is called for each basic block in a method.
1690 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1691 if (BB->hasName()) { // Print out the label if it exists...
1692 Out << "\n";
1693 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1694 Out << ':';
1695 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1696 Out << "\n; <label>:";
1697 int Slot = Machine.getLocalSlot(BB);
1698 if (Slot != -1)
1699 Out << Slot;
1700 else
1701 Out << "<badref>";
1704 if (BB->getParent() == 0) {
1705 Out.PadToColumn(50);
1706 Out << "; Error: Block without parent!";
1707 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1708 // Output predecessors for the block.
1709 Out.PadToColumn(50);
1710 Out << ";";
1711 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1713 if (PI == PE) {
1714 Out << " No predecessors!";
1715 } else {
1716 Out << " preds = ";
1717 writeOperand(*PI, false);
1718 for (++PI; PI != PE; ++PI) {
1719 Out << ", ";
1720 writeOperand(*PI, false);
1725 Out << "\n";
1727 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1729 // Output all of the instructions in the basic block...
1730 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1731 printInstruction(*I);
1732 Out << '\n';
1735 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1738 /// printDebugLoc - Print DebugLoc.
1739 static void printDebugLoc(const DebugLoc &DL, formatted_raw_ostream &OS) {
1740 OS << DL.getLine() << ":" << DL.getCol();
1741 if (MDNode *N = DL.getInlinedAt(getGlobalContext())) {
1742 DebugLoc IDL = DebugLoc::getFromDILocation(N);
1743 if (!IDL.isUnknown()) {
1744 OS << "@";
1745 printDebugLoc(IDL,OS);
1750 /// printInfoComment - Print a little comment after the instruction indicating
1751 /// which slot it occupies.
1753 void AssemblyWriter::printInfoComment(const Value &V) {
1754 if (AnnotationWriter) {
1755 AnnotationWriter->printInfoComment(V, Out);
1756 return;
1757 } else if (EnableDebugInfoComment) {
1758 bool Padded = false;
1759 if (const Instruction *I = dyn_cast<Instruction>(&V)) {
1760 const DebugLoc &DL = I->getDebugLoc();
1761 if (!DL.isUnknown()) {
1762 if (!Padded) {
1763 Out.PadToColumn(50);
1764 Padded = true;
1765 Out << ";";
1767 Out << " [debug line = ";
1768 printDebugLoc(DL,Out);
1769 Out << "]";
1771 if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
1772 const MDNode *Var = DDI->getVariable();
1773 if (!Padded) {
1774 Out.PadToColumn(50);
1775 Padded = true;
1776 Out << ";";
1778 if (Var && Var->getNumOperands() >= 2)
1779 if (MDString *MDS = dyn_cast_or_null<MDString>(Var->getOperand(2)))
1780 Out << " [debug variable = " << MDS->getString() << "]";
1782 else if (const DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
1783 const MDNode *Var = DVI->getVariable();
1784 if (!Padded) {
1785 Out.PadToColumn(50);
1786 Padded = true;
1787 Out << ";";
1789 if (Var && Var->getNumOperands() >= 2)
1790 if (MDString *MDS = dyn_cast_or_null<MDString>(Var->getOperand(2)))
1791 Out << " [debug variable = " << MDS->getString() << "]";
1797 // This member is called for each Instruction in a function..
1798 void AssemblyWriter::printInstruction(const Instruction &I) {
1799 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1801 // Print out indentation for an instruction.
1802 Out << " ";
1804 // Print out name if it exists...
1805 if (I.hasName()) {
1806 PrintLLVMName(Out, &I);
1807 Out << " = ";
1808 } else if (!I.getType()->isVoidTy()) {
1809 // Print out the def slot taken.
1810 int SlotNum = Machine.getLocalSlot(&I);
1811 if (SlotNum == -1)
1812 Out << "<badref> = ";
1813 else
1814 Out << '%' << SlotNum << " = ";
1817 // If this is a volatile load or store, print out the volatile marker.
1818 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1819 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1820 Out << "volatile ";
1821 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1822 // If this is a call, check if it's a tail call.
1823 Out << "tail ";
1826 // Print out the opcode...
1827 Out << I.getOpcodeName();
1829 // Print out optimization information.
1830 WriteOptimizationInfo(Out, &I);
1832 // Print out the compare instruction predicates
1833 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1834 Out << ' ' << getPredicateText(CI->getPredicate());
1836 // Print out the type of the operands...
1837 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1839 // Special case conditional branches to swizzle the condition out to the front
1840 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1841 BranchInst &BI(cast<BranchInst>(I));
1842 Out << ' ';
1843 writeOperand(BI.getCondition(), true);
1844 Out << ", ";
1845 writeOperand(BI.getSuccessor(0), true);
1846 Out << ", ";
1847 writeOperand(BI.getSuccessor(1), true);
1849 } else if (isa<SwitchInst>(I)) {
1850 // Special case switch instruction to get formatting nice and correct.
1851 Out << ' ';
1852 writeOperand(Operand , true);
1853 Out << ", ";
1854 writeOperand(I.getOperand(1), true);
1855 Out << " [";
1857 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1858 Out << "\n ";
1859 writeOperand(I.getOperand(op ), true);
1860 Out << ", ";
1861 writeOperand(I.getOperand(op+1), true);
1863 Out << "\n ]";
1864 } else if (isa<IndirectBrInst>(I)) {
1865 // Special case indirectbr instruction to get formatting nice and correct.
1866 Out << ' ';
1867 writeOperand(Operand, true);
1868 Out << ", [";
1870 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1871 if (i != 1)
1872 Out << ", ";
1873 writeOperand(I.getOperand(i), true);
1875 Out << ']';
1876 } else if (isa<PHINode>(I)) {
1877 Out << ' ';
1878 TypePrinter.print(I.getType(), Out);
1879 Out << ' ';
1881 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1882 if (op) Out << ", ";
1883 Out << "[ ";
1884 writeOperand(I.getOperand(op ), false); Out << ", ";
1885 writeOperand(I.getOperand(op+1), false); Out << " ]";
1887 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1888 Out << ' ';
1889 writeOperand(I.getOperand(0), true);
1890 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1891 Out << ", " << *i;
1892 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1893 Out << ' ';
1894 writeOperand(I.getOperand(0), true); Out << ", ";
1895 writeOperand(I.getOperand(1), true);
1896 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1897 Out << ", " << *i;
1898 } else if (isa<ReturnInst>(I) && !Operand) {
1899 Out << " void";
1900 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1901 // Print the calling convention being used.
1902 switch (CI->getCallingConv()) {
1903 case CallingConv::C: break; // default
1904 case CallingConv::Fast: Out << " fastcc"; break;
1905 case CallingConv::Cold: Out << " coldcc"; break;
1906 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1907 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1908 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1909 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1910 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1911 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1912 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1913 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1914 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1915 default: Out << " cc" << CI->getCallingConv(); break;
1918 Operand = CI->getCalledValue();
1919 const PointerType *PTy = cast<PointerType>(Operand->getType());
1920 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1921 const Type *RetTy = FTy->getReturnType();
1922 const AttrListPtr &PAL = CI->getAttributes();
1924 if (PAL.getRetAttributes() != Attribute::None)
1925 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1927 // If possible, print out the short form of the call instruction. We can
1928 // only do this if the first argument is a pointer to a nonvararg function,
1929 // and if the return type is not a pointer to a function.
1931 Out << ' ';
1932 if (!FTy->isVarArg() &&
1933 (!RetTy->isPointerTy() ||
1934 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1935 TypePrinter.print(RetTy, Out);
1936 Out << ' ';
1937 writeOperand(Operand, false);
1938 } else {
1939 writeOperand(Operand, true);
1941 Out << '(';
1942 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1943 if (op > 0)
1944 Out << ", ";
1945 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1947 Out << ')';
1948 if (PAL.getFnAttributes() != Attribute::None)
1949 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1950 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1951 Operand = II->getCalledValue();
1952 const PointerType *PTy = cast<PointerType>(Operand->getType());
1953 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1954 const Type *RetTy = FTy->getReturnType();
1955 const AttrListPtr &PAL = II->getAttributes();
1957 // Print the calling convention being used.
1958 switch (II->getCallingConv()) {
1959 case CallingConv::C: break; // default
1960 case CallingConv::Fast: Out << " fastcc"; break;
1961 case CallingConv::Cold: Out << " coldcc"; break;
1962 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1963 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1964 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1965 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1966 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1967 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1968 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1969 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1970 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1971 default: Out << " cc" << II->getCallingConv(); break;
1974 if (PAL.getRetAttributes() != Attribute::None)
1975 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1977 // If possible, print out the short form of the invoke instruction. We can
1978 // only do this if the first argument is a pointer to a nonvararg function,
1979 // and if the return type is not a pointer to a function.
1981 Out << ' ';
1982 if (!FTy->isVarArg() &&
1983 (!RetTy->isPointerTy() ||
1984 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1985 TypePrinter.print(RetTy, Out);
1986 Out << ' ';
1987 writeOperand(Operand, false);
1988 } else {
1989 writeOperand(Operand, true);
1991 Out << '(';
1992 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1993 if (op)
1994 Out << ", ";
1995 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1998 Out << ')';
1999 if (PAL.getFnAttributes() != Attribute::None)
2000 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
2002 Out << "\n to ";
2003 writeOperand(II->getNormalDest(), true);
2004 Out << " unwind ";
2005 writeOperand(II->getUnwindDest(), true);
2007 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
2008 Out << ' ';
2009 TypePrinter.print(AI->getType()->getElementType(), Out);
2010 if (!AI->getArraySize() || AI->isArrayAllocation()) {
2011 Out << ", ";
2012 writeOperand(AI->getArraySize(), true);
2014 if (AI->getAlignment()) {
2015 Out << ", align " << AI->getAlignment();
2017 } else if (isa<CastInst>(I)) {
2018 if (Operand) {
2019 Out << ' ';
2020 writeOperand(Operand, true); // Work with broken code
2022 Out << " to ";
2023 TypePrinter.print(I.getType(), Out);
2024 } else if (isa<VAArgInst>(I)) {
2025 if (Operand) {
2026 Out << ' ';
2027 writeOperand(Operand, true); // Work with broken code
2029 Out << ", ";
2030 TypePrinter.print(I.getType(), Out);
2031 } else if (Operand) { // Print the normal way.
2033 // PrintAllTypes - Instructions who have operands of all the same type
2034 // omit the type from all but the first operand. If the instruction has
2035 // different type operands (for example br), then they are all printed.
2036 bool PrintAllTypes = false;
2037 const Type *TheType = Operand->getType();
2039 // Select, Store and ShuffleVector always print all types.
2040 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
2041 || isa<ReturnInst>(I)) {
2042 PrintAllTypes = true;
2043 } else {
2044 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
2045 Operand = I.getOperand(i);
2046 // note that Operand shouldn't be null, but the test helps make dump()
2047 // more tolerant of malformed IR
2048 if (Operand && Operand->getType() != TheType) {
2049 PrintAllTypes = true; // We have differing types! Print them all!
2050 break;
2055 if (!PrintAllTypes) {
2056 Out << ' ';
2057 TypePrinter.print(TheType, Out);
2060 Out << ' ';
2061 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
2062 if (i) Out << ", ";
2063 writeOperand(I.getOperand(i), PrintAllTypes);
2067 // Print post operand alignment for load/store.
2068 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
2069 Out << ", align " << cast<LoadInst>(I).getAlignment();
2070 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
2071 Out << ", align " << cast<StoreInst>(I).getAlignment();
2074 // Print Metadata info.
2075 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2076 I.getAllMetadata(InstMD);
2077 if (!InstMD.empty()) {
2078 SmallVector<StringRef, 8> MDNames;
2079 I.getType()->getContext().getMDKindNames(MDNames);
2080 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2081 unsigned Kind = InstMD[i].first;
2082 if (Kind < MDNames.size()) {
2083 Out << ", !" << MDNames[Kind];
2084 } else {
2085 Out << ", !<unknown kind #" << Kind << ">";
2087 Out << ' ';
2088 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2089 TheModule);
2092 printInfoComment(I);
2095 static void WriteMDNodeComment(const MDNode *Node,
2096 formatted_raw_ostream &Out) {
2097 if (Node->getNumOperands() < 1)
2098 return;
2099 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2100 if (!CI) return;
2101 APInt Val = CI->getValue();
2102 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
2103 if (Val.ult(LLVMDebugVersion))
2104 return;
2106 Out.PadToColumn(50);
2107 if (Tag == dwarf::DW_TAG_user_base)
2108 Out << "; [ DW_TAG_user_base ]";
2109 else if (Tag.isIntN(32)) {
2110 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
2111 Out << "; [ " << TagName << " ]";
2115 void AssemblyWriter::writeAllMDNodes() {
2116 SmallVector<const MDNode *, 16> Nodes;
2117 Nodes.resize(Machine.mdn_size());
2118 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2119 I != E; ++I)
2120 Nodes[I->second] = cast<MDNode>(I->first);
2122 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2123 Out << '!' << i << " = metadata ";
2124 printMDNodeBody(Nodes[i]);
2128 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2129 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2130 WriteMDNodeComment(Node, Out);
2131 Out << "\n";
2134 //===----------------------------------------------------------------------===//
2135 // External Interface declarations
2136 //===----------------------------------------------------------------------===//
2138 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2139 SlotTracker SlotTable(this);
2140 formatted_raw_ostream OS(ROS);
2141 AssemblyWriter W(OS, SlotTable, this, AAW);
2142 W.printModule(this);
2145 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2146 SlotTracker SlotTable(getParent());
2147 formatted_raw_ostream OS(ROS);
2148 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2149 W.printNamedMDNode(this);
2152 void Type::print(raw_ostream &OS) const {
2153 if (this == 0) {
2154 OS << "<null Type>";
2155 return;
2157 TypePrinting().print(this, OS);
2160 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2161 if (this == 0) {
2162 ROS << "printing a <null> value\n";
2163 return;
2165 formatted_raw_ostream OS(ROS);
2166 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2167 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2168 SlotTracker SlotTable(F);
2169 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2170 W.printInstruction(*I);
2171 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2172 SlotTracker SlotTable(BB->getParent());
2173 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2174 W.printBasicBlock(BB);
2175 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2176 SlotTracker SlotTable(GV->getParent());
2177 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2178 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2179 W.printGlobal(V);
2180 else if (const Function *F = dyn_cast<Function>(GV))
2181 W.printFunction(F);
2182 else
2183 W.printAlias(cast<GlobalAlias>(GV));
2184 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2185 const Function *F = N->getFunction();
2186 SlotTracker SlotTable(F);
2187 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2188 W.printMDNodeBody(N);
2189 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2190 TypePrinting TypePrinter;
2191 TypePrinter.print(C->getType(), OS);
2192 OS << ' ';
2193 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2194 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2195 isa<Argument>(this)) {
2196 WriteAsOperand(OS, this, true, 0);
2197 } else {
2198 // Otherwise we don't know what it is. Call the virtual function to
2199 // allow a subclass to print itself.
2200 printCustom(OS);
2204 // Value::printCustom - subclasses should override this to implement printing.
2205 void Value::printCustom(raw_ostream &OS) const {
2206 llvm_unreachable("Unknown value to print out!");
2209 // Value::dump - allow easy printing of Values from the debugger.
2210 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2212 // Type::dump - allow easy printing of Types from the debugger.
2213 // This one uses type names from the given context module
2214 void Type::dump(const Module *Context) const {
2215 WriteTypeSymbolic(dbgs(), this, Context);
2216 dbgs() << '\n';
2219 // Type::dump - allow easy printing of Types from the debugger.
2220 void Type::dump() const { dump(0); }
2222 // Module::dump() - Allow printing of Modules from the debugger.
2223 void Module::dump() const { print(dbgs(), 0); }