1
//===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This library implements the functionality defined in llvm/Assembly/Writer.h
12
// Note that these routines must be extremely tolerant of various errors in the
13
// LLVM code, because it can be used for debugging transformations.
15
//===----------------------------------------------------------------------===//
17
#include "llvm/Assembly/Writer.h"
18
#include "llvm/Assembly/PrintModulePass.h"
19
#include "llvm/Assembly/AsmAnnotationWriter.h"
20
#include "llvm/LLVMContext.h"
21
#include "llvm/CallingConv.h"
22
#include "llvm/Constants.h"
23
#include "llvm/DerivedTypes.h"
24
#include "llvm/InlineAsm.h"
25
#include "llvm/IntrinsicInst.h"
26
#include "llvm/Operator.h"
27
#include "llvm/Module.h"
28
#include "llvm/ValueSymbolTable.h"
29
#include "llvm/TypeSymbolTable.h"
30
#include "llvm/ADT/DenseSet.h"
31
#include "llvm/ADT/SmallString.h"
32
#include "llvm/ADT/StringExtras.h"
33
#include "llvm/ADT/STLExtras.h"
34
#include "llvm/Support/CFG.h"
35
#include "llvm/Support/Debug.h"
36
#include "llvm/Support/Dwarf.h"
37
#include "llvm/Support/ErrorHandling.h"
38
#include "llvm/Support/MathExtras.h"
39
#include "llvm/Support/FormattedStream.h"
45
// Make virtual table appear in this compilation unit.
46
AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
48
//===----------------------------------------------------------------------===//
50
//===----------------------------------------------------------------------===//
52
static const Module *getModuleFromVal(const Value *V) {
53
if (const Argument *MA = dyn_cast<Argument>(V))
54
return MA->getParent() ? MA->getParent()->getParent() : 0;
56
if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
57
return BB->getParent() ? BB->getParent()->getParent() : 0;
59
if (const Instruction *I = dyn_cast<Instruction>(V)) {
60
const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
61
return M ? M->getParent() : 0;
64
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
65
return GV->getParent();
66
if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
67
return NMD->getParent();
71
// PrintEscapedString - Print each character of the specified string, escaping
72
// it if it is not printable or if it is an escape char.
73
static void PrintEscapedString(const StringRef &Name,
75
for (unsigned i = 0, e = Name.size(); i != e; ++i) {
76
unsigned char C = Name[i];
77
if (isprint(C) && C != '\\' && C != '"')
80
Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
91
/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
92
/// prefixed with % (if the string only contains simple characters) or is
93
/// surrounded with ""'s (if it has special chars in it). Print it out.
94
static void PrintLLVMName(raw_ostream &OS, const StringRef &Name,
96
assert(Name.data() && "Cannot get empty name!");
98
default: llvm_unreachable("Bad prefix!");
100
case GlobalPrefix: OS << '@'; break;
101
case LabelPrefix: break;
102
case LocalPrefix: OS << '%'; break;
105
// Scan the name to see if it needs quotes first.
106
bool NeedsQuotes = isdigit(Name[0]);
108
for (unsigned i = 0, e = Name.size(); i != e; ++i) {
110
if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
117
// If we didn't need any quotes, just write out the name in one blast.
123
// Okay, we need quotes. Output the quotes and escape any scary characters as
126
PrintEscapedString(Name, OS);
130
/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
131
/// prefixed with % (if the string only contains simple characters) or is
132
/// surrounded with ""'s (if it has special chars in it). Print it out.
133
static void PrintLLVMName(raw_ostream &OS, const Value *V) {
134
PrintLLVMName(OS, V->getName(),
135
isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
138
//===----------------------------------------------------------------------===//
139
// TypePrinting Class: Type printing machinery
140
//===----------------------------------------------------------------------===//
142
static DenseMap<const Type *, std::string> &getTypeNamesMap(void *M) {
143
return *static_cast<DenseMap<const Type *, std::string>*>(M);
146
void TypePrinting::clear() {
147
getTypeNamesMap(TypeNames).clear();
150
bool TypePrinting::hasTypeName(const Type *Ty) const {
151
return getTypeNamesMap(TypeNames).count(Ty);
154
void TypePrinting::addTypeName(const Type *Ty, const std::string &N) {
155
getTypeNamesMap(TypeNames).insert(std::make_pair(Ty, N));
159
TypePrinting::TypePrinting() {
160
TypeNames = new DenseMap<const Type *, std::string>();
163
TypePrinting::~TypePrinting() {
164
delete &getTypeNamesMap(TypeNames);
167
/// CalcTypeName - Write the specified type to the specified raw_ostream, making
168
/// use of type names or up references to shorten the type name where possible.
169
void TypePrinting::CalcTypeName(const Type *Ty,
170
SmallVectorImpl<const Type *> &TypeStack,
171
raw_ostream &OS, bool IgnoreTopLevelName) {
172
// Check to see if the type is named.
173
if (!IgnoreTopLevelName) {
174
DenseMap<const Type *, std::string> &TM = getTypeNamesMap(TypeNames);
175
DenseMap<const Type *, std::string>::iterator I = TM.find(Ty);
182
// Check to see if the Type is already on the stack...
183
unsigned Slot = 0, CurSize = TypeStack.size();
184
while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
186
// This is another base case for the recursion. In this case, we know
187
// that we have looped back to a type that we have previously visited.
188
// Generate the appropriate upreference to handle this.
189
if (Slot < CurSize) {
190
OS << '\\' << unsigned(CurSize-Slot); // Here's the upreference
194
TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
196
switch (Ty->getTypeID()) {
197
case Type::VoidTyID: OS << "void"; break;
198
case Type::FloatTyID: OS << "float"; break;
199
case Type::DoubleTyID: OS << "double"; break;
200
case Type::X86_FP80TyID: OS << "x86_fp80"; break;
201
case Type::FP128TyID: OS << "fp128"; break;
202
case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
203
case Type::LabelTyID: OS << "label"; break;
204
case Type::MetadataTyID: OS << "metadata"; break;
205
case Type::IntegerTyID:
206
OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
209
case Type::FunctionTyID: {
210
const FunctionType *FTy = cast<FunctionType>(Ty);
211
CalcTypeName(FTy->getReturnType(), TypeStack, OS);
213
for (FunctionType::param_iterator I = FTy->param_begin(),
214
E = FTy->param_end(); I != E; ++I) {
215
if (I != FTy->param_begin())
217
CalcTypeName(*I, TypeStack, OS);
219
if (FTy->isVarArg()) {
220
if (FTy->getNumParams()) OS << ", ";
226
case Type::StructTyID: {
227
const StructType *STy = cast<StructType>(Ty);
231
for (StructType::element_iterator I = STy->element_begin(),
232
E = STy->element_end(); I != E; ++I) {
233
CalcTypeName(*I, TypeStack, OS);
234
if (next(I) != STy->element_end())
243
case Type::UnionTyID: {
244
const UnionType *UTy = cast<UnionType>(Ty);
246
for (StructType::element_iterator I = UTy->element_begin(),
247
E = UTy->element_end(); I != E; ++I) {
248
CalcTypeName(*I, TypeStack, OS);
249
if (next(I) != UTy->element_end())
256
case Type::PointerTyID: {
257
const PointerType *PTy = cast<PointerType>(Ty);
258
CalcTypeName(PTy->getElementType(), TypeStack, OS);
259
if (unsigned AddressSpace = PTy->getAddressSpace())
260
OS << " addrspace(" << AddressSpace << ')';
264
case Type::ArrayTyID: {
265
const ArrayType *ATy = cast<ArrayType>(Ty);
266
OS << '[' << ATy->getNumElements() << " x ";
267
CalcTypeName(ATy->getElementType(), TypeStack, OS);
271
case Type::VectorTyID: {
272
const VectorType *PTy = cast<VectorType>(Ty);
273
OS << "<" << PTy->getNumElements() << " x ";
274
CalcTypeName(PTy->getElementType(), TypeStack, OS);
278
case Type::OpaqueTyID:
282
OS << "<unrecognized-type>";
286
TypeStack.pop_back(); // Remove self from stack.
289
/// printTypeInt - The internal guts of printing out a type that has a
290
/// potentially named portion.
292
void TypePrinting::print(const Type *Ty, raw_ostream &OS,
293
bool IgnoreTopLevelName) {
294
// Check to see if the type is named.
295
DenseMap<const Type*, std::string> &TM = getTypeNamesMap(TypeNames);
296
if (!IgnoreTopLevelName) {
297
DenseMap<const Type*, std::string>::iterator I = TM.find(Ty);
304
// Otherwise we have a type that has not been named but is a derived type.
305
// Carefully recurse the type hierarchy to print out any contained symbolic
307
SmallVector<const Type *, 16> TypeStack;
308
std::string TypeName;
310
raw_string_ostream TypeOS(TypeName);
311
CalcTypeName(Ty, TypeStack, TypeOS, IgnoreTopLevelName);
314
// Cache type name for later use.
315
if (!IgnoreTopLevelName)
316
TM.insert(std::make_pair(Ty, TypeOS.str()));
321
// To avoid walking constant expressions multiple times and other IR
322
// objects, we keep several helper maps.
323
DenseSet<const Value*> VisitedConstants;
324
DenseSet<const Type*> VisitedTypes;
327
std::vector<const Type*> &NumberedTypes;
329
TypeFinder(TypePrinting &tp, std::vector<const Type*> &numberedTypes)
330
: TP(tp), NumberedTypes(numberedTypes) {}
332
void Run(const Module &M) {
333
// Get types from the type symbol table. This gets opaque types referened
334
// only through derived named types.
335
const TypeSymbolTable &ST = M.getTypeSymbolTable();
336
for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
338
IncorporateType(TI->second);
340
// Get types from global variables.
341
for (Module::const_global_iterator I = M.global_begin(),
342
E = M.global_end(); I != E; ++I) {
343
IncorporateType(I->getType());
344
if (I->hasInitializer())
345
IncorporateValue(I->getInitializer());
348
// Get types from aliases.
349
for (Module::const_alias_iterator I = M.alias_begin(),
350
E = M.alias_end(); I != E; ++I) {
351
IncorporateType(I->getType());
352
IncorporateValue(I->getAliasee());
355
// Get types from functions.
356
for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
357
IncorporateType(FI->getType());
359
for (Function::const_iterator BB = FI->begin(), E = FI->end();
361
for (BasicBlock::const_iterator II = BB->begin(),
362
E = BB->end(); II != E; ++II) {
363
const Instruction &I = *II;
364
// Incorporate the type of the instruction and all its operands.
365
IncorporateType(I.getType());
366
for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
368
IncorporateValue(*OI);
374
void IncorporateType(const Type *Ty) {
375
// Check to see if we're already visited this type.
376
if (!VisitedTypes.insert(Ty).second)
379
// If this is a structure or opaque type, add a name for the type.
380
if (((Ty->isStructTy() && cast<StructType>(Ty)->getNumElements())
381
|| Ty->isOpaqueTy()) && !TP.hasTypeName(Ty)) {
382
TP.addTypeName(Ty, "%"+utostr(unsigned(NumberedTypes.size())));
383
NumberedTypes.push_back(Ty);
386
// Recursively walk all contained types.
387
for (Type::subtype_iterator I = Ty->subtype_begin(),
388
E = Ty->subtype_end(); I != E; ++I)
392
/// IncorporateValue - This method is used to walk operand lists finding
393
/// types hiding in constant expressions and other operands that won't be
394
/// walked in other ways. GlobalValues, basic blocks, instructions, and
395
/// inst operands are all explicitly enumerated.
396
void IncorporateValue(const Value *V) {
397
if (V == 0 || !isa<Constant>(V) || isa<GlobalValue>(V)) return;
400
if (!VisitedConstants.insert(V).second)
404
IncorporateType(V->getType());
406
// Look in operands for types.
407
const Constant *C = cast<Constant>(V);
408
for (Constant::const_op_iterator I = C->op_begin(),
409
E = C->op_end(); I != E;++I)
410
IncorporateValue(*I);
413
} // end anonymous namespace
416
/// AddModuleTypesToPrinter - Add all of the symbolic type names for types in
417
/// the specified module to the TypePrinter and all numbered types to it and the
418
/// NumberedTypes table.
419
static void AddModuleTypesToPrinter(TypePrinting &TP,
420
std::vector<const Type*> &NumberedTypes,
424
// If the module has a symbol table, take all global types and stuff their
425
// names into the TypeNames map.
426
const TypeSymbolTable &ST = M->getTypeSymbolTable();
427
for (TypeSymbolTable::const_iterator TI = ST.begin(), E = ST.end();
429
const Type *Ty = cast<Type>(TI->second);
431
// As a heuristic, don't insert pointer to primitive types, because
432
// they are used too often to have a single useful name.
433
if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
434
const Type *PETy = PTy->getElementType();
435
if ((PETy->isPrimitiveType() || PETy->isIntegerTy()) &&
440
// Likewise don't insert primitives either.
441
if (Ty->isIntegerTy() || Ty->isPrimitiveType())
444
// Get the name as a string and insert it into TypeNames.
446
raw_string_ostream NameROS(NameStr);
447
formatted_raw_ostream NameOS(NameROS);
448
PrintLLVMName(NameOS, TI->first, LocalPrefix);
450
TP.addTypeName(Ty, NameStr);
453
// Walk the entire module to find references to unnamed structure and opaque
454
// types. This is required for correctness by opaque types (because multiple
455
// uses of an unnamed opaque type needs to be referred to by the same ID) and
456
// it shrinks complex recursive structure types substantially in some cases.
457
TypeFinder(TP, NumberedTypes).Run(*M);
461
/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
462
/// type, iff there is an entry in the modules symbol table for the specified
463
/// type or one of it's component types.
465
void llvm::WriteTypeSymbolic(raw_ostream &OS, const Type *Ty, const Module *M) {
466
TypePrinting Printer;
467
std::vector<const Type*> NumberedTypes;
468
AddModuleTypesToPrinter(Printer, NumberedTypes, M);
469
Printer.print(Ty, OS);
472
//===----------------------------------------------------------------------===//
473
// SlotTracker Class: Enumerate slot numbers for unnamed values
474
//===----------------------------------------------------------------------===//
478
/// This class provides computation of slot numbers for LLVM Assembly writing.
482
/// ValueMap - A mapping of Values to slot numbers.
483
typedef DenseMap<const Value*, unsigned> ValueMap;
486
/// TheModule - The module for which we are holding slot numbers.
487
const Module* TheModule;
489
/// TheFunction - The function for which we are holding slot numbers.
490
const Function* TheFunction;
491
bool FunctionProcessed;
493
/// mMap - The TypePlanes map for the module level data.
497
/// fMap - The TypePlanes map for the function level data.
501
/// mdnMap - Map for MDNodes.
502
DenseMap<const MDNode*, unsigned> mdnMap;
505
/// Construct from a module
506
explicit SlotTracker(const Module *M);
507
/// Construct from a function, starting out in incorp state.
508
explicit SlotTracker(const Function *F);
510
/// Return the slot number of the specified value in it's type
511
/// plane. If something is not in the SlotTracker, return -1.
512
int getLocalSlot(const Value *V);
513
int getGlobalSlot(const GlobalValue *V);
514
int getMetadataSlot(const MDNode *N);
516
/// If you'd like to deal with a function instead of just a module, use
517
/// this method to get its data into the SlotTracker.
518
void incorporateFunction(const Function *F) {
520
FunctionProcessed = false;
523
/// After calling incorporateFunction, use this method to remove the
524
/// most recently incorporated function from the SlotTracker. This
525
/// will reset the state of the machine back to just the module contents.
526
void purgeFunction();
528
/// MDNode map iterators.
529
typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
530
mdn_iterator mdn_begin() { return mdnMap.begin(); }
531
mdn_iterator mdn_end() { return mdnMap.end(); }
532
unsigned mdn_size() const { return mdnMap.size(); }
533
bool mdn_empty() const { return mdnMap.empty(); }
535
/// This function does the actual initialization.
536
inline void initialize();
538
// Implementation Details
540
/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
541
void CreateModuleSlot(const GlobalValue *V);
543
/// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
544
void CreateMetadataSlot(const MDNode *N);
546
/// CreateFunctionSlot - Insert the specified Value* into the slot table.
547
void CreateFunctionSlot(const Value *V);
549
/// Add all of the module level global variables (and their initializers)
550
/// and function declarations, but not the contents of those functions.
551
void processModule();
553
/// Add all of the functions arguments, basic blocks, and instructions.
554
void processFunction();
556
SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
557
void operator=(const SlotTracker &); // DO NOT IMPLEMENT
560
} // end anonymous namespace
563
static SlotTracker *createSlotTracker(const Value *V) {
564
if (const Argument *FA = dyn_cast<Argument>(V))
565
return new SlotTracker(FA->getParent());
567
if (const Instruction *I = dyn_cast<Instruction>(V))
568
return new SlotTracker(I->getParent()->getParent());
570
if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
571
return new SlotTracker(BB->getParent());
573
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
574
return new SlotTracker(GV->getParent());
576
if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
577
return new SlotTracker(GA->getParent());
579
if (const Function *Func = dyn_cast<Function>(V))
580
return new SlotTracker(Func);
583
return new SlotTracker((Function *)0);
589
#define ST_DEBUG(X) dbgs() << X
594
// Module level constructor. Causes the contents of the Module (sans functions)
595
// to be added to the slot table.
596
SlotTracker::SlotTracker(const Module *M)
597
: TheModule(M), TheFunction(0), FunctionProcessed(false),
598
mNext(0), fNext(0), mdnNext(0) {
601
// Function level constructor. Causes the contents of the Module and the one
602
// function provided to be added to the slot table.
603
SlotTracker::SlotTracker(const Function *F)
604
: TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
605
mNext(0), fNext(0), mdnNext(0) {
608
inline void SlotTracker::initialize() {
611
TheModule = 0; ///< Prevent re-processing next time we're called.
614
if (TheFunction && !FunctionProcessed)
618
// Iterate through all the global variables, functions, and global
619
// variable initializers and create slots for them.
620
void SlotTracker::processModule() {
621
ST_DEBUG("begin processModule!\n");
623
// Add all of the unnamed global variables to the value table.
624
for (Module::const_global_iterator I = TheModule->global_begin(),
625
E = TheModule->global_end(); I != E; ++I) {
630
// Add metadata used by named metadata.
631
for (Module::const_named_metadata_iterator
632
I = TheModule->named_metadata_begin(),
633
E = TheModule->named_metadata_end(); I != E; ++I) {
634
const NamedMDNode *NMD = I;
635
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
636
if (MDNode *MD = NMD->getOperand(i))
637
CreateMetadataSlot(MD);
641
// Add all the unnamed functions to the table.
642
for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
647
ST_DEBUG("end processModule!\n");
650
// Process the arguments, basic blocks, and instructions of a function.
651
void SlotTracker::processFunction() {
652
ST_DEBUG("begin processFunction!\n");
655
// Add all the function arguments with no names.
656
for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
657
AE = TheFunction->arg_end(); AI != AE; ++AI)
659
CreateFunctionSlot(AI);
661
ST_DEBUG("Inserting Instructions:\n");
663
SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
665
// Add all of the basic blocks and instructions with no names.
666
for (Function::const_iterator BB = TheFunction->begin(),
667
E = TheFunction->end(); BB != E; ++BB) {
669
CreateFunctionSlot(BB);
671
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
673
if (!I->getType()->isVoidTy() && !I->hasName())
674
CreateFunctionSlot(I);
676
// Intrinsics can directly use metadata.
677
if (isa<IntrinsicInst>(I))
678
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
679
if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
680
CreateMetadataSlot(N);
682
// Process metadata attached with this instruction.
683
I->getAllMetadata(MDForInst);
684
for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
685
CreateMetadataSlot(MDForInst[i].second);
690
FunctionProcessed = true;
692
ST_DEBUG("end processFunction!\n");
695
/// Clean up after incorporating a function. This is the only way to get out of
696
/// the function incorporation state that affects get*Slot/Create*Slot. Function
697
/// incorporation state is indicated by TheFunction != 0.
698
void SlotTracker::purgeFunction() {
699
ST_DEBUG("begin purgeFunction!\n");
700
fMap.clear(); // Simply discard the function level map
702
FunctionProcessed = false;
703
ST_DEBUG("end purgeFunction!\n");
706
/// getGlobalSlot - Get the slot number of a global value.
707
int SlotTracker::getGlobalSlot(const GlobalValue *V) {
708
// Check for uninitialized state and do lazy initialization.
711
// Find the type plane in the module map
712
ValueMap::iterator MI = mMap.find(V);
713
return MI == mMap.end() ? -1 : (int)MI->second;
716
/// getMetadataSlot - Get the slot number of a MDNode.
717
int SlotTracker::getMetadataSlot(const MDNode *N) {
718
// Check for uninitialized state and do lazy initialization.
721
// Find the type plane in the module map
722
mdn_iterator MI = mdnMap.find(N);
723
return MI == mdnMap.end() ? -1 : (int)MI->second;
727
/// getLocalSlot - Get the slot number for a value that is local to a function.
728
int SlotTracker::getLocalSlot(const Value *V) {
729
assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
731
// Check for uninitialized state and do lazy initialization.
734
ValueMap::iterator FI = fMap.find(V);
735
return FI == fMap.end() ? -1 : (int)FI->second;
739
/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
740
void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
741
assert(V && "Can't insert a null Value into SlotTracker!");
742
assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
743
assert(!V->hasName() && "Doesn't need a slot!");
745
unsigned DestSlot = mNext++;
748
ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
750
// G = Global, F = Function, A = Alias, o = other
751
ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
752
(isa<Function>(V) ? 'F' :
753
(isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
756
/// CreateSlot - Create a new slot for the specified value if it has no name.
757
void SlotTracker::CreateFunctionSlot(const Value *V) {
758
assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
760
unsigned DestSlot = fNext++;
763
// G = Global, F = Function, o = other
764
ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
765
DestSlot << " [o]\n");
768
/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
769
void SlotTracker::CreateMetadataSlot(const MDNode *N) {
770
assert(N && "Can't insert a null Value into SlotTracker!");
772
// Don't insert if N is a function-local metadata, these are always printed
774
if (N->isFunctionLocal())
777
mdn_iterator I = mdnMap.find(N);
778
if (I != mdnMap.end())
781
unsigned DestSlot = mdnNext++;
782
mdnMap[N] = DestSlot;
784
// Recursively add any MDNodes referenced by operands.
785
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
786
if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
787
CreateMetadataSlot(Op);
790
//===----------------------------------------------------------------------===//
791
// AsmWriter Implementation
792
//===----------------------------------------------------------------------===//
794
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
795
TypePrinting *TypePrinter,
796
SlotTracker *Machine);
800
static const char *getPredicateText(unsigned predicate) {
801
const char * pred = "unknown";
803
case FCmpInst::FCMP_FALSE: pred = "false"; break;
804
case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
805
case FCmpInst::FCMP_OGT: pred = "ogt"; break;
806
case FCmpInst::FCMP_OGE: pred = "oge"; break;
807
case FCmpInst::FCMP_OLT: pred = "olt"; break;
808
case FCmpInst::FCMP_OLE: pred = "ole"; break;
809
case FCmpInst::FCMP_ONE: pred = "one"; break;
810
case FCmpInst::FCMP_ORD: pred = "ord"; break;
811
case FCmpInst::FCMP_UNO: pred = "uno"; break;
812
case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
813
case FCmpInst::FCMP_UGT: pred = "ugt"; break;
814
case FCmpInst::FCMP_UGE: pred = "uge"; break;
815
case FCmpInst::FCMP_ULT: pred = "ult"; break;
816
case FCmpInst::FCMP_ULE: pred = "ule"; break;
817
case FCmpInst::FCMP_UNE: pred = "une"; break;
818
case FCmpInst::FCMP_TRUE: pred = "true"; break;
819
case ICmpInst::ICMP_EQ: pred = "eq"; break;
820
case ICmpInst::ICMP_NE: pred = "ne"; break;
821
case ICmpInst::ICMP_SGT: pred = "sgt"; break;
822
case ICmpInst::ICMP_SGE: pred = "sge"; break;
823
case ICmpInst::ICMP_SLT: pred = "slt"; break;
824
case ICmpInst::ICMP_SLE: pred = "sle"; break;
825
case ICmpInst::ICMP_UGT: pred = "ugt"; break;
826
case ICmpInst::ICMP_UGE: pred = "uge"; break;
827
case ICmpInst::ICMP_ULT: pred = "ult"; break;
828
case ICmpInst::ICMP_ULE: pred = "ule"; break;
834
static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
835
if (const OverflowingBinaryOperator *OBO =
836
dyn_cast<OverflowingBinaryOperator>(U)) {
837
if (OBO->hasNoUnsignedWrap())
839
if (OBO->hasNoSignedWrap())
841
} else if (const SDivOperator *Div = dyn_cast<SDivOperator>(U)) {
844
} else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
845
if (GEP->isInBounds())
850
static void WriteConstantInt(raw_ostream &Out, const Constant *CV,
851
TypePrinting &TypePrinter, SlotTracker *Machine) {
852
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
853
if (CI->getType()->isIntegerTy(1)) {
854
Out << (CI->getZExtValue() ? "true" : "false");
857
Out << CI->getValue();
861
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
862
if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
863
&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
864
// We would like to output the FP constant value in exponential notation,
865
// but we cannot do this if doing so will lose precision. Check here to
866
// make sure that we only output it in exponential format if we can parse
867
// the value back and get the same value.
870
bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
871
double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
872
CFP->getValueAPF().convertToFloat();
873
SmallString<128> StrVal;
874
raw_svector_ostream(StrVal) << Val;
876
// Check to make sure that the stringized number is not some string like
877
// "Inf" or NaN, that atof will accept, but the lexer will not. Check
878
// that the string matches the "[-+]?[0-9]" regex.
880
if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
881
((StrVal[0] == '-' || StrVal[0] == '+') &&
882
(StrVal[1] >= '0' && StrVal[1] <= '9'))) {
883
// Reparse stringized version!
884
if (atof(StrVal.c_str()) == Val) {
889
// Otherwise we could not reparse it to exactly the same value, so we must
890
// output the string in hexadecimal format! Note that loading and storing
891
// floating point types changes the bits of NaNs on some hosts, notably
892
// x86, so we must not use these types.
893
assert(sizeof(double) == sizeof(uint64_t) &&
894
"assuming that double is 64 bits!");
896
APFloat apf = CFP->getValueAPF();
897
// Floats are represented in ASCII IR as double, convert.
899
apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
902
utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
907
// Some form of long double. These appear as a magic letter identifying
908
// the type, then a fixed number of hex digits.
910
if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
912
// api needed to prevent premature destruction
913
APInt api = CFP->getValueAPF().bitcastToAPInt();
914
const uint64_t* p = api.getRawData();
915
uint64_t word = p[1];
917
int width = api.getBitWidth();
918
for (int j=0; j<width; j+=4, shiftcount-=4) {
919
unsigned int nibble = (word>>shiftcount) & 15;
921
Out << (unsigned char)(nibble + '0');
923
Out << (unsigned char)(nibble - 10 + 'A');
924
if (shiftcount == 0 && j+4 < width) {
928
shiftcount = width-j-4;
932
} else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
934
else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
937
llvm_unreachable("Unsupported floating point type");
938
// api needed to prevent premature destruction
939
APInt api = CFP->getValueAPF().bitcastToAPInt();
940
const uint64_t* p = api.getRawData();
943
int width = api.getBitWidth();
944
for (int j=0; j<width; j+=4, shiftcount-=4) {
945
unsigned int nibble = (word>>shiftcount) & 15;
947
Out << (unsigned char)(nibble + '0');
949
Out << (unsigned char)(nibble - 10 + 'A');
950
if (shiftcount == 0 && j+4 < width) {
954
shiftcount = width-j-4;
960
if (isa<ConstantAggregateZero>(CV)) {
961
Out << "zeroinitializer";
965
if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
966
Out << "blockaddress(";
967
WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine);
969
WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine);
974
if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
975
// As a special case, print the array as a string if it is an array of
976
// i8 with ConstantInt values.
978
const Type *ETy = CA->getType()->getElementType();
979
if (CA->isString()) {
981
PrintEscapedString(CA->getAsString(), Out);
983
} else { // Cannot output in string format...
985
if (CA->getNumOperands()) {
986
TypePrinter.print(ETy, Out);
988
WriteAsOperandInternal(Out, CA->getOperand(0),
989
&TypePrinter, Machine);
990
for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
992
TypePrinter.print(ETy, Out);
994
WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine);
1002
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1003
if (CS->getType()->isPacked())
1006
unsigned N = CS->getNumOperands();
1009
TypePrinter.print(CS->getOperand(0)->getType(), Out);
1012
WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine);
1014
for (unsigned i = 1; i < N; i++) {
1016
TypePrinter.print(CS->getOperand(i)->getType(), Out);
1019
WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine);
1025
if (CS->getType()->isPacked())
1030
if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
1031
const Type *ETy = CP->getType()->getElementType();
1032
assert(CP->getNumOperands() > 0 &&
1033
"Number of operands for a PackedConst must be > 0");
1035
TypePrinter.print(ETy, Out);
1037
WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine);
1038
for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
1040
TypePrinter.print(ETy, Out);
1042
WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine);
1048
if (isa<ConstantPointerNull>(CV)) {
1053
if (isa<UndefValue>(CV)) {
1058
if (const MDNode *Node = dyn_cast<MDNode>(CV)) {
1059
Out << "!" << Machine->getMetadataSlot(Node);
1063
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1064
Out << CE->getOpcodeName();
1065
WriteOptimizationInfo(Out, CE);
1066
if (CE->isCompare())
1067
Out << ' ' << getPredicateText(CE->getPredicate());
1070
for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1071
TypePrinter.print((*OI)->getType(), Out);
1073
WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine);
1074
if (OI+1 != CE->op_end())
1078
if (CE->hasIndices()) {
1079
const SmallVector<unsigned, 4> &Indices = CE->getIndices();
1080
for (unsigned i = 0, e = Indices.size(); i != e; ++i)
1081
Out << ", " << Indices[i];
1086
TypePrinter.print(CE->getType(), Out);
1093
Out << "<placeholder or erroneous Constant>";
1096
static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
1097
TypePrinting *TypePrinter,
1098
SlotTracker *Machine) {
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);
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) {
1126
PrintLLVMName(Out, V);
1130
const Constant *CV = dyn_cast<Constant>(V);
1131
if (CV && !isa<GlobalValue>(CV)) {
1132
assert(TypePrinter && "Constants require TypePrinting!");
1133
WriteConstantInt(Out, CV, *TypePrinter, Machine);
1137
if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1139
if (IA->hasSideEffects())
1140
Out << "sideeffect ";
1141
if (IA->isAlignStack())
1142
Out << "alignstack ";
1144
PrintEscapedString(IA->getAsmString(), Out);
1146
PrintEscapedString(IA->getConstraintString(), Out);
1151
if (const MDNode *N = dyn_cast<MDNode>(V)) {
1152
if (N->isFunctionLocal()) {
1153
// Print metadata inline, not via slot reference number.
1154
WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine);
1159
Machine = createSlotTracker(V);
1160
Out << '!' << Machine->getMetadataSlot(N);
1164
if (const MDString *MDS = dyn_cast<MDString>(V)) {
1166
PrintEscapedString(MDS->getString(), Out);
1171
if (V->getValueID() == Value::PseudoSourceValueVal ||
1172
V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1180
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1181
Slot = Machine->getGlobalSlot(GV);
1184
Slot = Machine->getLocalSlot(V);
1187
Machine = createSlotTracker(V);
1189
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1190
Slot = Machine->getGlobalSlot(GV);
1193
Slot = Machine->getLocalSlot(V);
1202
Out << Prefix << Slot;
1207
void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1208
bool PrintType, const Module *Context) {
1210
// Fast path: Don't construct and populate a TypePrinting object if we
1211
// won't be needing any types printed.
1213
(!isa<Constant>(V) || V->hasName() || isa<GlobalValue>(V))) {
1214
WriteAsOperandInternal(Out, V, 0, 0);
1218
if (Context == 0) Context = getModuleFromVal(V);
1220
TypePrinting TypePrinter;
1221
std::vector<const Type*> NumberedTypes;
1222
AddModuleTypesToPrinter(TypePrinter, NumberedTypes, Context);
1224
TypePrinter.print(V->getType(), Out);
1228
WriteAsOperandInternal(Out, V, &TypePrinter, 0);
1233
class AssemblyWriter {
1234
formatted_raw_ostream &Out;
1235
SlotTracker &Machine;
1236
const Module *TheModule;
1237
TypePrinting TypePrinter;
1238
AssemblyAnnotationWriter *AnnotationWriter;
1239
std::vector<const Type*> NumberedTypes;
1242
inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1244
AssemblyAnnotationWriter *AAW)
1245
: Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1246
AddModuleTypesToPrinter(TypePrinter, NumberedTypes, M);
1249
void printMDNodeBody(const MDNode *MD);
1250
void printNamedMDNode(const NamedMDNode *NMD);
1252
void printModule(const Module *M);
1254
void writeOperand(const Value *Op, bool PrintType);
1255
void writeParamOperand(const Value *Operand, Attributes Attrs);
1257
void writeAllMDNodes();
1259
void printTypeSymbolTable(const TypeSymbolTable &ST);
1260
void printGlobal(const GlobalVariable *GV);
1261
void printAlias(const GlobalAlias *GV);
1262
void printFunction(const Function *F);
1263
void printArgument(const Argument *FA, Attributes Attrs);
1264
void printBasicBlock(const BasicBlock *BB);
1265
void printInstruction(const Instruction &I);
1268
// printInfoComment - Print a little comment after the instruction indicating
1269
// which slot it occupies.
1270
void printInfoComment(const Value &V);
1272
} // end of anonymous namespace
1274
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1276
Out << "<null operand!>";
1280
TypePrinter.print(Operand->getType(), Out);
1283
WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1286
void AssemblyWriter::writeParamOperand(const Value *Operand,
1289
Out << "<null operand!>";
1294
TypePrinter.print(Operand->getType(), Out);
1295
// Print parameter attributes list
1296
if (Attrs != Attribute::None)
1297
Out << ' ' << Attribute::getAsString(Attrs);
1299
// Print the operand
1300
WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine);
1303
void AssemblyWriter::printModule(const Module *M) {
1304
if (!M->getModuleIdentifier().empty() &&
1305
// Don't print the ID if it will start a new line (which would
1306
// require a comment char before it).
1307
M->getModuleIdentifier().find('\n') == std::string::npos)
1308
Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1310
if (!M->getDataLayout().empty())
1311
Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1312
if (!M->getTargetTriple().empty())
1313
Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1315
if (!M->getModuleInlineAsm().empty()) {
1316
// Split the string into lines, to make it easier to read the .ll file.
1317
std::string Asm = M->getModuleInlineAsm();
1319
size_t NewLine = Asm.find_first_of('\n', CurPos);
1321
while (NewLine != std::string::npos) {
1322
// We found a newline, print the portion of the asm string from the
1323
// last newline up to this newline.
1324
Out << "module asm \"";
1325
PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1329
NewLine = Asm.find_first_of('\n', CurPos);
1331
Out << "module asm \"";
1332
PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
1336
// Loop over the dependent libraries and emit them.
1337
Module::lib_iterator LI = M->lib_begin();
1338
Module::lib_iterator LE = M->lib_end();
1341
Out << "deplibs = [ ";
1343
Out << '"' << *LI << '"';
1351
// Loop over the symbol table, emitting all id'd types.
1352
if (!M->getTypeSymbolTable().empty() || !NumberedTypes.empty()) Out << '\n';
1353
printTypeSymbolTable(M->getTypeSymbolTable());
1355
// Output all globals.
1356
if (!M->global_empty()) Out << '\n';
1357
for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1361
// Output all aliases.
1362
if (!M->alias_empty()) Out << "\n";
1363
for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1367
// Output all of the functions.
1368
for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1371
// Output named metadata.
1372
if (!M->named_metadata_empty()) Out << '\n';
1374
for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1375
E = M->named_metadata_end(); I != E; ++I)
1376
printNamedMDNode(I);
1379
if (!Machine.mdn_empty()) {
1385
void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1386
Out << "!" << NMD->getName() << " = !{";
1387
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1389
if (MDNode *MD = NMD->getOperand(i))
1390
Out << '!' << Machine.getMetadataSlot(MD);
1398
static void PrintLinkage(GlobalValue::LinkageTypes LT,
1399
formatted_raw_ostream &Out) {
1401
case GlobalValue::ExternalLinkage: break;
1402
case GlobalValue::PrivateLinkage: Out << "private "; break;
1403
case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1404
case GlobalValue::InternalLinkage: Out << "internal "; break;
1405
case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1406
case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1407
case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1408
case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1409
case GlobalValue::CommonLinkage: Out << "common "; break;
1410
case GlobalValue::AppendingLinkage: Out << "appending "; break;
1411
case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1412
case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1413
case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1414
case GlobalValue::AvailableExternallyLinkage:
1415
Out << "available_externally ";
1421
static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1422
formatted_raw_ostream &Out) {
1424
case GlobalValue::DefaultVisibility: break;
1425
case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1426
case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1430
void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1431
if (GV->isMaterializable())
1432
Out << "; Materializable\n";
1434
WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine);
1437
if (!GV->hasInitializer() && GV->hasExternalLinkage())
1440
PrintLinkage(GV->getLinkage(), Out);
1441
PrintVisibility(GV->getVisibility(), Out);
1443
if (GV->isThreadLocal()) Out << "thread_local ";
1444
if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1445
Out << "addrspace(" << AddressSpace << ") ";
1446
Out << (GV->isConstant() ? "constant " : "global ");
1447
TypePrinter.print(GV->getType()->getElementType(), Out);
1449
if (GV->hasInitializer()) {
1451
writeOperand(GV->getInitializer(), false);
1454
if (GV->hasSection())
1455
Out << ", section \"" << GV->getSection() << '"';
1456
if (GV->getAlignment())
1457
Out << ", align " << GV->getAlignment();
1459
printInfoComment(*GV);
1463
void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1464
if (GA->isMaterializable())
1465
Out << "; Materializable\n";
1467
// Don't crash when dumping partially built GA
1469
Out << "<<nameless>> = ";
1471
PrintLLVMName(Out, GA);
1474
PrintVisibility(GA->getVisibility(), Out);
1478
PrintLinkage(GA->getLinkage(), Out);
1480
const Constant *Aliasee = GA->getAliasee();
1482
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
1483
TypePrinter.print(GV->getType(), Out);
1485
PrintLLVMName(Out, GV);
1486
} else if (const Function *F = dyn_cast<Function>(Aliasee)) {
1487
TypePrinter.print(F->getFunctionType(), Out);
1490
WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1491
} else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
1492
TypePrinter.print(GA->getType(), Out);
1494
PrintLLVMName(Out, GA);
1496
const ConstantExpr *CE = cast<ConstantExpr>(Aliasee);
1497
// The only valid GEP is an all zero GEP.
1498
assert((CE->getOpcode() == Instruction::BitCast ||
1499
CE->getOpcode() == Instruction::GetElementPtr) &&
1500
"Unsupported aliasee");
1501
writeOperand(CE, false);
1504
printInfoComment(*GA);
1508
void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1509
// Emit all numbered types.
1510
for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1511
Out << '%' << i << " = type ";
1513
// Make sure we print out at least one level of the type structure, so
1514
// that we do not get %2 = type %2
1515
TypePrinter.printAtLeastOneLevel(NumberedTypes[i], Out);
1519
// Print the named types.
1520
for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1522
PrintLLVMName(Out, TI->first, LocalPrefix);
1525
// Make sure we print out at least one level of the type structure, so
1526
// that we do not get %FILE = type %FILE
1527
TypePrinter.printAtLeastOneLevel(TI->second, Out);
1532
/// printFunction - Print all aspects of a function.
1534
void AssemblyWriter::printFunction(const Function *F) {
1535
// Print out the return type and name.
1538
if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1540
if (F->isMaterializable())
1541
Out << "; Materializable\n";
1543
if (F->isDeclaration())
1548
PrintLinkage(F->getLinkage(), Out);
1549
PrintVisibility(F->getVisibility(), Out);
1551
// Print the calling convention.
1552
switch (F->getCallingConv()) {
1553
case CallingConv::C: break; // default
1554
case CallingConv::Fast: Out << "fastcc "; break;
1555
case CallingConv::Cold: Out << "coldcc "; break;
1556
case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1557
case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1558
case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1559
case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1560
case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1561
case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1562
default: Out << "cc" << F->getCallingConv() << " "; break;
1565
const FunctionType *FT = F->getFunctionType();
1566
const AttrListPtr &Attrs = F->getAttributes();
1567
Attributes RetAttrs = Attrs.getRetAttributes();
1568
if (RetAttrs != Attribute::None)
1569
Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1570
TypePrinter.print(F->getReturnType(), Out);
1572
WriteAsOperandInternal(Out, F, &TypePrinter, &Machine);
1574
Machine.incorporateFunction(F);
1576
// Loop over the arguments, printing them...
1579
if (!F->isDeclaration()) {
1580
// If this isn't a declaration, print the argument names as well.
1581
for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1583
// Insert commas as we go... the first arg doesn't get a comma
1584
if (I != F->arg_begin()) Out << ", ";
1585
printArgument(I, Attrs.getParamAttributes(Idx));
1589
// Otherwise, print the types from the function type.
1590
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1591
// Insert commas as we go... the first arg doesn't get a comma
1595
TypePrinter.print(FT->getParamType(i), Out);
1597
Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1598
if (ArgAttrs != Attribute::None)
1599
Out << ' ' << Attribute::getAsString(ArgAttrs);
1603
// Finish printing arguments...
1604
if (FT->isVarArg()) {
1605
if (FT->getNumParams()) Out << ", ";
1606
Out << "..."; // Output varargs portion of signature!
1609
Attributes FnAttrs = Attrs.getFnAttributes();
1610
if (FnAttrs != Attribute::None)
1611
Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1612
if (F->hasSection())
1613
Out << " section \"" << F->getSection() << '"';
1614
if (F->getAlignment())
1615
Out << " align " << F->getAlignment();
1617
Out << " gc \"" << F->getGC() << '"';
1618
if (F->isDeclaration()) {
1623
// Output all of its basic blocks... for the function
1624
for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1630
Machine.purgeFunction();
1633
/// printArgument - This member is called for every argument that is passed into
1634
/// the function. Simply print it out
1636
void AssemblyWriter::printArgument(const Argument *Arg,
1639
TypePrinter.print(Arg->getType(), Out);
1641
// Output parameter attributes list
1642
if (Attrs != Attribute::None)
1643
Out << ' ' << Attribute::getAsString(Attrs);
1645
// Output name, if available...
1646
if (Arg->hasName()) {
1648
PrintLLVMName(Out, Arg);
1652
/// printBasicBlock - This member is called for each basic block in a method.
1654
void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1655
if (BB->hasName()) { // Print out the label if it exists...
1657
PrintLLVMName(Out, BB->getName(), LabelPrefix);
1659
} else if (!BB->use_empty()) { // Don't print block # of no uses...
1660
Out << "\n; <label>:";
1661
int Slot = Machine.getLocalSlot(BB);
1668
if (BB->getParent() == 0) {
1669
Out.PadToColumn(50);
1670
Out << "; Error: Block without parent!";
1671
} else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1672
// Output predecessors for the block...
1673
Out.PadToColumn(50);
1675
pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1678
Out << " No predecessors!";
1681
writeOperand(*PI, false);
1682
for (++PI; PI != PE; ++PI) {
1684
writeOperand(*PI, false);
1691
if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1693
// Output all of the instructions in the basic block...
1694
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1695
printInstruction(*I);
1699
if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1702
/// printInfoComment - Print a little comment after the instruction indicating
1703
/// which slot it occupies.
1705
void AssemblyWriter::printInfoComment(const Value &V) {
1706
if (AnnotationWriter) {
1707
AnnotationWriter->printInfoComment(V, Out);
1711
if (V.getType()->isVoidTy()) return;
1713
Out.PadToColumn(50);
1715
TypePrinter.print(V.getType(), Out);
1716
Out << "> [#uses=" << V.getNumUses() << ']'; // Output # uses
1719
// This member is called for each Instruction in a function..
1720
void AssemblyWriter::printInstruction(const Instruction &I) {
1721
if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1723
// Print out indentation for an instruction.
1726
// Print out name if it exists...
1728
PrintLLVMName(Out, &I);
1730
} else if (!I.getType()->isVoidTy()) {
1731
// Print out the def slot taken.
1732
int SlotNum = Machine.getLocalSlot(&I);
1734
Out << "<badref> = ";
1736
Out << '%' << SlotNum << " = ";
1739
// If this is a volatile load or store, print out the volatile marker.
1740
if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1741
(isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1743
} else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1744
// If this is a call, check if it's a tail call.
1748
// Print out the opcode...
1749
Out << I.getOpcodeName();
1751
// Print out optimization information.
1752
WriteOptimizationInfo(Out, &I);
1754
// Print out the compare instruction predicates
1755
if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1756
Out << ' ' << getPredicateText(CI->getPredicate());
1758
// Print out the type of the operands...
1759
const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1761
// Special case conditional branches to swizzle the condition out to the front
1762
if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1763
BranchInst &BI(cast<BranchInst>(I));
1765
writeOperand(BI.getCondition(), true);
1767
writeOperand(BI.getSuccessor(0), true);
1769
writeOperand(BI.getSuccessor(1), true);
1771
} else if (isa<SwitchInst>(I)) {
1772
// Special case switch instruction to get formatting nice and correct.
1774
writeOperand(Operand , true);
1776
writeOperand(I.getOperand(1), true);
1779
for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1781
writeOperand(I.getOperand(op ), true);
1783
writeOperand(I.getOperand(op+1), true);
1786
} else if (isa<IndirectBrInst>(I)) {
1787
// Special case indirectbr instruction to get formatting nice and correct.
1789
writeOperand(Operand, true);
1792
for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1795
writeOperand(I.getOperand(i), true);
1798
} else if (isa<PHINode>(I)) {
1800
TypePrinter.print(I.getType(), Out);
1803
for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1804
if (op) Out << ", ";
1806
writeOperand(I.getOperand(op ), false); Out << ", ";
1807
writeOperand(I.getOperand(op+1), false); Out << " ]";
1809
} else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1811
writeOperand(I.getOperand(0), true);
1812
for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1814
} else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1816
writeOperand(I.getOperand(0), true); Out << ", ";
1817
writeOperand(I.getOperand(1), true);
1818
for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1820
} else if (isa<ReturnInst>(I) && !Operand) {
1822
} else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1823
// Print the calling convention being used.
1824
switch (CI->getCallingConv()) {
1825
case CallingConv::C: break; // default
1826
case CallingConv::Fast: Out << " fastcc"; break;
1827
case CallingConv::Cold: Out << " coldcc"; break;
1828
case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1829
case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1830
case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1831
case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1832
case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1833
case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1834
default: Out << " cc" << CI->getCallingConv(); break;
1837
const PointerType *PTy = cast<PointerType>(Operand->getType());
1838
const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1839
const Type *RetTy = FTy->getReturnType();
1840
const AttrListPtr &PAL = CI->getAttributes();
1842
if (PAL.getRetAttributes() != Attribute::None)
1843
Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1845
// If possible, print out the short form of the call instruction. We can
1846
// only do this if the first argument is a pointer to a nonvararg function,
1847
// and if the return type is not a pointer to a function.
1850
if (!FTy->isVarArg() &&
1851
(!RetTy->isPointerTy() ||
1852
!cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1853
TypePrinter.print(RetTy, Out);
1855
writeOperand(Operand, false);
1857
writeOperand(Operand, true);
1860
for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1863
writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op));
1866
if (PAL.getFnAttributes() != Attribute::None)
1867
Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1868
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1869
const PointerType *PTy = cast<PointerType>(Operand->getType());
1870
const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1871
const Type *RetTy = FTy->getReturnType();
1872
const AttrListPtr &PAL = II->getAttributes();
1874
// Print the calling convention being used.
1875
switch (II->getCallingConv()) {
1876
case CallingConv::C: break; // default
1877
case CallingConv::Fast: Out << " fastcc"; break;
1878
case CallingConv::Cold: Out << " coldcc"; break;
1879
case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1880
case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1881
case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1882
case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1883
case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1884
case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1885
default: Out << " cc" << II->getCallingConv(); break;
1888
if (PAL.getRetAttributes() != Attribute::None)
1889
Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1891
// If possible, print out the short form of the invoke instruction. We can
1892
// only do this if the first argument is a pointer to a nonvararg function,
1893
// and if the return type is not a pointer to a function.
1896
if (!FTy->isVarArg() &&
1897
(!RetTy->isPointerTy() ||
1898
!cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1899
TypePrinter.print(RetTy, Out);
1901
writeOperand(Operand, false);
1903
writeOperand(Operand, true);
1906
for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1909
writeParamOperand(I.getOperand(op), PAL.getParamAttributes(op-2));
1913
if (PAL.getFnAttributes() != Attribute::None)
1914
Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1917
writeOperand(II->getNormalDest(), true);
1919
writeOperand(II->getUnwindDest(), true);
1921
} else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1923
TypePrinter.print(AI->getType()->getElementType(), Out);
1924
if (!AI->getArraySize() || AI->isArrayAllocation()) {
1926
writeOperand(AI->getArraySize(), true);
1928
if (AI->getAlignment()) {
1929
Out << ", align " << AI->getAlignment();
1931
} else if (isa<CastInst>(I)) {
1934
writeOperand(Operand, true); // Work with broken code
1937
TypePrinter.print(I.getType(), Out);
1938
} else if (isa<VAArgInst>(I)) {
1941
writeOperand(Operand, true); // Work with broken code
1944
TypePrinter.print(I.getType(), Out);
1945
} else if (Operand) { // Print the normal way.
1947
// PrintAllTypes - Instructions who have operands of all the same type
1948
// omit the type from all but the first operand. If the instruction has
1949
// different type operands (for example br), then they are all printed.
1950
bool PrintAllTypes = false;
1951
const Type *TheType = Operand->getType();
1953
// Select, Store and ShuffleVector always print all types.
1954
if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1955
|| isa<ReturnInst>(I)) {
1956
PrintAllTypes = true;
1958
for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1959
Operand = I.getOperand(i);
1960
// note that Operand shouldn't be null, but the test helps make dump()
1961
// more tolerant of malformed IR
1962
if (Operand && Operand->getType() != TheType) {
1963
PrintAllTypes = true; // We have differing types! Print them all!
1969
if (!PrintAllTypes) {
1971
TypePrinter.print(TheType, Out);
1975
for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1977
writeOperand(I.getOperand(i), PrintAllTypes);
1981
// Print post operand alignment for load/store.
1982
if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1983
Out << ", align " << cast<LoadInst>(I).getAlignment();
1984
} else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1985
Out << ", align " << cast<StoreInst>(I).getAlignment();
1988
// Print Metadata info.
1989
SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1990
I.getAllMetadata(InstMD);
1991
if (!InstMD.empty()) {
1992
SmallVector<StringRef, 8> MDNames;
1993
I.getType()->getContext().getMDKindNames(MDNames);
1994
for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1995
unsigned Kind = InstMD[i].first;
1996
if (Kind < MDNames.size()) {
1997
Out << ", !" << MDNames[Kind];
1999
Out << ", !<unknown kind #" << Kind << ">";
2001
Out << " !" << Machine.getMetadataSlot(InstMD[i].second);
2004
printInfoComment(I);
2007
static void WriteMDNodeComment(const MDNode *Node,
2008
formatted_raw_ostream &Out) {
2009
if (Node->getNumOperands() < 1)
2011
ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
2013
unsigned Val = CI->getZExtValue();
2014
unsigned Tag = Val & ~LLVMDebugVersionMask;
2015
if (Val < LLVMDebugVersion)
2018
Out.PadToColumn(50);
2019
if (Tag == dwarf::DW_TAG_auto_variable)
2020
Out << "; [ DW_TAG_auto_variable ]";
2021
else if (Tag == dwarf::DW_TAG_arg_variable)
2022
Out << "; [ DW_TAG_arg_variable ]";
2023
else if (Tag == dwarf::DW_TAG_return_variable)
2024
Out << "; [ DW_TAG_return_variable ]";
2025
else if (Tag == dwarf::DW_TAG_vector_type)
2026
Out << "; [ DW_TAG_vector_type ]";
2027
else if (Tag == dwarf::DW_TAG_user_base)
2028
Out << "; [ DW_TAG_user_base ]";
2029
else if (const char *TagName = dwarf::TagString(Tag))
2030
Out << "; [ " << TagName << " ]";
2033
void AssemblyWriter::writeAllMDNodes() {
2034
SmallVector<const MDNode *, 16> Nodes;
2035
Nodes.resize(Machine.mdn_size());
2036
for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2038
Nodes[I->second] = cast<MDNode>(I->first);
2040
for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2041
Out << '!' << i << " = metadata ";
2042
printMDNodeBody(Nodes[i]);
2046
void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2047
WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine);
2048
WriteMDNodeComment(Node, Out);
2052
//===----------------------------------------------------------------------===//
2053
// External Interface declarations
2054
//===----------------------------------------------------------------------===//
2056
void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2057
SlotTracker SlotTable(this);
2058
formatted_raw_ostream OS(ROS);
2059
AssemblyWriter W(OS, SlotTable, this, AAW);
2060
W.printModule(this);
2063
void Type::print(raw_ostream &OS) const {
2065
OS << "<null Type>";
2068
TypePrinting().print(this, OS);
2071
void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2073
ROS << "printing a <null> value\n";
2076
formatted_raw_ostream OS(ROS);
2077
if (const Instruction *I = dyn_cast<Instruction>(this)) {
2078
const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2079
SlotTracker SlotTable(F);
2080
AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2081
W.printInstruction(*I);
2082
} else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2083
SlotTracker SlotTable(BB->getParent());
2084
AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2085
W.printBasicBlock(BB);
2086
} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2087
SlotTracker SlotTable(GV->getParent());
2088
AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2089
if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2091
else if (const Function *F = dyn_cast<Function>(GV))
2094
W.printAlias(cast<GlobalAlias>(GV));
2095
} else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2096
const Function *F = N->getFunction();
2097
SlotTracker SlotTable(F);
2098
AssemblyWriter W(OS, SlotTable, F ? getModuleFromVal(F) : 0, AAW);
2099
W.printMDNodeBody(N);
2100
} else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(this)) {
2101
SlotTracker SlotTable(N->getParent());
2102
AssemblyWriter W(OS, SlotTable, N->getParent(), AAW);
2103
W.printNamedMDNode(N);
2104
} else if (const Constant *C = dyn_cast<Constant>(this)) {
2105
TypePrinting TypePrinter;
2106
TypePrinter.print(C->getType(), OS);
2108
WriteConstantInt(OS, C, TypePrinter, 0);
2109
} else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2110
isa<Argument>(this)) {
2111
WriteAsOperand(OS, this, true, 0);
2113
// Otherwise we don't know what it is. Call the virtual function to
2114
// allow a subclass to print itself.
2119
// Value::printCustom - subclasses should override this to implement printing.
2120
void Value::printCustom(raw_ostream &OS) const {
2121
llvm_unreachable("Unknown value to print out!");
2124
// Value::dump - allow easy printing of Values from the debugger.
2125
void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2127
// Type::dump - allow easy printing of Types from the debugger.
2128
// This one uses type names from the given context module
2129
void Type::dump(const Module *Context) const {
2130
WriteTypeSymbolic(dbgs(), this, Context);
2134
// Type::dump - allow easy printing of Types from the debugger.
2135
void Type::dump() const { dump(0); }
2137
// Module::dump() - Allow printing of Modules from the debugger.
2138
void Module::dump() const { print(dbgs(), 0); }