1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/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"
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 //===----------------------------------------------------------------------===//
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();
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
!= '"')
82 Out
<< '\\' << hexdigit(C
>> 4) << hexdigit(C
& 0x0F);
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!");
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]);
109 for (unsigned i
= 0, e
= Name
.size(); i
!= e
; ++i
) {
111 if (!isalnum(C
) && C
!= '-' && C
!= '.' && C
!= '_') {
118 // If we didn't need any quotes, just write out the name in one blast.
124 // Okay, we need quotes. Output the quotes and escape any scary characters as
127 PrintEscapedString(Name
, 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
);
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
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();
211 case Type::FunctionTyID
: {
212 const FunctionType
*FTy
= cast
<FunctionType
>(Ty
);
213 CalcTypeName(FTy
->getReturnType(), TypeStack
, OS
);
215 for (FunctionType::param_iterator I
= FTy
->param_begin(),
216 E
= FTy
->param_end(); I
!= E
; ++I
) {
217 if (I
!= FTy
->param_begin())
219 CalcTypeName(*I
, TypeStack
, OS
);
221 if (FTy
->isVarArg()) {
222 if (FTy
->getNumParams()) OS
<< ", ";
228 case Type::StructTyID
: {
229 const StructType
*STy
= cast
<StructType
>(Ty
);
233 for (StructType::element_iterator I
= STy
->element_begin(),
234 E
= STy
->element_end(); I
!= E
; ++I
) {
236 CalcTypeName(*I
, TypeStack
, OS
);
237 if (llvm::next(I
) == STy
->element_end())
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
<< ')';
255 case Type::ArrayTyID
: {
256 const ArrayType
*ATy
= cast
<ArrayType
>(Ty
);
257 OS
<< '[' << ATy
->getNumElements() << " x ";
258 CalcTypeName(ATy
->getElementType(), TypeStack
, OS
);
262 case Type::VectorTyID
: {
263 const VectorType
*PTy
= cast
<VectorType
>(Ty
);
264 OS
<< "<" << PTy
->getNumElements() << " x ";
265 CalcTypeName(PTy
->getElementType(), TypeStack
, OS
);
269 case Type::OpaqueTyID
:
273 OS
<< "<unrecognized-type>";
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
);
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
298 SmallVector
<const Type
*, 16> TypeStack
;
299 std::string TypeName
;
301 raw_string_ostream
TypeOS(TypeName
);
302 CalcTypeName(Ty
, TypeStack
, TypeOS
, IgnoreTopLevelName
);
305 // Cache type name for later use.
306 if (!IgnoreTopLevelName
)
307 TM
.insert(std::make_pair(Ty
, TypeOS
.str()));
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
;
318 std::vector
<const Type
*> &NumberedTypes
;
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();
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();
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();
359 IncorporateValue(*OI
);
365 void IncorporateType(const Type
*Ty
) {
366 // Check to see if we're already visited this type.
367 if (!VisitedTypes
.insert(Ty
).second
)
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
)
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;
391 if (!VisitedConstants
.insert(V
).second
)
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
,
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();
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()) &&
431 // Likewise don't insert primitives either.
432 if (Ty
->isIntegerTy() || Ty
->isPrimitiveType())
435 // Get the name as a string and insert it into TypeNames.
437 raw_string_ostream
NameROS(NameStr
);
438 formatted_raw_ostream
NameOS(NameROS
);
439 PrintLLVMName(NameOS
, TI
->first
, LocalPrefix
);
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 //===----------------------------------------------------------------------===//
469 /// This class provides computation of slot numbers for LLVM Assembly writing.
473 /// ValueMap - A mapping of Values to slot numbers.
474 typedef DenseMap
<const Value
*, unsigned> ValueMap
;
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.
488 /// fMap - The TypePlanes map for the function level data.
492 /// mdnMap - Map for MDNodes.
493 DenseMap
<const MDNode
*, unsigned> mdnMap
;
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
) {
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
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);
584 #define ST_DEBUG(X) dbgs() << X
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() {
606 TheModule
= 0; ///< Prevent re-processing next time we're called.
609 if (TheFunction
&& !FunctionProcessed
)
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
) {
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();
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");
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
)
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
) {
662 CreateFunctionSlot(BB
);
664 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
;
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
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
);
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
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.
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.
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.
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
++;
746 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
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
++;
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
772 if (!N
->isFunctionLocal()) {
773 mdn_iterator I
= mdnMap
.find(N
);
774 if (I
!= mdnMap
.end())
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";
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;
832 static void WriteOptimizationInfo(raw_ostream
&Out
, const User
*U
) {
833 if (const OverflowingBinaryOperator
*OBO
=
834 dyn_cast
<OverflowingBinaryOperator
>(U
)) {
835 if (OBO
->hasNoUnsignedWrap())
837 if (OBO
->hasNoSignedWrap())
839 } else if (const PossiblyExactOperator
*Div
=
840 dyn_cast
<PossiblyExactOperator
>(U
)) {
843 } else if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(U
)) {
844 if (GEP
->isInBounds())
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");
858 Out
<< CI
->getValue();
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.
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
) {
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!");
897 APFloat apf
= CFP
->getValueAPF();
898 // Floats are represented in ASCII IR as double, convert.
900 apf
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
,
903 utohex_buffer(uint64_t(apf
.bitcastToAPInt().getZExtValue()),
908 // Some form of long double. These appear as a magic letter identifying
909 // the type, then a fixed number of hex digits.
911 if (&CFP
->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended
) {
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];
918 int width
= api
.getBitWidth();
919 for (int j
=0; j
<width
; j
+=4, shiftcount
-=4) {
920 unsigned int nibble
= (word
>>shiftcount
) & 15;
922 Out
<< (unsigned char)(nibble
+ '0');
924 Out
<< (unsigned char)(nibble
- 10 + 'A');
925 if (shiftcount
== 0 && j
+4 < width
) {
929 shiftcount
= width
-j
-4;
933 } else if (&CFP
->getValueAPF().getSemantics() == &APFloat::IEEEquad
)
935 else if (&CFP
->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble
)
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();
944 int width
= api
.getBitWidth();
945 for (int j
=0; j
<width
; j
+=4, shiftcount
-=4) {
946 unsigned int nibble
= (word
>>shiftcount
) & 15;
948 Out
<< (unsigned char)(nibble
+ '0');
950 Out
<< (unsigned char)(nibble
- 10 + 'A');
951 if (shiftcount
== 0 && j
+4 < width
) {
955 shiftcount
= width
-j
-4;
961 if (isa
<ConstantAggregateZero
>(CV
)) {
962 Out
<< "zeroinitializer";
966 if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(CV
)) {
967 Out
<< "blockaddress(";
968 WriteAsOperandInternal(Out
, BA
->getFunction(), &TypePrinter
, Machine
,
971 WriteAsOperandInternal(Out
, BA
->getBasicBlock(), &TypePrinter
, Machine
,
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()) {
984 PrintEscapedString(CA
->getAsString(), Out
);
986 } else { // Cannot output in string format...
988 if (CA
->getNumOperands()) {
989 TypePrinter
.print(ETy
, Out
);
991 WriteAsOperandInternal(Out
, CA
->getOperand(0),
992 &TypePrinter
, Machine
,
994 for (unsigned i
= 1, e
= CA
->getNumOperands(); i
!= e
; ++i
) {
996 TypePrinter
.print(ETy
, Out
);
998 WriteAsOperandInternal(Out
, CA
->getOperand(i
), &TypePrinter
, Machine
,
1007 if (const ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(CV
)) {
1008 if (CS
->getType()->isPacked())
1011 unsigned N
= CS
->getNumOperands();
1014 TypePrinter
.print(CS
->getOperand(0)->getType(), Out
);
1017 WriteAsOperandInternal(Out
, CS
->getOperand(0), &TypePrinter
, Machine
,
1020 for (unsigned i
= 1; i
< N
; i
++) {
1022 TypePrinter
.print(CS
->getOperand(i
)->getType(), Out
);
1025 WriteAsOperandInternal(Out
, CS
->getOperand(i
), &TypePrinter
, Machine
,
1032 if (CS
->getType()->isPacked())
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");
1042 TypePrinter
.print(ETy
, Out
);
1044 WriteAsOperandInternal(Out
, CP
->getOperand(0), &TypePrinter
, Machine
,
1046 for (unsigned i
= 1, e
= CP
->getNumOperands(); i
!= e
; ++i
) {
1048 TypePrinter
.print(ETy
, Out
);
1050 WriteAsOperandInternal(Out
, CP
->getOperand(i
), &TypePrinter
, Machine
,
1057 if (isa
<ConstantPointerNull
>(CV
)) {
1062 if (isa
<UndefValue
>(CV
)) {
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());
1074 for (User::const_op_iterator OI
=CE
->op_begin(); OI
!= CE
->op_end(); ++OI
) {
1075 TypePrinter
.print((*OI
)->getType(), Out
);
1077 WriteAsOperandInternal(Out
, *OI
, &TypePrinter
, Machine
, Context
);
1078 if (OI
+1 != CE
->op_end())
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
];
1090 TypePrinter
.print(CE
->getType(), Out
);
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
) {
1105 for (unsigned mi
= 0, me
= Node
->getNumOperands(); mi
!= me
; ++mi
) {
1106 const Value
*V
= Node
->getOperand(mi
);
1110 TypePrinter
->print(V
->getType(), Out
);
1112 WriteAsOperandInternal(Out
, Node
->getOperand(mi
),
1113 TypePrinter
, Machine
, Context
);
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
) {
1132 PrintLLVMName(Out
, V
);
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
);
1143 if (const InlineAsm
*IA
= dyn_cast
<InlineAsm
>(V
)) {
1145 if (IA
->hasSideEffects())
1146 Out
<< "sideeffect ";
1147 if (IA
->isAlignStack())
1148 Out
<< "alignstack ";
1150 PrintEscapedString(IA
->getAsmString(), Out
);
1152 PrintEscapedString(IA
->getConstraintString(), Out
);
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
);
1165 if (N
->isFunctionLocal())
1166 Machine
= new SlotTracker(N
->getFunction());
1168 Machine
= new SlotTracker(Context
);
1170 int Slot
= Machine
->getMetadataSlot(N
);
1178 if (const MDString
*MDS
= dyn_cast
<MDString
>(V
)) {
1180 PrintEscapedString(MDS
->getString(), Out
);
1185 if (V
->getValueID() == Value::PseudoSourceValueVal
||
1186 V
->getValueID() == Value::FixedStackPseudoSourceValueVal
) {
1194 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
1195 Slot
= Machine
->getGlobalSlot(GV
);
1198 Slot
= Machine
->getLocalSlot(V
);
1201 Machine
= createSlotTracker(V
);
1203 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
1204 Slot
= Machine
->getGlobalSlot(GV
);
1207 Slot
= Machine
->getLocalSlot(V
);
1216 Out
<< Prefix
<< Slot
;
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.
1227 ((!isa
<Constant
>(V
) && !isa
<MDNode
>(V
)) ||
1228 V
->hasName() || isa
<GlobalValue
>(V
))) {
1229 WriteAsOperandInternal(Out
, V
, 0, 0, Context
);
1233 if (Context
== 0) Context
= getModuleFromVal(V
);
1235 TypePrinting TypePrinter
;
1236 std::vector
<const Type
*> NumberedTypes
;
1237 AddModuleTypesToPrinter(TypePrinter
, NumberedTypes
, Context
);
1239 TypePrinter
.print(V
->getType(), Out
);
1243 WriteAsOperandInternal(Out
, V
, &TypePrinter
, 0, Context
);
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
;
1257 inline AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
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
);
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
) {
1291 Out
<< "<null operand!>";
1295 TypePrinter
.print(Operand
->getType(), Out
);
1298 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
1301 void AssemblyWriter::writeParamOperand(const Value
*Operand
,
1304 Out
<< "<null operand!>";
1309 TypePrinter
.print(Operand
->getType(), Out
);
1310 // Print parameter attributes list
1311 if (Attrs
!= Attribute::None
)
1312 Out
<< ' ' << Attribute::getAsString(Attrs
);
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();
1334 size_t NewLine
= Asm
.find_first_of('\n', CurPos
);
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
),
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
);
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();
1359 Out
<< "deplibs = [ ";
1361 Out
<< '"' << *LI
<< '"';
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();
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();
1385 // Output all of the functions.
1386 for (Module::const_iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++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
);
1397 if (!Machine
.mdn_empty()) {
1403 void AssemblyWriter::printNamedMDNode(const NamedMDNode
*NMD
) {
1404 Out
<< "!" << NMD
->getName() << " = !{";
1405 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
1407 int Slot
= Machine
.getMetadataSlot(NMD
->getOperand(i
));
1417 static void PrintLinkage(GlobalValue::LinkageTypes LT
,
1418 formatted_raw_ostream
&Out
) {
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 ";
1426 case GlobalValue::LinkerPrivateWeakDefAutoLinkage
:
1427 Out
<< "linker_private_weak_def_auto ";
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 ";
1446 static void PrintVisibility(GlobalValue::VisibilityTypes Vis
,
1447 formatted_raw_ostream
&Out
) {
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());
1462 if (!GV
->hasInitializer() && GV
->hasExternalLinkage())
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()) {
1477 writeOperand(GV
->getInitializer(), false);
1480 if (GV
->hasSection()) {
1481 Out
<< ", section \"";
1482 PrintEscapedString(GV
->getSection(), Out
);
1485 if (GV
->getAlignment())
1486 Out
<< ", align " << GV
->getAlignment();
1488 printInfoComment(*GV
);
1492 void AssemblyWriter::printAlias(const GlobalAlias
*GA
) {
1493 if (GA
->isMaterializable())
1494 Out
<< "; Materializable\n";
1496 // Don't crash when dumping partially built GA
1498 Out
<< "<<nameless>> = ";
1500 PrintLLVMName(Out
, GA
);
1503 PrintVisibility(GA
->getVisibility(), Out
);
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
);
1514 PrintLLVMName(Out
, GV
);
1515 } else if (const Function
*F
= dyn_cast
<Function
>(Aliasee
)) {
1516 TypePrinter
.print(F
->getFunctionType(), 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
);
1523 PrintLLVMName(Out
, GA
);
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
);
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
);
1548 // Print the named types.
1549 for (TypeSymbolTable::const_iterator TI
= ST
.begin(), TE
= ST
.end();
1551 PrintLLVMName(Out
, TI
->first
, LocalPrefix
);
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
);
1561 /// printFunction - Print all aspects of a function.
1563 void AssemblyWriter::printFunction(const Function
*F
) {
1564 // Print out the return type and name.
1567 if (AnnotationWriter
) AnnotationWriter
->emitFunctionAnnot(F
, Out
);
1569 if (F
->isMaterializable())
1570 Out
<< "; Materializable\n";
1572 if (F
->isDeclaration())
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
);
1604 WriteAsOperandInternal(Out
, F
, &TypePrinter
, &Machine
, F
->getParent());
1606 Machine
.incorporateFunction(F
);
1608 // Loop over the arguments, printing them...
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();
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
));
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
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!
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
);
1651 if (F
->getAlignment())
1652 Out
<< " align " << F
->getAlignment();
1654 Out
<< " gc \"" << F
->getGC() << '"';
1655 if (F
->isDeclaration()) {
1659 // Output all of the function's basic blocks.
1660 for (Function::const_iterator I
= F
->begin(), E
= F
->end(); I
!= E
; ++I
)
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
,
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()) {
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...
1693 PrintLLVMName(Out
, BB
->getName(), LabelPrefix
);
1695 } else if (!BB
->use_empty()) { // Don't print block # of no uses...
1696 Out
<< "\n; <label>:";
1697 int Slot
= Machine
.getLocalSlot(BB
);
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);
1711 const_pred_iterator PI
= pred_begin(BB
), PE
= pred_end(BB
);
1714 Out
<< " No predecessors!";
1717 writeOperand(*PI
, false);
1718 for (++PI
; PI
!= PE
; ++PI
) {
1720 writeOperand(*PI
, false);
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
);
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()) {
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
);
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()) {
1763 Out
.PadToColumn(50);
1767 Out
<< " [debug line = ";
1768 printDebugLoc(DL
,Out
);
1771 if (const DbgDeclareInst
*DDI
= dyn_cast
<DbgDeclareInst
>(I
)) {
1772 const MDNode
*Var
= DDI
->getVariable();
1774 Out
.PadToColumn(50);
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();
1785 Out
.PadToColumn(50);
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.
1804 // Print out name if it exists...
1806 PrintLLVMName(Out
, &I
);
1808 } else if (!I
.getType()->isVoidTy()) {
1809 // Print out the def slot taken.
1810 int SlotNum
= Machine
.getLocalSlot(&I
);
1812 Out
<< "<badref> = ";
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())) {
1821 } else if (isa
<CallInst
>(I
) && cast
<CallInst
>(I
).isTailCall()) {
1822 // If this is a call, check if it's a tail call.
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
));
1843 writeOperand(BI
.getCondition(), true);
1845 writeOperand(BI
.getSuccessor(0), true);
1847 writeOperand(BI
.getSuccessor(1), true);
1849 } else if (isa
<SwitchInst
>(I
)) {
1850 // Special case switch instruction to get formatting nice and correct.
1852 writeOperand(Operand
, true);
1854 writeOperand(I
.getOperand(1), true);
1857 for (unsigned op
= 2, Eop
= I
.getNumOperands(); op
< Eop
; op
+= 2) {
1859 writeOperand(I
.getOperand(op
), true);
1861 writeOperand(I
.getOperand(op
+1), true);
1864 } else if (isa
<IndirectBrInst
>(I
)) {
1865 // Special case indirectbr instruction to get formatting nice and correct.
1867 writeOperand(Operand
, true);
1870 for (unsigned i
= 1, e
= I
.getNumOperands(); i
!= e
; ++i
) {
1873 writeOperand(I
.getOperand(i
), true);
1876 } else if (isa
<PHINode
>(I
)) {
1878 TypePrinter
.print(I
.getType(), Out
);
1881 for (unsigned op
= 0, Eop
= I
.getNumOperands(); op
< Eop
; op
+= 2) {
1882 if (op
) 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
)) {
1889 writeOperand(I
.getOperand(0), true);
1890 for (const unsigned *i
= EVI
->idx_begin(), *e
= EVI
->idx_end(); i
!= e
; ++i
)
1892 } else if (const InsertValueInst
*IVI
= dyn_cast
<InsertValueInst
>(&I
)) {
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
)
1898 } else if (isa
<ReturnInst
>(I
) && !Operand
) {
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.
1932 if (!FTy
->isVarArg() &&
1933 (!RetTy
->isPointerTy() ||
1934 !cast
<PointerType
>(RetTy
)->getElementType()->isFunctionTy())) {
1935 TypePrinter
.print(RetTy
, Out
);
1937 writeOperand(Operand
, false);
1939 writeOperand(Operand
, true);
1942 for (unsigned op
= 0, Eop
= CI
->getNumArgOperands(); op
< Eop
; ++op
) {
1945 writeParamOperand(CI
->getArgOperand(op
), PAL
.getParamAttributes(op
+ 1));
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.
1982 if (!FTy
->isVarArg() &&
1983 (!RetTy
->isPointerTy() ||
1984 !cast
<PointerType
>(RetTy
)->getElementType()->isFunctionTy())) {
1985 TypePrinter
.print(RetTy
, Out
);
1987 writeOperand(Operand
, false);
1989 writeOperand(Operand
, true);
1992 for (unsigned op
= 0, Eop
= II
->getNumArgOperands(); op
< Eop
; ++op
) {
1995 writeParamOperand(II
->getArgOperand(op
), PAL
.getParamAttributes(op
+ 1));
1999 if (PAL
.getFnAttributes() != Attribute::None
)
2000 Out
<< ' ' << Attribute::getAsString(PAL
.getFnAttributes());
2003 writeOperand(II
->getNormalDest(), true);
2005 writeOperand(II
->getUnwindDest(), true);
2007 } else if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(&I
)) {
2009 TypePrinter
.print(AI
->getType()->getElementType(), Out
);
2010 if (!AI
->getArraySize() || AI
->isArrayAllocation()) {
2012 writeOperand(AI
->getArraySize(), true);
2014 if (AI
->getAlignment()) {
2015 Out
<< ", align " << AI
->getAlignment();
2017 } else if (isa
<CastInst
>(I
)) {
2020 writeOperand(Operand
, true); // Work with broken code
2023 TypePrinter
.print(I
.getType(), Out
);
2024 } else if (isa
<VAArgInst
>(I
)) {
2027 writeOperand(Operand
, true); // Work with broken code
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;
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!
2055 if (!PrintAllTypes
) {
2057 TypePrinter
.print(TheType
, Out
);
2061 for (unsigned i
= 0, E
= I
.getNumOperands(); i
!= E
; ++i
) {
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
];
2085 Out
<< ", !<unknown kind #" << Kind
<< ">";
2088 WriteAsOperandInternal(Out
, InstMD
[i
].second
, &TypePrinter
, &Machine
,
2092 printInfoComment(I
);
2095 static void WriteMDNodeComment(const MDNode
*Node
,
2096 formatted_raw_ostream
&Out
) {
2097 if (Node
->getNumOperands() < 1)
2099 ConstantInt
*CI
= dyn_cast_or_null
<ConstantInt
>(Node
->getOperand(0));
2101 APInt Val
= CI
->getValue();
2102 APInt Tag
= Val
& ~APInt(Val
.getBitWidth(), LLVMDebugVersionMask
);
2103 if (Val
.ult(LLVMDebugVersion
))
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();
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
);
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 {
2154 OS
<< "<null Type>";
2157 TypePrinting().print(this, OS
);
2160 void Value::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
) const {
2162 ROS
<< "printing a <null> value\n";
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
))
2180 else if (const Function
*F
= dyn_cast
<Function
>(GV
))
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
);
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);
2198 // Otherwise we don't know what it is. Call the virtual function to
2199 // allow a subclass to print itself.
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
);
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); }