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/Debug.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/FormattedStream.h"
45 // Make virtual table appear in this compilation unit.
46 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 static const Module
*getModuleFromVal(const Value
*V
) {
53 if (const Argument
*MA
= dyn_cast
<Argument
>(V
))
54 return MA
->getParent() ? MA
->getParent()->getParent() : 0;
56 if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
57 return BB
->getParent() ? BB
->getParent()->getParent() : 0;
59 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
60 const Function
*M
= I
->getParent() ? I
->getParent()->getParent() : 0;
61 return M
? M
->getParent() : 0;
64 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
))
65 return GV
->getParent();
69 // PrintEscapedString - Print each character of the specified string, escaping
70 // it if it is not printable or if it is an escape char.
71 static void PrintEscapedString(StringRef Name
, raw_ostream
&Out
) {
72 for (unsigned i
= 0, e
= Name
.size(); i
!= e
; ++i
) {
73 unsigned char C
= Name
[i
];
74 if (isprint(C
) && C
!= '\\' && C
!= '"')
77 Out
<< '\\' << hexdigit(C
>> 4) << hexdigit(C
& 0x0F);
88 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
89 /// prefixed with % (if the string only contains simple characters) or is
90 /// surrounded with ""'s (if it has special chars in it). Print it out.
91 static void PrintLLVMName(raw_ostream
&OS
, StringRef Name
, PrefixType Prefix
) {
92 assert(Name
.data() && "Cannot get empty name!");
94 default: llvm_unreachable("Bad prefix!");
96 case GlobalPrefix
: OS
<< '@'; break;
97 case LabelPrefix
: break;
98 case LocalPrefix
: OS
<< '%'; break;
101 // Scan the name to see if it needs quotes first.
102 bool NeedsQuotes
= isdigit(Name
[0]);
104 for (unsigned i
= 0, e
= Name
.size(); i
!= e
; ++i
) {
106 if (!isalnum(C
) && C
!= '-' && C
!= '.' && C
!= '_') {
113 // If we didn't need any quotes, just write out the name in one blast.
119 // Okay, we need quotes. Output the quotes and escape any scary characters as
122 PrintEscapedString(Name
, OS
);
126 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
127 /// prefixed with % (if the string only contains simple characters) or is
128 /// surrounded with ""'s (if it has special chars in it). Print it out.
129 static void PrintLLVMName(raw_ostream
&OS
, const Value
*V
) {
130 PrintLLVMName(OS
, V
->getName(),
131 isa
<GlobalValue
>(V
) ? GlobalPrefix
: LocalPrefix
);
134 //===----------------------------------------------------------------------===//
135 // TypePrinting Class: Type printing machinery
136 //===----------------------------------------------------------------------===//
138 static DenseMap
<const Type
*, std::string
> &getTypeNamesMap(void *M
) {
139 return *static_cast<DenseMap
<const Type
*, std::string
>*>(M
);
142 void TypePrinting::clear() {
143 getTypeNamesMap(TypeNames
).clear();
146 bool TypePrinting::hasTypeName(const Type
*Ty
) const {
147 return getTypeNamesMap(TypeNames
).count(Ty
);
150 void TypePrinting::addTypeName(const Type
*Ty
, const std::string
&N
) {
151 getTypeNamesMap(TypeNames
).insert(std::make_pair(Ty
, N
));
155 TypePrinting::TypePrinting() {
156 TypeNames
= new DenseMap
<const Type
*, std::string
>();
159 TypePrinting::~TypePrinting() {
160 delete &getTypeNamesMap(TypeNames
);
163 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
164 /// use of type names or up references to shorten the type name where possible.
165 void TypePrinting::CalcTypeName(const Type
*Ty
,
166 SmallVectorImpl
<const Type
*> &TypeStack
,
167 raw_ostream
&OS
, bool IgnoreTopLevelName
) {
168 // Check to see if the type is named.
169 if (!IgnoreTopLevelName
) {
170 DenseMap
<const Type
*, std::string
> &TM
= getTypeNamesMap(TypeNames
);
171 DenseMap
<const Type
*, std::string
>::iterator I
= TM
.find(Ty
);
178 // Check to see if the Type is already on the stack...
179 unsigned Slot
= 0, CurSize
= TypeStack
.size();
180 while (Slot
< CurSize
&& TypeStack
[Slot
] != Ty
) ++Slot
; // Scan for type
182 // This is another base case for the recursion. In this case, we know
183 // that we have looped back to a type that we have previously visited.
184 // Generate the appropriate upreference to handle this.
185 if (Slot
< CurSize
) {
186 OS
<< '\\' << unsigned(CurSize
-Slot
); // Here's the upreference
190 TypeStack
.push_back(Ty
); // Recursive case: Add us to the stack..
192 switch (Ty
->getTypeID()) {
193 case Type::VoidTyID
: OS
<< "void"; break;
194 case Type::FloatTyID
: OS
<< "float"; break;
195 case Type::DoubleTyID
: OS
<< "double"; break;
196 case Type::X86_FP80TyID
: OS
<< "x86_fp80"; break;
197 case Type::FP128TyID
: OS
<< "fp128"; break;
198 case Type::PPC_FP128TyID
: OS
<< "ppc_fp128"; break;
199 case Type::LabelTyID
: OS
<< "label"; break;
200 case Type::MetadataTyID
: OS
<< "metadata"; break;
201 case Type::X86_MMXTyID
: OS
<< "x86_mmx"; break;
202 case Type::IntegerTyID
:
203 OS
<< 'i' << cast
<IntegerType
>(Ty
)->getBitWidth();
206 case Type::FunctionTyID
: {
207 const FunctionType
*FTy
= cast
<FunctionType
>(Ty
);
208 CalcTypeName(FTy
->getReturnType(), TypeStack
, OS
);
210 for (FunctionType::param_iterator I
= FTy
->param_begin(),
211 E
= FTy
->param_end(); I
!= E
; ++I
) {
212 if (I
!= FTy
->param_begin())
214 CalcTypeName(*I
, TypeStack
, OS
);
216 if (FTy
->isVarArg()) {
217 if (FTy
->getNumParams()) OS
<< ", ";
223 case Type::StructTyID
: {
224 const StructType
*STy
= cast
<StructType
>(Ty
);
228 for (StructType::element_iterator I
= STy
->element_begin(),
229 E
= STy
->element_end(); I
!= E
; ++I
) {
231 CalcTypeName(*I
, TypeStack
, OS
);
232 if (llvm::next(I
) == STy
->element_end())
242 case Type::PointerTyID
: {
243 const PointerType
*PTy
= cast
<PointerType
>(Ty
);
244 CalcTypeName(PTy
->getElementType(), TypeStack
, OS
);
245 if (unsigned AddressSpace
= PTy
->getAddressSpace())
246 OS
<< " addrspace(" << AddressSpace
<< ')';
250 case Type::ArrayTyID
: {
251 const ArrayType
*ATy
= cast
<ArrayType
>(Ty
);
252 OS
<< '[' << ATy
->getNumElements() << " x ";
253 CalcTypeName(ATy
->getElementType(), TypeStack
, OS
);
257 case Type::VectorTyID
: {
258 const VectorType
*PTy
= cast
<VectorType
>(Ty
);
259 OS
<< "<" << PTy
->getNumElements() << " x ";
260 CalcTypeName(PTy
->getElementType(), TypeStack
, OS
);
264 case Type::OpaqueTyID
:
268 OS
<< "<unrecognized-type>";
272 TypeStack
.pop_back(); // Remove self from stack.
275 /// printTypeInt - The internal guts of printing out a type that has a
276 /// potentially named portion.
278 void TypePrinting::print(const Type
*Ty
, raw_ostream
&OS
,
279 bool IgnoreTopLevelName
) {
280 // Check to see if the type is named.
281 DenseMap
<const Type
*, std::string
> &TM
= getTypeNamesMap(TypeNames
);
282 if (!IgnoreTopLevelName
) {
283 DenseMap
<const Type
*, std::string
>::iterator I
= TM
.find(Ty
);
290 // Otherwise we have a type that has not been named but is a derived type.
291 // Carefully recurse the type hierarchy to print out any contained symbolic
293 SmallVector
<const Type
*, 16> TypeStack
;
294 std::string TypeName
;
296 raw_string_ostream
TypeOS(TypeName
);
297 CalcTypeName(Ty
, TypeStack
, TypeOS
, IgnoreTopLevelName
);
300 // Cache type name for later use.
301 if (!IgnoreTopLevelName
)
302 TM
.insert(std::make_pair(Ty
, TypeOS
.str()));
307 // To avoid walking constant expressions multiple times and other IR
308 // objects, we keep several helper maps.
309 DenseSet
<const Value
*> VisitedConstants
;
310 DenseSet
<const Type
*> VisitedTypes
;
313 std::vector
<const Type
*> &NumberedTypes
;
315 TypeFinder(TypePrinting
&tp
, std::vector
<const Type
*> &numberedTypes
)
316 : TP(tp
), NumberedTypes(numberedTypes
) {}
318 void Run(const Module
&M
) {
319 // Get types from the type symbol table. This gets opaque types referened
320 // only through derived named types.
321 const TypeSymbolTable
&ST
= M
.getTypeSymbolTable();
322 for (TypeSymbolTable::const_iterator TI
= ST
.begin(), E
= ST
.end();
324 IncorporateType(TI
->second
);
326 // Get types from global variables.
327 for (Module::const_global_iterator I
= M
.global_begin(),
328 E
= M
.global_end(); I
!= E
; ++I
) {
329 IncorporateType(I
->getType());
330 if (I
->hasInitializer())
331 IncorporateValue(I
->getInitializer());
334 // Get types from aliases.
335 for (Module::const_alias_iterator I
= M
.alias_begin(),
336 E
= M
.alias_end(); I
!= E
; ++I
) {
337 IncorporateType(I
->getType());
338 IncorporateValue(I
->getAliasee());
341 // Get types from functions.
342 for (Module::const_iterator FI
= M
.begin(), E
= M
.end(); FI
!= E
; ++FI
) {
343 IncorporateType(FI
->getType());
345 for (Function::const_iterator BB
= FI
->begin(), E
= FI
->end();
347 for (BasicBlock::const_iterator II
= BB
->begin(),
348 E
= BB
->end(); II
!= E
; ++II
) {
349 const Instruction
&I
= *II
;
350 // Incorporate the type of the instruction and all its operands.
351 IncorporateType(I
.getType());
352 for (User::const_op_iterator OI
= I
.op_begin(), OE
= I
.op_end();
354 IncorporateValue(*OI
);
360 void IncorporateType(const Type
*Ty
) {
361 // Check to see if we're already visited this type.
362 if (!VisitedTypes
.insert(Ty
).second
)
365 // If this is a structure or opaque type, add a name for the type.
366 if (((Ty
->isStructTy() && cast
<StructType
>(Ty
)->getNumElements())
367 || Ty
->isOpaqueTy()) && !TP
.hasTypeName(Ty
)) {
368 TP
.addTypeName(Ty
, "%"+utostr(unsigned(NumberedTypes
.size())));
369 NumberedTypes
.push_back(Ty
);
372 // Recursively walk all contained types.
373 for (Type::subtype_iterator I
= Ty
->subtype_begin(),
374 E
= Ty
->subtype_end(); I
!= E
; ++I
)
378 /// IncorporateValue - This method is used to walk operand lists finding
379 /// types hiding in constant expressions and other operands that won't be
380 /// walked in other ways. GlobalValues, basic blocks, instructions, and
381 /// inst operands are all explicitly enumerated.
382 void IncorporateValue(const Value
*V
) {
383 if (V
== 0 || !isa
<Constant
>(V
) || isa
<GlobalValue
>(V
)) return;
386 if (!VisitedConstants
.insert(V
).second
)
390 IncorporateType(V
->getType());
392 // Look in operands for types.
393 const Constant
*C
= cast
<Constant
>(V
);
394 for (Constant::const_op_iterator I
= C
->op_begin(),
395 E
= C
->op_end(); I
!= E
;++I
)
396 IncorporateValue(*I
);
399 } // end anonymous namespace
402 /// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
403 /// the specified module to the TypePrinter and all numbered types to it and the
404 /// NumberedTypes table.
405 static void AddModuleTypesToPrinter(TypePrinting
&TP
,
406 std::vector
<const Type
*> &NumberedTypes
,
410 // If the module has a symbol table, take all global types and stuff their
411 // names into the TypeNames map.
412 const TypeSymbolTable
&ST
= M
->getTypeSymbolTable();
413 for (TypeSymbolTable::const_iterator TI
= ST
.begin(), E
= ST
.end();
415 const Type
*Ty
= cast
<Type
>(TI
->second
);
417 // As a heuristic, don't insert pointer to primitive types, because
418 // they are used too often to have a single useful name.
419 if (const PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
)) {
420 const Type
*PETy
= PTy
->getElementType();
421 if ((PETy
->isPrimitiveType() || PETy
->isIntegerTy()) &&
426 // Likewise don't insert primitives either.
427 if (Ty
->isIntegerTy() || Ty
->isPrimitiveType())
430 // Get the name as a string and insert it into TypeNames.
432 raw_string_ostream
NameROS(NameStr
);
433 formatted_raw_ostream
NameOS(NameROS
);
434 PrintLLVMName(NameOS
, TI
->first
, LocalPrefix
);
436 TP
.addTypeName(Ty
, NameStr
);
439 // Walk the entire module to find references to unnamed structure and opaque
440 // types. This is required for correctness by opaque types (because multiple
441 // uses of an unnamed opaque type needs to be referred to by the same ID) and
442 // it shrinks complex recursive structure types substantially in some cases.
443 TypeFinder(TP
, NumberedTypes
).Run(*M
);
447 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
448 /// type, iff there is an entry in the modules symbol table for the specified
449 /// type or one of it's component types.
451 void llvm::WriteTypeSymbolic(raw_ostream
&OS
, const Type
*Ty
, const Module
*M
) {
452 TypePrinting Printer
;
453 std::vector
<const Type
*> NumberedTypes
;
454 AddModuleTypesToPrinter(Printer
, NumberedTypes
, M
);
455 Printer
.print(Ty
, OS
);
458 //===----------------------------------------------------------------------===//
459 // SlotTracker Class: Enumerate slot numbers for unnamed values
460 //===----------------------------------------------------------------------===//
464 /// This class provides computation of slot numbers for LLVM Assembly writing.
468 /// ValueMap - A mapping of Values to slot numbers.
469 typedef DenseMap
<const Value
*, unsigned> ValueMap
;
472 /// TheModule - The module for which we are holding slot numbers.
473 const Module
* TheModule
;
475 /// TheFunction - The function for which we are holding slot numbers.
476 const Function
* TheFunction
;
477 bool FunctionProcessed
;
479 /// mMap - The TypePlanes map for the module level data.
483 /// fMap - The TypePlanes map for the function level data.
487 /// mdnMap - Map for MDNodes.
488 DenseMap
<const MDNode
*, unsigned> mdnMap
;
491 /// Construct from a module
492 explicit SlotTracker(const Module
*M
);
493 /// Construct from a function, starting out in incorp state.
494 explicit SlotTracker(const Function
*F
);
496 /// Return the slot number of the specified value in it's type
497 /// plane. If something is not in the SlotTracker, return -1.
498 int getLocalSlot(const Value
*V
);
499 int getGlobalSlot(const GlobalValue
*V
);
500 int getMetadataSlot(const MDNode
*N
);
502 /// If you'd like to deal with a function instead of just a module, use
503 /// this method to get its data into the SlotTracker.
504 void incorporateFunction(const Function
*F
) {
506 FunctionProcessed
= false;
509 /// After calling incorporateFunction, use this method to remove the
510 /// most recently incorporated function from the SlotTracker. This
511 /// will reset the state of the machine back to just the module contents.
512 void purgeFunction();
514 /// MDNode map iterators.
515 typedef DenseMap
<const MDNode
*, unsigned>::iterator mdn_iterator
;
516 mdn_iterator
mdn_begin() { return mdnMap
.begin(); }
517 mdn_iterator
mdn_end() { return mdnMap
.end(); }
518 unsigned mdn_size() const { return mdnMap
.size(); }
519 bool mdn_empty() const { return mdnMap
.empty(); }
521 /// This function does the actual initialization.
522 inline void initialize();
524 // Implementation Details
526 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
527 void CreateModuleSlot(const GlobalValue
*V
);
529 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
530 void CreateMetadataSlot(const MDNode
*N
);
532 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
533 void CreateFunctionSlot(const Value
*V
);
535 /// Add all of the module level global variables (and their initializers)
536 /// and function declarations, but not the contents of those functions.
537 void processModule();
539 /// Add all of the functions arguments, basic blocks, and instructions.
540 void processFunction();
542 SlotTracker(const SlotTracker
&); // DO NOT IMPLEMENT
543 void operator=(const SlotTracker
&); // DO NOT IMPLEMENT
546 } // end anonymous namespace
549 static SlotTracker
*createSlotTracker(const Value
*V
) {
550 if (const Argument
*FA
= dyn_cast
<Argument
>(V
))
551 return new SlotTracker(FA
->getParent());
553 if (const Instruction
*I
= dyn_cast
<Instruction
>(V
))
554 return new SlotTracker(I
->getParent()->getParent());
556 if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
557 return new SlotTracker(BB
->getParent());
559 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(V
))
560 return new SlotTracker(GV
->getParent());
562 if (const GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
))
563 return new SlotTracker(GA
->getParent());
565 if (const Function
*Func
= dyn_cast
<Function
>(V
))
566 return new SlotTracker(Func
);
568 if (const MDNode
*MD
= dyn_cast
<MDNode
>(V
)) {
569 if (!MD
->isFunctionLocal())
570 return new SlotTracker(MD
->getFunction());
572 return new SlotTracker((Function
*)0);
579 #define ST_DEBUG(X) dbgs() << X
584 // Module level constructor. Causes the contents of the Module (sans functions)
585 // to be added to the slot table.
586 SlotTracker::SlotTracker(const Module
*M
)
587 : TheModule(M
), TheFunction(0), FunctionProcessed(false),
588 mNext(0), fNext(0), mdnNext(0) {
591 // Function level constructor. Causes the contents of the Module and the one
592 // function provided to be added to the slot table.
593 SlotTracker::SlotTracker(const Function
*F
)
594 : TheModule(F
? F
->getParent() : 0), TheFunction(F
), FunctionProcessed(false),
595 mNext(0), fNext(0), mdnNext(0) {
598 inline void SlotTracker::initialize() {
601 TheModule
= 0; ///< Prevent re-processing next time we're called.
604 if (TheFunction
&& !FunctionProcessed
)
608 // Iterate through all the global variables, functions, and global
609 // variable initializers and create slots for them.
610 void SlotTracker::processModule() {
611 ST_DEBUG("begin processModule!\n");
613 // Add all of the unnamed global variables to the value table.
614 for (Module::const_global_iterator I
= TheModule
->global_begin(),
615 E
= TheModule
->global_end(); I
!= E
; ++I
) {
620 // Add metadata used by named metadata.
621 for (Module::const_named_metadata_iterator
622 I
= TheModule
->named_metadata_begin(),
623 E
= TheModule
->named_metadata_end(); I
!= E
; ++I
) {
624 const NamedMDNode
*NMD
= I
;
625 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
)
626 CreateMetadataSlot(NMD
->getOperand(i
));
629 // Add all the unnamed functions to the table.
630 for (Module::const_iterator I
= TheModule
->begin(), E
= TheModule
->end();
635 ST_DEBUG("end processModule!\n");
638 // Process the arguments, basic blocks, and instructions of a function.
639 void SlotTracker::processFunction() {
640 ST_DEBUG("begin processFunction!\n");
643 // Add all the function arguments with no names.
644 for(Function::const_arg_iterator AI
= TheFunction
->arg_begin(),
645 AE
= TheFunction
->arg_end(); AI
!= AE
; ++AI
)
647 CreateFunctionSlot(AI
);
649 ST_DEBUG("Inserting Instructions:\n");
651 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> MDForInst
;
653 // Add all of the basic blocks and instructions with no names.
654 for (Function::const_iterator BB
= TheFunction
->begin(),
655 E
= TheFunction
->end(); BB
!= E
; ++BB
) {
657 CreateFunctionSlot(BB
);
659 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
;
661 if (!I
->getType()->isVoidTy() && !I
->hasName())
662 CreateFunctionSlot(I
);
664 // Intrinsics can directly use metadata. We allow direct calls to any
665 // llvm.foo function here, because the target may not be linked into the
667 if (const CallInst
*CI
= dyn_cast
<CallInst
>(I
)) {
668 if (Function
*F
= CI
->getCalledFunction())
669 if (F
->getName().startswith("llvm."))
670 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
)
671 if (MDNode
*N
= dyn_cast_or_null
<MDNode
>(I
->getOperand(i
)))
672 CreateMetadataSlot(N
);
675 // Process metadata attached with this instruction.
676 I
->getAllMetadata(MDForInst
);
677 for (unsigned i
= 0, e
= MDForInst
.size(); i
!= e
; ++i
)
678 CreateMetadataSlot(MDForInst
[i
].second
);
683 FunctionProcessed
= true;
685 ST_DEBUG("end processFunction!\n");
688 /// Clean up after incorporating a function. This is the only way to get out of
689 /// the function incorporation state that affects get*Slot/Create*Slot. Function
690 /// incorporation state is indicated by TheFunction != 0.
691 void SlotTracker::purgeFunction() {
692 ST_DEBUG("begin purgeFunction!\n");
693 fMap
.clear(); // Simply discard the function level map
695 FunctionProcessed
= false;
696 ST_DEBUG("end purgeFunction!\n");
699 /// getGlobalSlot - Get the slot number of a global value.
700 int SlotTracker::getGlobalSlot(const GlobalValue
*V
) {
701 // Check for uninitialized state and do lazy initialization.
704 // Find the type plane in the module map
705 ValueMap::iterator MI
= mMap
.find(V
);
706 return MI
== mMap
.end() ? -1 : (int)MI
->second
;
709 /// getMetadataSlot - Get the slot number of a MDNode.
710 int SlotTracker::getMetadataSlot(const MDNode
*N
) {
711 // Check for uninitialized state and do lazy initialization.
714 // Find the type plane in the module map
715 mdn_iterator MI
= mdnMap
.find(N
);
716 return MI
== mdnMap
.end() ? -1 : (int)MI
->second
;
720 /// getLocalSlot - Get the slot number for a value that is local to a function.
721 int SlotTracker::getLocalSlot(const Value
*V
) {
722 assert(!isa
<Constant
>(V
) && "Can't get a constant or global slot with this!");
724 // Check for uninitialized state and do lazy initialization.
727 ValueMap::iterator FI
= fMap
.find(V
);
728 return FI
== fMap
.end() ? -1 : (int)FI
->second
;
732 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
733 void SlotTracker::CreateModuleSlot(const GlobalValue
*V
) {
734 assert(V
&& "Can't insert a null Value into SlotTracker!");
735 assert(!V
->getType()->isVoidTy() && "Doesn't need a slot!");
736 assert(!V
->hasName() && "Doesn't need a slot!");
738 unsigned DestSlot
= mNext
++;
741 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
743 // G = Global, F = Function, A = Alias, o = other
744 ST_DEBUG((isa
<GlobalVariable
>(V
) ? 'G' :
745 (isa
<Function
>(V
) ? 'F' :
746 (isa
<GlobalAlias
>(V
) ? 'A' : 'o'))) << "]\n");
749 /// CreateSlot - Create a new slot for the specified value if it has no name.
750 void SlotTracker::CreateFunctionSlot(const Value
*V
) {
751 assert(!V
->getType()->isVoidTy() && !V
->hasName() && "Doesn't need a slot!");
753 unsigned DestSlot
= fNext
++;
756 // G = Global, F = Function, o = other
757 ST_DEBUG(" Inserting value [" << V
->getType() << "] = " << V
<< " slot=" <<
758 DestSlot
<< " [o]\n");
761 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
762 void SlotTracker::CreateMetadataSlot(const MDNode
*N
) {
763 assert(N
&& "Can't insert a null Value into SlotTracker!");
765 // Don't insert if N is a function-local metadata, these are always printed
767 if (!N
->isFunctionLocal()) {
768 mdn_iterator I
= mdnMap
.find(N
);
769 if (I
!= mdnMap
.end())
772 unsigned DestSlot
= mdnNext
++;
773 mdnMap
[N
] = DestSlot
;
776 // Recursively add any MDNodes referenced by operands.
777 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
)
778 if (const MDNode
*Op
= dyn_cast_or_null
<MDNode
>(N
->getOperand(i
)))
779 CreateMetadataSlot(Op
);
782 //===----------------------------------------------------------------------===//
783 // AsmWriter Implementation
784 //===----------------------------------------------------------------------===//
786 static void WriteAsOperandInternal(raw_ostream
&Out
, const Value
*V
,
787 TypePrinting
*TypePrinter
,
788 SlotTracker
*Machine
,
789 const Module
*Context
);
793 static const char *getPredicateText(unsigned predicate
) {
794 const char * pred
= "unknown";
796 case FCmpInst::FCMP_FALSE
: pred
= "false"; break;
797 case FCmpInst::FCMP_OEQ
: pred
= "oeq"; break;
798 case FCmpInst::FCMP_OGT
: pred
= "ogt"; break;
799 case FCmpInst::FCMP_OGE
: pred
= "oge"; break;
800 case FCmpInst::FCMP_OLT
: pred
= "olt"; break;
801 case FCmpInst::FCMP_OLE
: pred
= "ole"; break;
802 case FCmpInst::FCMP_ONE
: pred
= "one"; break;
803 case FCmpInst::FCMP_ORD
: pred
= "ord"; break;
804 case FCmpInst::FCMP_UNO
: pred
= "uno"; break;
805 case FCmpInst::FCMP_UEQ
: pred
= "ueq"; break;
806 case FCmpInst::FCMP_UGT
: pred
= "ugt"; break;
807 case FCmpInst::FCMP_UGE
: pred
= "uge"; break;
808 case FCmpInst::FCMP_ULT
: pred
= "ult"; break;
809 case FCmpInst::FCMP_ULE
: pred
= "ule"; break;
810 case FCmpInst::FCMP_UNE
: pred
= "une"; break;
811 case FCmpInst::FCMP_TRUE
: pred
= "true"; break;
812 case ICmpInst::ICMP_EQ
: pred
= "eq"; break;
813 case ICmpInst::ICMP_NE
: pred
= "ne"; break;
814 case ICmpInst::ICMP_SGT
: pred
= "sgt"; break;
815 case ICmpInst::ICMP_SGE
: pred
= "sge"; break;
816 case ICmpInst::ICMP_SLT
: pred
= "slt"; break;
817 case ICmpInst::ICMP_SLE
: pred
= "sle"; break;
818 case ICmpInst::ICMP_UGT
: pred
= "ugt"; break;
819 case ICmpInst::ICMP_UGE
: pred
= "uge"; break;
820 case ICmpInst::ICMP_ULT
: pred
= "ult"; break;
821 case ICmpInst::ICMP_ULE
: pred
= "ule"; break;
827 static void WriteOptimizationInfo(raw_ostream
&Out
, const User
*U
) {
828 if (const OverflowingBinaryOperator
*OBO
=
829 dyn_cast
<OverflowingBinaryOperator
>(U
)) {
830 if (OBO
->hasNoUnsignedWrap())
832 if (OBO
->hasNoSignedWrap())
834 } else if (const PossiblyExactOperator
*Div
=
835 dyn_cast
<PossiblyExactOperator
>(U
)) {
838 } else if (const GEPOperator
*GEP
= dyn_cast
<GEPOperator
>(U
)) {
839 if (GEP
->isInBounds())
844 static void WriteConstantInternal(raw_ostream
&Out
, const Constant
*CV
,
845 TypePrinting
&TypePrinter
,
846 SlotTracker
*Machine
,
847 const Module
*Context
) {
848 if (const ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CV
)) {
849 if (CI
->getType()->isIntegerTy(1)) {
850 Out
<< (CI
->getZExtValue() ? "true" : "false");
853 Out
<< CI
->getValue();
857 if (const ConstantFP
*CFP
= dyn_cast
<ConstantFP
>(CV
)) {
858 if (&CFP
->getValueAPF().getSemantics() == &APFloat::IEEEdouble
||
859 &CFP
->getValueAPF().getSemantics() == &APFloat::IEEEsingle
) {
860 // We would like to output the FP constant value in exponential notation,
861 // but we cannot do this if doing so will lose precision. Check here to
862 // make sure that we only output it in exponential format if we can parse
863 // the value back and get the same value.
866 bool isDouble
= &CFP
->getValueAPF().getSemantics()==&APFloat::IEEEdouble
;
867 double Val
= isDouble
? CFP
->getValueAPF().convertToDouble() :
868 CFP
->getValueAPF().convertToFloat();
869 SmallString
<128> StrVal
;
870 raw_svector_ostream(StrVal
) << Val
;
872 // Check to make sure that the stringized number is not some string like
873 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
874 // that the string matches the "[-+]?[0-9]" regex.
876 if ((StrVal
[0] >= '0' && StrVal
[0] <= '9') ||
877 ((StrVal
[0] == '-' || StrVal
[0] == '+') &&
878 (StrVal
[1] >= '0' && StrVal
[1] <= '9'))) {
879 // Reparse stringized version!
880 if (atof(StrVal
.c_str()) == Val
) {
885 // Otherwise we could not reparse it to exactly the same value, so we must
886 // output the string in hexadecimal format! Note that loading and storing
887 // floating point types changes the bits of NaNs on some hosts, notably
888 // x86, so we must not use these types.
889 assert(sizeof(double) == sizeof(uint64_t) &&
890 "assuming that double is 64 bits!");
892 APFloat apf
= CFP
->getValueAPF();
893 // Floats are represented in ASCII IR as double, convert.
895 apf
.convert(APFloat::IEEEdouble
, APFloat::rmNearestTiesToEven
,
898 utohex_buffer(uint64_t(apf
.bitcastToAPInt().getZExtValue()),
903 // Some form of long double. These appear as a magic letter identifying
904 // the type, then a fixed number of hex digits.
906 if (&CFP
->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended
) {
908 // api needed to prevent premature destruction
909 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
910 const uint64_t* p
= api
.getRawData();
911 uint64_t word
= p
[1];
913 int width
= api
.getBitWidth();
914 for (int j
=0; j
<width
; j
+=4, shiftcount
-=4) {
915 unsigned int nibble
= (word
>>shiftcount
) & 15;
917 Out
<< (unsigned char)(nibble
+ '0');
919 Out
<< (unsigned char)(nibble
- 10 + 'A');
920 if (shiftcount
== 0 && j
+4 < width
) {
924 shiftcount
= width
-j
-4;
928 } else if (&CFP
->getValueAPF().getSemantics() == &APFloat::IEEEquad
)
930 else if (&CFP
->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble
)
933 llvm_unreachable("Unsupported floating point type");
934 // api needed to prevent premature destruction
935 APInt api
= CFP
->getValueAPF().bitcastToAPInt();
936 const uint64_t* p
= api
.getRawData();
939 int width
= api
.getBitWidth();
940 for (int j
=0; j
<width
; j
+=4, shiftcount
-=4) {
941 unsigned int nibble
= (word
>>shiftcount
) & 15;
943 Out
<< (unsigned char)(nibble
+ '0');
945 Out
<< (unsigned char)(nibble
- 10 + 'A');
946 if (shiftcount
== 0 && j
+4 < width
) {
950 shiftcount
= width
-j
-4;
956 if (isa
<ConstantAggregateZero
>(CV
)) {
957 Out
<< "zeroinitializer";
961 if (const BlockAddress
*BA
= dyn_cast
<BlockAddress
>(CV
)) {
962 Out
<< "blockaddress(";
963 WriteAsOperandInternal(Out
, BA
->getFunction(), &TypePrinter
, Machine
,
966 WriteAsOperandInternal(Out
, BA
->getBasicBlock(), &TypePrinter
, Machine
,
972 if (const ConstantArray
*CA
= dyn_cast
<ConstantArray
>(CV
)) {
973 // As a special case, print the array as a string if it is an array of
974 // i8 with ConstantInt values.
976 const Type
*ETy
= CA
->getType()->getElementType();
977 if (CA
->isString()) {
979 PrintEscapedString(CA
->getAsString(), Out
);
981 } else { // Cannot output in string format...
983 if (CA
->getNumOperands()) {
984 TypePrinter
.print(ETy
, Out
);
986 WriteAsOperandInternal(Out
, CA
->getOperand(0),
987 &TypePrinter
, Machine
,
989 for (unsigned i
= 1, e
= CA
->getNumOperands(); i
!= e
; ++i
) {
991 TypePrinter
.print(ETy
, Out
);
993 WriteAsOperandInternal(Out
, CA
->getOperand(i
), &TypePrinter
, Machine
,
1002 if (const ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(CV
)) {
1003 if (CS
->getType()->isPacked())
1006 unsigned N
= CS
->getNumOperands();
1009 TypePrinter
.print(CS
->getOperand(0)->getType(), Out
);
1012 WriteAsOperandInternal(Out
, CS
->getOperand(0), &TypePrinter
, Machine
,
1015 for (unsigned i
= 1; i
< N
; i
++) {
1017 TypePrinter
.print(CS
->getOperand(i
)->getType(), Out
);
1020 WriteAsOperandInternal(Out
, CS
->getOperand(i
), &TypePrinter
, Machine
,
1027 if (CS
->getType()->isPacked())
1032 if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CV
)) {
1033 const Type
*ETy
= CP
->getType()->getElementType();
1034 assert(CP
->getNumOperands() > 0 &&
1035 "Number of operands for a PackedConst must be > 0");
1037 TypePrinter
.print(ETy
, Out
);
1039 WriteAsOperandInternal(Out
, CP
->getOperand(0), &TypePrinter
, Machine
,
1041 for (unsigned i
= 1, e
= CP
->getNumOperands(); i
!= e
; ++i
) {
1043 TypePrinter
.print(ETy
, Out
);
1045 WriteAsOperandInternal(Out
, CP
->getOperand(i
), &TypePrinter
, Machine
,
1052 if (isa
<ConstantPointerNull
>(CV
)) {
1057 if (isa
<UndefValue
>(CV
)) {
1062 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CV
)) {
1063 Out
<< CE
->getOpcodeName();
1064 WriteOptimizationInfo(Out
, CE
);
1065 if (CE
->isCompare())
1066 Out
<< ' ' << getPredicateText(CE
->getPredicate());
1069 for (User::const_op_iterator OI
=CE
->op_begin(); OI
!= CE
->op_end(); ++OI
) {
1070 TypePrinter
.print((*OI
)->getType(), Out
);
1072 WriteAsOperandInternal(Out
, *OI
, &TypePrinter
, Machine
, Context
);
1073 if (OI
+1 != CE
->op_end())
1077 if (CE
->hasIndices()) {
1078 const SmallVector
<unsigned, 4> &Indices
= CE
->getIndices();
1079 for (unsigned i
= 0, e
= Indices
.size(); i
!= e
; ++i
)
1080 Out
<< ", " << Indices
[i
];
1085 TypePrinter
.print(CE
->getType(), Out
);
1092 Out
<< "<placeholder or erroneous Constant>";
1095 static void WriteMDNodeBodyInternal(raw_ostream
&Out
, const MDNode
*Node
,
1096 TypePrinting
*TypePrinter
,
1097 SlotTracker
*Machine
,
1098 const Module
*Context
) {
1100 for (unsigned mi
= 0, me
= Node
->getNumOperands(); mi
!= me
; ++mi
) {
1101 const Value
*V
= Node
->getOperand(mi
);
1105 TypePrinter
->print(V
->getType(), Out
);
1107 WriteAsOperandInternal(Out
, Node
->getOperand(mi
),
1108 TypePrinter
, Machine
, Context
);
1118 /// WriteAsOperand - Write the name of the specified value out to the specified
1119 /// ostream. This can be useful when you just want to print int %reg126, not
1120 /// the whole instruction that generated it.
1122 static void WriteAsOperandInternal(raw_ostream
&Out
, const Value
*V
,
1123 TypePrinting
*TypePrinter
,
1124 SlotTracker
*Machine
,
1125 const Module
*Context
) {
1127 PrintLLVMName(Out
, V
);
1131 const Constant
*CV
= dyn_cast
<Constant
>(V
);
1132 if (CV
&& !isa
<GlobalValue
>(CV
)) {
1133 assert(TypePrinter
&& "Constants require TypePrinting!");
1134 WriteConstantInternal(Out
, CV
, *TypePrinter
, Machine
, Context
);
1138 if (const InlineAsm
*IA
= dyn_cast
<InlineAsm
>(V
)) {
1140 if (IA
->hasSideEffects())
1141 Out
<< "sideeffect ";
1142 if (IA
->isAlignStack())
1143 Out
<< "alignstack ";
1145 PrintEscapedString(IA
->getAsmString(), Out
);
1147 PrintEscapedString(IA
->getConstraintString(), Out
);
1152 if (const MDNode
*N
= dyn_cast
<MDNode
>(V
)) {
1153 if (N
->isFunctionLocal()) {
1154 // Print metadata inline, not via slot reference number.
1155 WriteMDNodeBodyInternal(Out
, N
, TypePrinter
, Machine
, Context
);
1160 if (N
->isFunctionLocal())
1161 Machine
= new SlotTracker(N
->getFunction());
1163 Machine
= new SlotTracker(Context
);
1165 int Slot
= Machine
->getMetadataSlot(N
);
1173 if (const MDString
*MDS
= dyn_cast
<MDString
>(V
)) {
1175 PrintEscapedString(MDS
->getString(), Out
);
1180 if (V
->getValueID() == Value::PseudoSourceValueVal
||
1181 V
->getValueID() == Value::FixedStackPseudoSourceValueVal
) {
1189 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
1190 Slot
= Machine
->getGlobalSlot(GV
);
1193 Slot
= Machine
->getLocalSlot(V
);
1196 Machine
= createSlotTracker(V
);
1198 if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(V
)) {
1199 Slot
= Machine
->getGlobalSlot(GV
);
1202 Slot
= Machine
->getLocalSlot(V
);
1211 Out
<< Prefix
<< Slot
;
1216 void llvm::WriteAsOperand(raw_ostream
&Out
, const Value
*V
,
1217 bool PrintType
, const Module
*Context
) {
1219 // Fast path: Don't construct and populate a TypePrinting object if we
1220 // won't be needing any types printed.
1222 ((!isa
<Constant
>(V
) && !isa
<MDNode
>(V
)) ||
1223 V
->hasName() || isa
<GlobalValue
>(V
))) {
1224 WriteAsOperandInternal(Out
, V
, 0, 0, Context
);
1228 if (Context
== 0) Context
= getModuleFromVal(V
);
1230 TypePrinting TypePrinter
;
1231 std::vector
<const Type
*> NumberedTypes
;
1232 AddModuleTypesToPrinter(TypePrinter
, NumberedTypes
, Context
);
1234 TypePrinter
.print(V
->getType(), Out
);
1238 WriteAsOperandInternal(Out
, V
, &TypePrinter
, 0, Context
);
1243 class AssemblyWriter
{
1244 formatted_raw_ostream
&Out
;
1245 SlotTracker
&Machine
;
1246 const Module
*TheModule
;
1247 TypePrinting TypePrinter
;
1248 AssemblyAnnotationWriter
*AnnotationWriter
;
1249 std::vector
<const Type
*> NumberedTypes
;
1252 inline AssemblyWriter(formatted_raw_ostream
&o
, SlotTracker
&Mac
,
1254 AssemblyAnnotationWriter
*AAW
)
1255 : Out(o
), Machine(Mac
), TheModule(M
), AnnotationWriter(AAW
) {
1256 AddModuleTypesToPrinter(TypePrinter
, NumberedTypes
, M
);
1259 void printMDNodeBody(const MDNode
*MD
);
1260 void printNamedMDNode(const NamedMDNode
*NMD
);
1262 void printModule(const Module
*M
);
1264 void writeOperand(const Value
*Op
, bool PrintType
);
1265 void writeParamOperand(const Value
*Operand
, Attributes Attrs
);
1267 void writeAllMDNodes();
1269 void printTypeSymbolTable(const TypeSymbolTable
&ST
);
1270 void printGlobal(const GlobalVariable
*GV
);
1271 void printAlias(const GlobalAlias
*GV
);
1272 void printFunction(const Function
*F
);
1273 void printArgument(const Argument
*FA
, Attributes Attrs
);
1274 void printBasicBlock(const BasicBlock
*BB
);
1275 void printInstruction(const Instruction
&I
);
1278 // printInfoComment - Print a little comment after the instruction indicating
1279 // which slot it occupies.
1280 void printInfoComment(const Value
&V
);
1282 } // end of anonymous namespace
1284 void AssemblyWriter::writeOperand(const Value
*Operand
, bool PrintType
) {
1286 Out
<< "<null operand!>";
1290 TypePrinter
.print(Operand
->getType(), Out
);
1293 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
1296 void AssemblyWriter::writeParamOperand(const Value
*Operand
,
1299 Out
<< "<null operand!>";
1304 TypePrinter
.print(Operand
->getType(), Out
);
1305 // Print parameter attributes list
1306 if (Attrs
!= Attribute::None
)
1307 Out
<< ' ' << Attribute::getAsString(Attrs
);
1309 // Print the operand
1310 WriteAsOperandInternal(Out
, Operand
, &TypePrinter
, &Machine
, TheModule
);
1313 void AssemblyWriter::printModule(const Module
*M
) {
1314 if (!M
->getModuleIdentifier().empty() &&
1315 // Don't print the ID if it will start a new line (which would
1316 // require a comment char before it).
1317 M
->getModuleIdentifier().find('\n') == std::string::npos
)
1318 Out
<< "; ModuleID = '" << M
->getModuleIdentifier() << "'\n";
1320 if (!M
->getDataLayout().empty())
1321 Out
<< "target datalayout = \"" << M
->getDataLayout() << "\"\n";
1322 if (!M
->getTargetTriple().empty())
1323 Out
<< "target triple = \"" << M
->getTargetTriple() << "\"\n";
1325 if (!M
->getModuleInlineAsm().empty()) {
1326 // Split the string into lines, to make it easier to read the .ll file.
1327 std::string Asm
= M
->getModuleInlineAsm();
1329 size_t NewLine
= Asm
.find_first_of('\n', CurPos
);
1331 while (NewLine
!= std::string::npos
) {
1332 // We found a newline, print the portion of the asm string from the
1333 // last newline up to this newline.
1334 Out
<< "module asm \"";
1335 PrintEscapedString(std::string(Asm
.begin()+CurPos
, Asm
.begin()+NewLine
),
1339 NewLine
= Asm
.find_first_of('\n', CurPos
);
1341 std::string
rest(Asm
.begin()+CurPos
, Asm
.end());
1342 if (!rest
.empty()) {
1343 Out
<< "module asm \"";
1344 PrintEscapedString(rest
, Out
);
1349 // Loop over the dependent libraries and emit them.
1350 Module::lib_iterator LI
= M
->lib_begin();
1351 Module::lib_iterator LE
= M
->lib_end();
1354 Out
<< "deplibs = [ ";
1356 Out
<< '"' << *LI
<< '"';
1364 // Loop over the symbol table, emitting all id'd types.
1365 if (!M
->getTypeSymbolTable().empty() || !NumberedTypes
.empty()) Out
<< '\n';
1366 printTypeSymbolTable(M
->getTypeSymbolTable());
1368 // Output all globals.
1369 if (!M
->global_empty()) Out
<< '\n';
1370 for (Module::const_global_iterator I
= M
->global_begin(), E
= M
->global_end();
1374 // Output all aliases.
1375 if (!M
->alias_empty()) Out
<< "\n";
1376 for (Module::const_alias_iterator I
= M
->alias_begin(), E
= M
->alias_end();
1380 // Output all of the functions.
1381 for (Module::const_iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++I
)
1384 // Output named metadata.
1385 if (!M
->named_metadata_empty()) Out
<< '\n';
1387 for (Module::const_named_metadata_iterator I
= M
->named_metadata_begin(),
1388 E
= M
->named_metadata_end(); I
!= E
; ++I
)
1389 printNamedMDNode(I
);
1392 if (!Machine
.mdn_empty()) {
1398 void AssemblyWriter::printNamedMDNode(const NamedMDNode
*NMD
) {
1399 Out
<< "!" << NMD
->getName() << " = !{";
1400 for (unsigned i
= 0, e
= NMD
->getNumOperands(); i
!= e
; ++i
) {
1402 int Slot
= Machine
.getMetadataSlot(NMD
->getOperand(i
));
1412 static void PrintLinkage(GlobalValue::LinkageTypes LT
,
1413 formatted_raw_ostream
&Out
) {
1415 case GlobalValue::ExternalLinkage
: break;
1416 case GlobalValue::PrivateLinkage
: Out
<< "private "; break;
1417 case GlobalValue::LinkerPrivateLinkage
: Out
<< "linker_private "; break;
1418 case GlobalValue::LinkerPrivateWeakLinkage
:
1419 Out
<< "linker_private_weak ";
1421 case GlobalValue::LinkerPrivateWeakDefAutoLinkage
:
1422 Out
<< "linker_private_weak_def_auto ";
1424 case GlobalValue::InternalLinkage
: Out
<< "internal "; break;
1425 case GlobalValue::LinkOnceAnyLinkage
: Out
<< "linkonce "; break;
1426 case GlobalValue::LinkOnceODRLinkage
: Out
<< "linkonce_odr "; break;
1427 case GlobalValue::WeakAnyLinkage
: Out
<< "weak "; break;
1428 case GlobalValue::WeakODRLinkage
: Out
<< "weak_odr "; break;
1429 case GlobalValue::CommonLinkage
: Out
<< "common "; break;
1430 case GlobalValue::AppendingLinkage
: Out
<< "appending "; break;
1431 case GlobalValue::DLLImportLinkage
: Out
<< "dllimport "; break;
1432 case GlobalValue::DLLExportLinkage
: Out
<< "dllexport "; break;
1433 case GlobalValue::ExternalWeakLinkage
: Out
<< "extern_weak "; break;
1434 case GlobalValue::AvailableExternallyLinkage
:
1435 Out
<< "available_externally ";
1441 static void PrintVisibility(GlobalValue::VisibilityTypes Vis
,
1442 formatted_raw_ostream
&Out
) {
1444 case GlobalValue::DefaultVisibility
: break;
1445 case GlobalValue::HiddenVisibility
: Out
<< "hidden "; break;
1446 case GlobalValue::ProtectedVisibility
: Out
<< "protected "; break;
1450 void AssemblyWriter::printGlobal(const GlobalVariable
*GV
) {
1451 if (GV
->isMaterializable())
1452 Out
<< "; Materializable\n";
1454 WriteAsOperandInternal(Out
, GV
, &TypePrinter
, &Machine
, GV
->getParent());
1457 if (!GV
->hasInitializer() && GV
->hasExternalLinkage())
1460 PrintLinkage(GV
->getLinkage(), Out
);
1461 PrintVisibility(GV
->getVisibility(), Out
);
1463 if (GV
->isThreadLocal()) Out
<< "thread_local ";
1464 if (unsigned AddressSpace
= GV
->getType()->getAddressSpace())
1465 Out
<< "addrspace(" << AddressSpace
<< ") ";
1466 if (GV
->hasUnnamedAddr()) Out
<< "unnamed_addr ";
1467 Out
<< (GV
->isConstant() ? "constant " : "global ");
1468 TypePrinter
.print(GV
->getType()->getElementType(), Out
);
1470 if (GV
->hasInitializer()) {
1472 writeOperand(GV
->getInitializer(), false);
1475 if (GV
->hasSection()) {
1476 Out
<< ", section \"";
1477 PrintEscapedString(GV
->getSection(), Out
);
1480 if (GV
->getAlignment())
1481 Out
<< ", align " << GV
->getAlignment();
1483 printInfoComment(*GV
);
1487 void AssemblyWriter::printAlias(const GlobalAlias
*GA
) {
1488 if (GA
->isMaterializable())
1489 Out
<< "; Materializable\n";
1491 // Don't crash when dumping partially built GA
1493 Out
<< "<<nameless>> = ";
1495 PrintLLVMName(Out
, GA
);
1498 PrintVisibility(GA
->getVisibility(), Out
);
1502 PrintLinkage(GA
->getLinkage(), Out
);
1504 const Constant
*Aliasee
= GA
->getAliasee();
1506 if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(Aliasee
)) {
1507 TypePrinter
.print(GV
->getType(), Out
);
1509 PrintLLVMName(Out
, GV
);
1510 } else if (const Function
*F
= dyn_cast
<Function
>(Aliasee
)) {
1511 TypePrinter
.print(F
->getFunctionType(), Out
);
1514 WriteAsOperandInternal(Out
, F
, &TypePrinter
, &Machine
, F
->getParent());
1515 } else if (const GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(Aliasee
)) {
1516 TypePrinter
.print(GA
->getType(), Out
);
1518 PrintLLVMName(Out
, GA
);
1520 const ConstantExpr
*CE
= cast
<ConstantExpr
>(Aliasee
);
1521 // The only valid GEP is an all zero GEP.
1522 assert((CE
->getOpcode() == Instruction::BitCast
||
1523 CE
->getOpcode() == Instruction::GetElementPtr
) &&
1524 "Unsupported aliasee");
1525 writeOperand(CE
, false);
1528 printInfoComment(*GA
);
1532 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable
&ST
) {
1533 // Emit all numbered types.
1534 for (unsigned i
= 0, e
= NumberedTypes
.size(); i
!= e
; ++i
) {
1535 Out
<< '%' << i
<< " = type ";
1537 // Make sure we print out at least one level of the type structure, so
1538 // that we do not get %2 = type %2
1539 TypePrinter
.printAtLeastOneLevel(NumberedTypes
[i
], Out
);
1543 // Print the named types.
1544 for (TypeSymbolTable::const_iterator TI
= ST
.begin(), TE
= ST
.end();
1546 PrintLLVMName(Out
, TI
->first
, LocalPrefix
);
1549 // Make sure we print out at least one level of the type structure, so
1550 // that we do not get %FILE = type %FILE
1551 TypePrinter
.printAtLeastOneLevel(TI
->second
, Out
);
1556 /// printFunction - Print all aspects of a function.
1558 void AssemblyWriter::printFunction(const Function
*F
) {
1559 // Print out the return type and name.
1562 if (AnnotationWriter
) AnnotationWriter
->emitFunctionAnnot(F
, Out
);
1564 if (F
->isMaterializable())
1565 Out
<< "; Materializable\n";
1567 if (F
->isDeclaration())
1572 PrintLinkage(F
->getLinkage(), Out
);
1573 PrintVisibility(F
->getVisibility(), Out
);
1575 // Print the calling convention.
1576 switch (F
->getCallingConv()) {
1577 case CallingConv::C
: break; // default
1578 case CallingConv::Fast
: Out
<< "fastcc "; break;
1579 case CallingConv::Cold
: Out
<< "coldcc "; break;
1580 case CallingConv::X86_StdCall
: Out
<< "x86_stdcallcc "; break;
1581 case CallingConv::X86_FastCall
: Out
<< "x86_fastcallcc "; break;
1582 case CallingConv::X86_ThisCall
: Out
<< "x86_thiscallcc "; break;
1583 case CallingConv::ARM_APCS
: Out
<< "arm_apcscc "; break;
1584 case CallingConv::ARM_AAPCS
: Out
<< "arm_aapcscc "; break;
1585 case CallingConv::ARM_AAPCS_VFP
:Out
<< "arm_aapcs_vfpcc "; break;
1586 case CallingConv::MSP430_INTR
: Out
<< "msp430_intrcc "; break;
1587 case CallingConv::PTX_Kernel
: Out
<< "ptx_kernel "; break;
1588 case CallingConv::PTX_Device
: Out
<< "ptx_device "; break;
1589 default: Out
<< "cc" << F
->getCallingConv() << " "; break;
1592 const FunctionType
*FT
= F
->getFunctionType();
1593 const AttrListPtr
&Attrs
= F
->getAttributes();
1594 Attributes RetAttrs
= Attrs
.getRetAttributes();
1595 if (RetAttrs
!= Attribute::None
)
1596 Out
<< Attribute::getAsString(Attrs
.getRetAttributes()) << ' ';
1597 TypePrinter
.print(F
->getReturnType(), Out
);
1599 WriteAsOperandInternal(Out
, F
, &TypePrinter
, &Machine
, F
->getParent());
1601 Machine
.incorporateFunction(F
);
1603 // Loop over the arguments, printing them...
1606 if (!F
->isDeclaration()) {
1607 // If this isn't a declaration, print the argument names as well.
1608 for (Function::const_arg_iterator I
= F
->arg_begin(), E
= F
->arg_end();
1610 // Insert commas as we go... the first arg doesn't get a comma
1611 if (I
!= F
->arg_begin()) Out
<< ", ";
1612 printArgument(I
, Attrs
.getParamAttributes(Idx
));
1616 // Otherwise, print the types from the function type.
1617 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
1618 // Insert commas as we go... the first arg doesn't get a comma
1622 TypePrinter
.print(FT
->getParamType(i
), Out
);
1624 Attributes ArgAttrs
= Attrs
.getParamAttributes(i
+1);
1625 if (ArgAttrs
!= Attribute::None
)
1626 Out
<< ' ' << Attribute::getAsString(ArgAttrs
);
1630 // Finish printing arguments...
1631 if (FT
->isVarArg()) {
1632 if (FT
->getNumParams()) Out
<< ", ";
1633 Out
<< "..."; // Output varargs portion of signature!
1636 if (F
->hasUnnamedAddr())
1637 Out
<< " unnamed_addr";
1638 Attributes FnAttrs
= Attrs
.getFnAttributes();
1639 if (FnAttrs
!= Attribute::None
)
1640 Out
<< ' ' << Attribute::getAsString(Attrs
.getFnAttributes());
1641 if (F
->hasSection()) {
1642 Out
<< " section \"";
1643 PrintEscapedString(F
->getSection(), Out
);
1646 if (F
->getAlignment())
1647 Out
<< " align " << F
->getAlignment();
1649 Out
<< " gc \"" << F
->getGC() << '"';
1650 if (F
->isDeclaration()) {
1654 // Output all of the function's basic blocks.
1655 for (Function::const_iterator I
= F
->begin(), E
= F
->end(); I
!= E
; ++I
)
1661 Machine
.purgeFunction();
1664 /// printArgument - This member is called for every argument that is passed into
1665 /// the function. Simply print it out
1667 void AssemblyWriter::printArgument(const Argument
*Arg
,
1670 TypePrinter
.print(Arg
->getType(), Out
);
1672 // Output parameter attributes list
1673 if (Attrs
!= Attribute::None
)
1674 Out
<< ' ' << Attribute::getAsString(Attrs
);
1676 // Output name, if available...
1677 if (Arg
->hasName()) {
1679 PrintLLVMName(Out
, Arg
);
1683 /// printBasicBlock - This member is called for each basic block in a method.
1685 void AssemblyWriter::printBasicBlock(const BasicBlock
*BB
) {
1686 if (BB
->hasName()) { // Print out the label if it exists...
1688 PrintLLVMName(Out
, BB
->getName(), LabelPrefix
);
1690 } else if (!BB
->use_empty()) { // Don't print block # of no uses...
1691 Out
<< "\n; <label>:";
1692 int Slot
= Machine
.getLocalSlot(BB
);
1699 if (BB
->getParent() == 0) {
1700 Out
.PadToColumn(50);
1701 Out
<< "; Error: Block without parent!";
1702 } else if (BB
!= &BB
->getParent()->getEntryBlock()) { // Not the entry block?
1703 // Output predecessors for the block.
1704 Out
.PadToColumn(50);
1706 const_pred_iterator PI
= pred_begin(BB
), PE
= pred_end(BB
);
1709 Out
<< " No predecessors!";
1712 writeOperand(*PI
, false);
1713 for (++PI
; PI
!= PE
; ++PI
) {
1715 writeOperand(*PI
, false);
1722 if (AnnotationWriter
) AnnotationWriter
->emitBasicBlockStartAnnot(BB
, Out
);
1724 // Output all of the instructions in the basic block...
1725 for (BasicBlock::const_iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ++I
) {
1726 printInstruction(*I
);
1730 if (AnnotationWriter
) AnnotationWriter
->emitBasicBlockEndAnnot(BB
, Out
);
1733 /// printInfoComment - Print a little comment after the instruction indicating
1734 /// which slot it occupies.
1736 void AssemblyWriter::printInfoComment(const Value
&V
) {
1737 if (AnnotationWriter
) {
1738 AnnotationWriter
->printInfoComment(V
, Out
);
1743 // This member is called for each Instruction in a function..
1744 void AssemblyWriter::printInstruction(const Instruction
&I
) {
1745 if (AnnotationWriter
) AnnotationWriter
->emitInstructionAnnot(&I
, Out
);
1747 // Print out indentation for an instruction.
1750 // Print out name if it exists...
1752 PrintLLVMName(Out
, &I
);
1754 } else if (!I
.getType()->isVoidTy()) {
1755 // Print out the def slot taken.
1756 int SlotNum
= Machine
.getLocalSlot(&I
);
1758 Out
<< "<badref> = ";
1760 Out
<< '%' << SlotNum
<< " = ";
1763 // If this is a volatile load or store, print out the volatile marker.
1764 if ((isa
<LoadInst
>(I
) && cast
<LoadInst
>(I
).isVolatile()) ||
1765 (isa
<StoreInst
>(I
) && cast
<StoreInst
>(I
).isVolatile())) {
1767 } else if (isa
<CallInst
>(I
) && cast
<CallInst
>(I
).isTailCall()) {
1768 // If this is a call, check if it's a tail call.
1772 // Print out the opcode...
1773 Out
<< I
.getOpcodeName();
1775 // Print out optimization information.
1776 WriteOptimizationInfo(Out
, &I
);
1778 // Print out the compare instruction predicates
1779 if (const CmpInst
*CI
= dyn_cast
<CmpInst
>(&I
))
1780 Out
<< ' ' << getPredicateText(CI
->getPredicate());
1782 // Print out the type of the operands...
1783 const Value
*Operand
= I
.getNumOperands() ? I
.getOperand(0) : 0;
1785 // Special case conditional branches to swizzle the condition out to the front
1786 if (isa
<BranchInst
>(I
) && cast
<BranchInst
>(I
).isConditional()) {
1787 BranchInst
&BI(cast
<BranchInst
>(I
));
1789 writeOperand(BI
.getCondition(), true);
1791 writeOperand(BI
.getSuccessor(0), true);
1793 writeOperand(BI
.getSuccessor(1), true);
1795 } else if (isa
<SwitchInst
>(I
)) {
1796 // Special case switch instruction to get formatting nice and correct.
1798 writeOperand(Operand
, true);
1800 writeOperand(I
.getOperand(1), true);
1803 for (unsigned op
= 2, Eop
= I
.getNumOperands(); op
< Eop
; op
+= 2) {
1805 writeOperand(I
.getOperand(op
), true);
1807 writeOperand(I
.getOperand(op
+1), true);
1810 } else if (isa
<IndirectBrInst
>(I
)) {
1811 // Special case indirectbr instruction to get formatting nice and correct.
1813 writeOperand(Operand
, true);
1816 for (unsigned i
= 1, e
= I
.getNumOperands(); i
!= e
; ++i
) {
1819 writeOperand(I
.getOperand(i
), true);
1822 } else if (isa
<PHINode
>(I
)) {
1824 TypePrinter
.print(I
.getType(), Out
);
1827 for (unsigned op
= 0, Eop
= I
.getNumOperands(); op
< Eop
; op
+= 2) {
1828 if (op
) Out
<< ", ";
1830 writeOperand(I
.getOperand(op
), false); Out
<< ", ";
1831 writeOperand(I
.getOperand(op
+1), false); Out
<< " ]";
1833 } else if (const ExtractValueInst
*EVI
= dyn_cast
<ExtractValueInst
>(&I
)) {
1835 writeOperand(I
.getOperand(0), true);
1836 for (const unsigned *i
= EVI
->idx_begin(), *e
= EVI
->idx_end(); i
!= e
; ++i
)
1838 } else if (const InsertValueInst
*IVI
= dyn_cast
<InsertValueInst
>(&I
)) {
1840 writeOperand(I
.getOperand(0), true); Out
<< ", ";
1841 writeOperand(I
.getOperand(1), true);
1842 for (const unsigned *i
= IVI
->idx_begin(), *e
= IVI
->idx_end(); i
!= e
; ++i
)
1844 } else if (isa
<ReturnInst
>(I
) && !Operand
) {
1846 } else if (const CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
1847 // Print the calling convention being used.
1848 switch (CI
->getCallingConv()) {
1849 case CallingConv::C
: break; // default
1850 case CallingConv::Fast
: Out
<< " fastcc"; break;
1851 case CallingConv::Cold
: Out
<< " coldcc"; break;
1852 case CallingConv::X86_StdCall
: Out
<< " x86_stdcallcc"; break;
1853 case CallingConv::X86_FastCall
: Out
<< " x86_fastcallcc"; break;
1854 case CallingConv::X86_ThisCall
: Out
<< " x86_thiscallcc"; break;
1855 case CallingConv::ARM_APCS
: Out
<< " arm_apcscc "; break;
1856 case CallingConv::ARM_AAPCS
: Out
<< " arm_aapcscc "; break;
1857 case CallingConv::ARM_AAPCS_VFP
:Out
<< " arm_aapcs_vfpcc "; break;
1858 case CallingConv::MSP430_INTR
: Out
<< " msp430_intrcc "; break;
1859 case CallingConv::PTX_Kernel
: Out
<< " ptx_kernel"; break;
1860 case CallingConv::PTX_Device
: Out
<< " ptx_device"; break;
1861 default: Out
<< " cc" << CI
->getCallingConv(); break;
1864 Operand
= CI
->getCalledValue();
1865 const PointerType
*PTy
= cast
<PointerType
>(Operand
->getType());
1866 const FunctionType
*FTy
= cast
<FunctionType
>(PTy
->getElementType());
1867 const Type
*RetTy
= FTy
->getReturnType();
1868 const AttrListPtr
&PAL
= CI
->getAttributes();
1870 if (PAL
.getRetAttributes() != Attribute::None
)
1871 Out
<< ' ' << Attribute::getAsString(PAL
.getRetAttributes());
1873 // If possible, print out the short form of the call instruction. We can
1874 // only do this if the first argument is a pointer to a nonvararg function,
1875 // and if the return type is not a pointer to a function.
1878 if (!FTy
->isVarArg() &&
1879 (!RetTy
->isPointerTy() ||
1880 !cast
<PointerType
>(RetTy
)->getElementType()->isFunctionTy())) {
1881 TypePrinter
.print(RetTy
, Out
);
1883 writeOperand(Operand
, false);
1885 writeOperand(Operand
, true);
1888 for (unsigned op
= 0, Eop
= CI
->getNumArgOperands(); op
< Eop
; ++op
) {
1891 writeParamOperand(CI
->getArgOperand(op
), PAL
.getParamAttributes(op
+ 1));
1894 if (PAL
.getFnAttributes() != Attribute::None
)
1895 Out
<< ' ' << Attribute::getAsString(PAL
.getFnAttributes());
1896 } else if (const InvokeInst
*II
= dyn_cast
<InvokeInst
>(&I
)) {
1897 Operand
= II
->getCalledValue();
1898 const PointerType
*PTy
= cast
<PointerType
>(Operand
->getType());
1899 const FunctionType
*FTy
= cast
<FunctionType
>(PTy
->getElementType());
1900 const Type
*RetTy
= FTy
->getReturnType();
1901 const AttrListPtr
&PAL
= II
->getAttributes();
1903 // Print the calling convention being used.
1904 switch (II
->getCallingConv()) {
1905 case CallingConv::C
: break; // default
1906 case CallingConv::Fast
: Out
<< " fastcc"; break;
1907 case CallingConv::Cold
: Out
<< " coldcc"; break;
1908 case CallingConv::X86_StdCall
: Out
<< " x86_stdcallcc"; break;
1909 case CallingConv::X86_FastCall
: Out
<< " x86_fastcallcc"; break;
1910 case CallingConv::X86_ThisCall
: Out
<< " x86_thiscallcc"; break;
1911 case CallingConv::ARM_APCS
: Out
<< " arm_apcscc "; break;
1912 case CallingConv::ARM_AAPCS
: Out
<< " arm_aapcscc "; break;
1913 case CallingConv::ARM_AAPCS_VFP
:Out
<< " arm_aapcs_vfpcc "; break;
1914 case CallingConv::MSP430_INTR
: Out
<< " msp430_intrcc "; break;
1915 case CallingConv::PTX_Kernel
: Out
<< " ptx_kernel"; break;
1916 case CallingConv::PTX_Device
: Out
<< " ptx_device"; break;
1917 default: Out
<< " cc" << II
->getCallingConv(); break;
1920 if (PAL
.getRetAttributes() != Attribute::None
)
1921 Out
<< ' ' << Attribute::getAsString(PAL
.getRetAttributes());
1923 // If possible, print out the short form of the invoke instruction. We can
1924 // only do this if the first argument is a pointer to a nonvararg function,
1925 // and if the return type is not a pointer to a function.
1928 if (!FTy
->isVarArg() &&
1929 (!RetTy
->isPointerTy() ||
1930 !cast
<PointerType
>(RetTy
)->getElementType()->isFunctionTy())) {
1931 TypePrinter
.print(RetTy
, Out
);
1933 writeOperand(Operand
, false);
1935 writeOperand(Operand
, true);
1938 for (unsigned op
= 0, Eop
= II
->getNumArgOperands(); op
< Eop
; ++op
) {
1941 writeParamOperand(II
->getArgOperand(op
), PAL
.getParamAttributes(op
+ 1));
1945 if (PAL
.getFnAttributes() != Attribute::None
)
1946 Out
<< ' ' << Attribute::getAsString(PAL
.getFnAttributes());
1949 writeOperand(II
->getNormalDest(), true);
1951 writeOperand(II
->getUnwindDest(), true);
1953 } else if (const AllocaInst
*AI
= dyn_cast
<AllocaInst
>(&I
)) {
1955 TypePrinter
.print(AI
->getType()->getElementType(), Out
);
1956 if (!AI
->getArraySize() || AI
->isArrayAllocation()) {
1958 writeOperand(AI
->getArraySize(), true);
1960 if (AI
->getAlignment()) {
1961 Out
<< ", align " << AI
->getAlignment();
1963 } else if (isa
<CastInst
>(I
)) {
1966 writeOperand(Operand
, true); // Work with broken code
1969 TypePrinter
.print(I
.getType(), Out
);
1970 } else if (isa
<VAArgInst
>(I
)) {
1973 writeOperand(Operand
, true); // Work with broken code
1976 TypePrinter
.print(I
.getType(), Out
);
1977 } else if (Operand
) { // Print the normal way.
1979 // PrintAllTypes - Instructions who have operands of all the same type
1980 // omit the type from all but the first operand. If the instruction has
1981 // different type operands (for example br), then they are all printed.
1982 bool PrintAllTypes
= false;
1983 const Type
*TheType
= Operand
->getType();
1985 // Select, Store and ShuffleVector always print all types.
1986 if (isa
<SelectInst
>(I
) || isa
<StoreInst
>(I
) || isa
<ShuffleVectorInst
>(I
)
1987 || isa
<ReturnInst
>(I
)) {
1988 PrintAllTypes
= true;
1990 for (unsigned i
= 1, E
= I
.getNumOperands(); i
!= E
; ++i
) {
1991 Operand
= I
.getOperand(i
);
1992 // note that Operand shouldn't be null, but the test helps make dump()
1993 // more tolerant of malformed IR
1994 if (Operand
&& Operand
->getType() != TheType
) {
1995 PrintAllTypes
= true; // We have differing types! Print them all!
2001 if (!PrintAllTypes
) {
2003 TypePrinter
.print(TheType
, Out
);
2007 for (unsigned i
= 0, E
= I
.getNumOperands(); i
!= E
; ++i
) {
2009 writeOperand(I
.getOperand(i
), PrintAllTypes
);
2013 // Print post operand alignment for load/store.
2014 if (isa
<LoadInst
>(I
) && cast
<LoadInst
>(I
).getAlignment()) {
2015 Out
<< ", align " << cast
<LoadInst
>(I
).getAlignment();
2016 } else if (isa
<StoreInst
>(I
) && cast
<StoreInst
>(I
).getAlignment()) {
2017 Out
<< ", align " << cast
<StoreInst
>(I
).getAlignment();
2020 // Print Metadata info.
2021 SmallVector
<std::pair
<unsigned, MDNode
*>, 4> InstMD
;
2022 I
.getAllMetadata(InstMD
);
2023 if (!InstMD
.empty()) {
2024 SmallVector
<StringRef
, 8> MDNames
;
2025 I
.getType()->getContext().getMDKindNames(MDNames
);
2026 for (unsigned i
= 0, e
= InstMD
.size(); i
!= e
; ++i
) {
2027 unsigned Kind
= InstMD
[i
].first
;
2028 if (Kind
< MDNames
.size()) {
2029 Out
<< ", !" << MDNames
[Kind
];
2031 Out
<< ", !<unknown kind #" << Kind
<< ">";
2034 WriteAsOperandInternal(Out
, InstMD
[i
].second
, &TypePrinter
, &Machine
,
2038 printInfoComment(I
);
2041 static void WriteMDNodeComment(const MDNode
*Node
,
2042 formatted_raw_ostream
&Out
) {
2043 if (Node
->getNumOperands() < 1)
2045 ConstantInt
*CI
= dyn_cast_or_null
<ConstantInt
>(Node
->getOperand(0));
2047 APInt Val
= CI
->getValue();
2048 APInt Tag
= Val
& ~APInt(Val
.getBitWidth(), LLVMDebugVersionMask
);
2049 if (Val
.ult(LLVMDebugVersion
))
2052 Out
.PadToColumn(50);
2053 if (Tag
== dwarf::DW_TAG_user_base
)
2054 Out
<< "; [ DW_TAG_user_base ]";
2055 else if (Tag
.isIntN(32)) {
2056 if (const char *TagName
= dwarf::TagString(Tag
.getZExtValue()))
2057 Out
<< "; [ " << TagName
<< " ]";
2061 void AssemblyWriter::writeAllMDNodes() {
2062 SmallVector
<const MDNode
*, 16> Nodes
;
2063 Nodes
.resize(Machine
.mdn_size());
2064 for (SlotTracker::mdn_iterator I
= Machine
.mdn_begin(), E
= Machine
.mdn_end();
2066 Nodes
[I
->second
] = cast
<MDNode
>(I
->first
);
2068 for (unsigned i
= 0, e
= Nodes
.size(); i
!= e
; ++i
) {
2069 Out
<< '!' << i
<< " = metadata ";
2070 printMDNodeBody(Nodes
[i
]);
2074 void AssemblyWriter::printMDNodeBody(const MDNode
*Node
) {
2075 WriteMDNodeBodyInternal(Out
, Node
, &TypePrinter
, &Machine
, TheModule
);
2076 WriteMDNodeComment(Node
, Out
);
2080 //===----------------------------------------------------------------------===//
2081 // External Interface declarations
2082 //===----------------------------------------------------------------------===//
2084 void Module::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
) const {
2085 SlotTracker
SlotTable(this);
2086 formatted_raw_ostream
OS(ROS
);
2087 AssemblyWriter
W(OS
, SlotTable
, this, AAW
);
2088 W
.printModule(this);
2091 void NamedMDNode::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
) const {
2092 SlotTracker
SlotTable(getParent());
2093 formatted_raw_ostream
OS(ROS
);
2094 AssemblyWriter
W(OS
, SlotTable
, getParent(), AAW
);
2095 W
.printNamedMDNode(this);
2098 void Type::print(raw_ostream
&OS
) const {
2100 OS
<< "<null Type>";
2103 TypePrinting().print(this, OS
);
2106 void Value::print(raw_ostream
&ROS
, AssemblyAnnotationWriter
*AAW
) const {
2108 ROS
<< "printing a <null> value\n";
2111 formatted_raw_ostream
OS(ROS
);
2112 if (const Instruction
*I
= dyn_cast
<Instruction
>(this)) {
2113 const Function
*F
= I
->getParent() ? I
->getParent()->getParent() : 0;
2114 SlotTracker
SlotTable(F
);
2115 AssemblyWriter
W(OS
, SlotTable
, getModuleFromVal(I
), AAW
);
2116 W
.printInstruction(*I
);
2117 } else if (const BasicBlock
*BB
= dyn_cast
<BasicBlock
>(this)) {
2118 SlotTracker
SlotTable(BB
->getParent());
2119 AssemblyWriter
W(OS
, SlotTable
, getModuleFromVal(BB
), AAW
);
2120 W
.printBasicBlock(BB
);
2121 } else if (const GlobalValue
*GV
= dyn_cast
<GlobalValue
>(this)) {
2122 SlotTracker
SlotTable(GV
->getParent());
2123 AssemblyWriter
W(OS
, SlotTable
, GV
->getParent(), AAW
);
2124 if (const GlobalVariable
*V
= dyn_cast
<GlobalVariable
>(GV
))
2126 else if (const Function
*F
= dyn_cast
<Function
>(GV
))
2129 W
.printAlias(cast
<GlobalAlias
>(GV
));
2130 } else if (const MDNode
*N
= dyn_cast
<MDNode
>(this)) {
2131 const Function
*F
= N
->getFunction();
2132 SlotTracker
SlotTable(F
);
2133 AssemblyWriter
W(OS
, SlotTable
, F
? F
->getParent() : 0, AAW
);
2134 W
.printMDNodeBody(N
);
2135 } else if (const Constant
*C
= dyn_cast
<Constant
>(this)) {
2136 TypePrinting TypePrinter
;
2137 TypePrinter
.print(C
->getType(), OS
);
2139 WriteConstantInternal(OS
, C
, TypePrinter
, 0, 0);
2140 } else if (isa
<InlineAsm
>(this) || isa
<MDString
>(this) ||
2141 isa
<Argument
>(this)) {
2142 WriteAsOperand(OS
, this, true, 0);
2144 // Otherwise we don't know what it is. Call the virtual function to
2145 // allow a subclass to print itself.
2150 // Value::printCustom - subclasses should override this to implement printing.
2151 void Value::printCustom(raw_ostream
&OS
) const {
2152 llvm_unreachable("Unknown value to print out!");
2155 // Value::dump - allow easy printing of Values from the debugger.
2156 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2158 // Type::dump - allow easy printing of Types from the debugger.
2159 // This one uses type names from the given context module
2160 void Type::dump(const Module
*Context
) const {
2161 WriteTypeSymbolic(dbgs(), this, Context
);
2165 // Type::dump - allow easy printing of Types from the debugger.
2166 void Type::dump() const { dump(0); }
2168 // Module::dump() - Allow printing of Modules from the debugger.
2169 void Module::dump() const { print(dbgs(), 0); }