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/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Module.h"
27 #include "llvm/ValueSymbolTable.h"
28 #include "llvm/TypeSymbolTable.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Streams.h"
34 #include "llvm/Support/raw_ostream.h"
41 // Make virtual table appear in this compilation unit.
42 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
44 /// This class provides computation of slot numbers for LLVM Assembly writing.
48 /// ValueMap - A mapping of Values to slot numbers
49 typedef std::map<const Value*, unsigned> ValueMap;
52 /// TheModule - The module for which we are holding slot numbers
53 const Module* TheModule;
55 /// TheFunction - The function for which we are holding slot numbers
56 const Function* TheFunction;
57 bool FunctionProcessed;
59 /// mMap - The TypePlanes map for the module level data
63 /// fMap - The TypePlanes map for the function level data
68 /// Construct from a module
69 explicit SlotMachine(const Module *M);
70 /// Construct from a function, starting out in incorp state.
71 explicit SlotMachine(const Function *F);
73 /// Return the slot number of the specified value in it's type
74 /// plane. If something is not in the SlotMachine, return -1.
75 int getLocalSlot(const Value *V);
76 int getGlobalSlot(const GlobalValue *V);
78 /// If you'd like to deal with a function instead of just a module, use
79 /// this method to get its data into the SlotMachine.
80 void incorporateFunction(const Function *F) {
82 FunctionProcessed = false;
85 /// After calling incorporateFunction, use this method to remove the
86 /// most recently incorporated function from the SlotMachine. This
87 /// will reset the state of the machine back to just the module contents.
90 // Implementation Details
92 /// This function does the actual initialization.
93 inline void initialize();
95 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
96 void CreateModuleSlot(const GlobalValue *V);
98 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
99 void CreateFunctionSlot(const Value *V);
101 /// Add all of the module level global variables (and their initializers)
102 /// and function declarations, but not the contents of those functions.
103 void processModule();
105 /// Add all of the functions arguments, basic blocks, and instructions
106 void processFunction();
108 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
109 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
112 } // end namespace llvm
114 char PrintModulePass::ID = 0;
115 static RegisterPass<PrintModulePass>
116 X("printm", "Print module to stderr");
117 char PrintFunctionPass::ID = 0;
118 static RegisterPass<PrintFunctionPass>
119 Y("print","Print function to stderr");
121 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
122 std::map<const Type *, std::string> &TypeTable,
123 SlotMachine *Machine);
125 static const Module *getModuleFromVal(const Value *V) {
126 if (const Argument *MA = dyn_cast<Argument>(V))
127 return MA->getParent() ? MA->getParent()->getParent() : 0;
128 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
129 return BB->getParent() ? BB->getParent()->getParent() : 0;
130 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
131 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
132 return M ? M->getParent() : 0;
133 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
134 return GV->getParent();
138 static SlotMachine *createSlotMachine(const Value *V) {
139 if (const Argument *FA = dyn_cast<Argument>(V)) {
140 return new SlotMachine(FA->getParent());
141 } else if (const Instruction *I = dyn_cast<Instruction>(V)) {
142 return new SlotMachine(I->getParent()->getParent());
143 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
144 return new SlotMachine(BB->getParent());
145 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
146 return new SlotMachine(GV->getParent());
147 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)){
148 return new SlotMachine(GA->getParent());
149 } else if (const Function *Func = dyn_cast<Function>(V)) {
150 return new SlotMachine(Func);
155 /// NameNeedsQuotes - Return true if the specified llvm name should be wrapped
157 static std::string QuoteNameIfNeeded(const std::string &Name) {
159 bool needsQuotes = Name[0] >= '0' && Name[0] <= '9';
160 // Scan the name to see if it needs quotes and to replace funky chars with
161 // their octal equivalent.
162 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
164 assert(C != '"' && "Illegal character in LLVM value name!");
165 if (isalnum(C) || C == '-' || C == '.' || C == '_')
167 else if (C == '\\') {
170 } else if (isprint(C)) {
176 char hex1 = (C >> 4) & 0x0F;
178 result += hex1 + '0';
180 result += hex1 - 10 + 'A';
181 char hex2 = C & 0x0F;
183 result += hex2 + '0';
185 result += hex2 - 10 + 'A';
189 result.insert(0,"\"");
201 /// getLLVMName - Turn the specified string into an 'LLVM name', which is either
202 /// prefixed with % (if the string only contains simple characters) or is
203 /// surrounded with ""'s (if it has special chars in it).
204 static std::string getLLVMName(const std::string &Name, PrefixType Prefix) {
205 assert(!Name.empty() && "Cannot get empty name!");
207 default: assert(0 && "Bad prefix!");
208 case GlobalPrefix: return '@' + QuoteNameIfNeeded(Name);
209 case LabelPrefix: return QuoteNameIfNeeded(Name);
210 case LocalPrefix: return '%' + QuoteNameIfNeeded(Name);
215 /// fillTypeNameTable - If the module has a symbol table, take all global types
216 /// and stuff their names into the TypeNames map.
218 static void fillTypeNameTable(const Module *M,
219 std::map<const Type *, std::string> &TypeNames) {
221 const TypeSymbolTable &ST = M->getTypeSymbolTable();
222 TypeSymbolTable::const_iterator TI = ST.begin();
223 for (; TI != ST.end(); ++TI) {
224 // As a heuristic, don't insert pointer to primitive types, because
225 // they are used too often to have a single useful name.
227 const Type *Ty = cast<Type>(TI->second);
228 if (!isa<PointerType>(Ty) ||
229 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
230 !cast<PointerType>(Ty)->getElementType()->isInteger() ||
231 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
232 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first, LocalPrefix)));
238 static void calcTypeName(const Type *Ty,
239 std::vector<const Type *> &TypeStack,
240 std::map<const Type *, std::string> &TypeNames,
241 std::string & Result){
242 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))) {
243 Result += Ty->getDescription(); // Base case
247 // Check to see if the type is named.
248 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
249 if (I != TypeNames.end()) {
254 if (isa<OpaqueType>(Ty)) {
259 // Check to see if the Type is already on the stack...
260 unsigned Slot = 0, CurSize = TypeStack.size();
261 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
263 // This is another base case for the recursion. In this case, we know
264 // that we have looped back to a type that we have previously visited.
265 // Generate the appropriate upreference to handle this.
266 if (Slot < CurSize) {
267 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
271 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
273 switch (Ty->getTypeID()) {
274 case Type::IntegerTyID: {
275 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
276 Result += "i" + utostr(BitWidth);
279 case Type::FunctionTyID: {
280 const FunctionType *FTy = cast<FunctionType>(Ty);
281 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
283 for (FunctionType::param_iterator I = FTy->param_begin(),
284 E = FTy->param_end(); I != E; ++I) {
285 if (I != FTy->param_begin())
287 calcTypeName(*I, TypeStack, TypeNames, Result);
289 if (FTy->isVarArg()) {
290 if (FTy->getNumParams()) Result += ", ";
296 case Type::StructTyID: {
297 const StructType *STy = cast<StructType>(Ty);
301 for (StructType::element_iterator I = STy->element_begin(),
302 E = STy->element_end(); I != E; ++I) {
303 if (I != STy->element_begin())
305 calcTypeName(*I, TypeStack, TypeNames, Result);
312 case Type::PointerTyID: {
313 const PointerType *PTy = cast<PointerType>(Ty);
314 calcTypeName(PTy->getElementType(),
315 TypeStack, TypeNames, Result);
316 if (unsigned AddressSpace = PTy->getAddressSpace())
317 Result += " addrspace(" + utostr(AddressSpace) + ")";
321 case Type::ArrayTyID: {
322 const ArrayType *ATy = cast<ArrayType>(Ty);
323 Result += "[" + utostr(ATy->getNumElements()) + " x ";
324 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
328 case Type::VectorTyID: {
329 const VectorType *PTy = cast<VectorType>(Ty);
330 Result += "<" + utostr(PTy->getNumElements()) + " x ";
331 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
335 case Type::OpaqueTyID:
339 Result += "<unrecognized-type>";
343 TypeStack.pop_back(); // Remove self from stack...
347 /// printTypeInt - The internal guts of printing out a type that has a
348 /// potentially named portion.
350 static std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,
351 std::map<const Type *, std::string> &TypeNames) {
352 // Primitive types always print out their description, regardless of whether
353 // they have been named or not.
355 if (Ty->isInteger() || (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)))
356 return Out << Ty->getDescription();
358 // Check to see if the type is named.
359 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
360 if (I != TypeNames.end()) return Out << I->second;
362 // Otherwise we have a type that has not been named but is a derived type.
363 // Carefully recurse the type hierarchy to print out any contained symbolic
366 std::vector<const Type *> TypeStack;
367 std::string TypeName;
368 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
369 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
370 return (Out << TypeName);
374 /// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
375 /// type, iff there is an entry in the modules symbol table for the specified
376 /// type or one of it's component types. This is slower than a simple x << Type
378 std::ostream &llvm::WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
382 // If they want us to print out a type, but there is no context, we can't
383 // print it symbolically.
385 return Out << Ty->getDescription();
387 std::map<const Type *, std::string> TypeNames;
388 fillTypeNameTable(M, TypeNames);
389 return printTypeInt(Out, Ty, TypeNames);
392 // PrintEscapedString - Print each character of the specified string, escaping
393 // it if it is not printable or if it is an escape char.
394 static void PrintEscapedString(const std::string &Str, std::ostream &Out) {
395 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
396 unsigned char C = Str[i];
397 if (isprint(C) && C != '"' && C != '\\') {
401 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
402 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
407 static const char *getPredicateText(unsigned predicate) {
408 const char * pred = "unknown";
410 case FCmpInst::FCMP_FALSE: pred = "false"; break;
411 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
412 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
413 case FCmpInst::FCMP_OGE: pred = "oge"; break;
414 case FCmpInst::FCMP_OLT: pred = "olt"; break;
415 case FCmpInst::FCMP_OLE: pred = "ole"; break;
416 case FCmpInst::FCMP_ONE: pred = "one"; break;
417 case FCmpInst::FCMP_ORD: pred = "ord"; break;
418 case FCmpInst::FCMP_UNO: pred = "uno"; break;
419 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
420 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
421 case FCmpInst::FCMP_UGE: pred = "uge"; break;
422 case FCmpInst::FCMP_ULT: pred = "ult"; break;
423 case FCmpInst::FCMP_ULE: pred = "ule"; break;
424 case FCmpInst::FCMP_UNE: pred = "une"; break;
425 case FCmpInst::FCMP_TRUE: pred = "true"; break;
426 case ICmpInst::ICMP_EQ: pred = "eq"; break;
427 case ICmpInst::ICMP_NE: pred = "ne"; break;
428 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
429 case ICmpInst::ICMP_SGE: pred = "sge"; break;
430 case ICmpInst::ICMP_SLT: pred = "slt"; break;
431 case ICmpInst::ICMP_SLE: pred = "sle"; break;
432 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
433 case ICmpInst::ICMP_UGE: pred = "uge"; break;
434 case ICmpInst::ICMP_ULT: pred = "ult"; break;
435 case ICmpInst::ICMP_ULE: pred = "ule"; break;
440 static void WriteConstantInt(std::ostream &Out, const Constant *CV,
441 std::map<const Type *, std::string> &TypeTable,
442 SlotMachine *Machine) {
443 const int IndentSize = 4;
444 static std::string Indent = "\n";
445 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
446 if (CI->getType() == Type::Int1Ty)
447 Out << (CI->getZExtValue() ? "true" : "false");
449 Out << CI->getValue().toStringSigned(10);
450 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
451 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
452 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
453 // We would like to output the FP constant value in exponential notation,
454 // but we cannot do this if doing so will lose precision. Check here to
455 // make sure that we only output it in exponential format if we can parse
456 // the value back and get the same value.
458 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
459 double Val = (isDouble) ? CFP->getValueAPF().convertToDouble() :
460 CFP->getValueAPF().convertToFloat();
461 std::string StrVal = ftostr(CFP->getValueAPF());
463 // Check to make sure that the stringized number is not some string like
464 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
465 // that the string matches the "[-+]?[0-9]" regex.
467 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
468 ((StrVal[0] == '-' || StrVal[0] == '+') &&
469 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
470 // Reparse stringized version!
471 if (atof(StrVal.c_str()) == Val) {
476 // Otherwise we could not reparse it to exactly the same value, so we must
477 // output the string in hexadecimal format!
478 assert(sizeof(double) == sizeof(uint64_t) &&
479 "assuming that double is 64 bits!");
480 Out << "0x" << utohexstr(DoubleToBits(Val));
482 // Some form of long double. These appear as a magic letter identifying
483 // the type, then a fixed number of hex digits.
485 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended)
487 else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
489 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
492 assert(0 && "Unsupported floating point type");
493 // api needed to prevent premature destruction
494 APInt api = CFP->getValueAPF().convertToAPInt();
495 const uint64_t* p = api.getRawData();
498 int width = api.getBitWidth();
499 for (int j=0; j<width; j+=4, shiftcount-=4) {
500 unsigned int nibble = (word>>shiftcount) & 15;
502 Out << (unsigned char)(nibble + '0');
504 Out << (unsigned char)(nibble - 10 + 'A');
505 if (shiftcount == 0 && j+4 < width) {
509 shiftcount = width-j-4;
513 } else if (isa<ConstantAggregateZero>(CV)) {
514 Out << "zeroinitializer";
515 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
516 // As a special case, print the array as a string if it is an array of
517 // i8 with ConstantInt values.
519 const Type *ETy = CA->getType()->getElementType();
520 if (CA->isString()) {
522 PrintEscapedString(CA->getAsString(), Out);
525 } else { // Cannot output in string format...
527 if (CA->getNumOperands()) {
529 printTypeInt(Out, ETy, TypeTable);
530 WriteAsOperandInternal(Out, CA->getOperand(0),
532 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
534 printTypeInt(Out, ETy, TypeTable);
535 WriteAsOperandInternal(Out, CA->getOperand(i), TypeTable, Machine);
540 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
541 if (CS->getType()->isPacked())
544 unsigned N = CS->getNumOperands();
547 Indent += std::string(IndentSize, ' ');
552 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
554 WriteAsOperandInternal(Out, CS->getOperand(0), TypeTable, Machine);
556 for (unsigned i = 1; i < N; i++) {
558 if (N > 2) Out << Indent;
559 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
561 WriteAsOperandInternal(Out, CS->getOperand(i), TypeTable, Machine);
563 if (N > 2) Indent.resize(Indent.size() - IndentSize);
567 if (CS->getType()->isPacked())
569 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
570 const Type *ETy = CP->getType()->getElementType();
571 assert(CP->getNumOperands() > 0 &&
572 "Number of operands for a PackedConst must be > 0");
575 printTypeInt(Out, ETy, TypeTable);
576 WriteAsOperandInternal(Out, CP->getOperand(0), TypeTable, Machine);
577 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
579 printTypeInt(Out, ETy, TypeTable);
580 WriteAsOperandInternal(Out, CP->getOperand(i), TypeTable, Machine);
583 } else if (isa<ConstantPointerNull>(CV)) {
586 } else if (isa<UndefValue>(CV)) {
589 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
590 Out << CE->getOpcodeName();
592 Out << " " << getPredicateText(CE->getPredicate());
595 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
596 printTypeInt(Out, (*OI)->getType(), TypeTable);
597 WriteAsOperandInternal(Out, *OI, TypeTable, Machine);
598 if (OI+1 != CE->op_end())
602 if (CE->hasIndices()) {
603 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
604 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
605 Out << ", " << Indices[i];
610 printTypeInt(Out, CE->getType(), TypeTable);
616 Out << "<placeholder or erroneous Constant>";
621 /// WriteAsOperand - Write the name of the specified value out to the specified
622 /// ostream. This can be useful when you just want to print int %reg126, not
623 /// the whole instruction that generated it.
625 static void WriteAsOperandInternal(std::ostream &Out, const Value *V,
626 std::map<const Type*, std::string> &TypeTable,
627 SlotMachine *Machine) {
630 Out << getLLVMName(V->getName(),
631 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
633 const Constant *CV = dyn_cast<Constant>(V);
634 if (CV && !isa<GlobalValue>(CV)) {
635 WriteConstantInt(Out, CV, TypeTable, Machine);
636 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
638 if (IA->hasSideEffects())
639 Out << "sideeffect ";
641 PrintEscapedString(IA->getAsmString(), Out);
643 PrintEscapedString(IA->getConstraintString(), Out);
649 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
650 Slot = Machine->getGlobalSlot(GV);
653 Slot = Machine->getLocalSlot(V);
656 Machine = createSlotMachine(V);
658 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
659 Slot = Machine->getGlobalSlot(GV);
662 Slot = Machine->getLocalSlot(V);
670 Out << Prefix << Slot;
677 /// WriteAsOperand - Write the name of the specified value out to the specified
678 /// ostream. This can be useful when you just want to print int %reg126, not
679 /// the whole instruction that generated it.
681 std::ostream &llvm::WriteAsOperand(std::ostream &Out, const Value *V,
682 bool PrintType, const Module *Context) {
683 std::map<const Type *, std::string> TypeNames;
684 if (Context == 0) Context = getModuleFromVal(V);
687 fillTypeNameTable(Context, TypeNames);
690 printTypeInt(Out, V->getType(), TypeNames);
692 WriteAsOperandInternal(Out, V, TypeNames, 0);
699 class AssemblyWriter {
701 SlotMachine &Machine;
702 const Module *TheModule;
703 std::map<const Type *, std::string> TypeNames;
704 AssemblyAnnotationWriter *AnnotationWriter;
706 inline AssemblyWriter(std::ostream &o, SlotMachine &Mac, const Module *M,
707 AssemblyAnnotationWriter *AAW)
708 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
710 // If the module has a symbol table, take all global types and stuff their
711 // names into the TypeNames map.
713 fillTypeNameTable(M, TypeNames);
716 inline void write(const Module *M) { printModule(M); }
717 inline void write(const GlobalVariable *G) { printGlobal(G); }
718 inline void write(const GlobalAlias *G) { printAlias(G); }
719 inline void write(const Function *F) { printFunction(F); }
720 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
721 inline void write(const Instruction *I) { printInstruction(*I); }
722 inline void write(const Type *Ty) { printType(Ty); }
724 void writeOperand(const Value *Op, bool PrintType);
725 void writeParamOperand(const Value *Operand, ParameterAttributes Attrs);
727 const Module* getModule() { return TheModule; }
730 void printModule(const Module *M);
731 void printTypeSymbolTable(const TypeSymbolTable &ST);
732 void printGlobal(const GlobalVariable *GV);
733 void printAlias(const GlobalAlias *GV);
734 void printFunction(const Function *F);
735 void printArgument(const Argument *FA, ParameterAttributes Attrs);
736 void printBasicBlock(const BasicBlock *BB);
737 void printInstruction(const Instruction &I);
739 // printType - Go to extreme measures to attempt to print out a short,
740 // symbolic version of a type name.
742 std::ostream &printType(const Type *Ty) {
743 return printTypeInt(Out, Ty, TypeNames);
746 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
747 // without considering any symbolic types that we may have equal to it.
749 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
751 // printInfoComment - Print a little comment after the instruction indicating
752 // which slot it occupies.
753 void printInfoComment(const Value &V);
755 } // end of llvm namespace
757 /// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
758 /// without considering any symbolic types that we may have equal to it.
760 std::ostream &AssemblyWriter::printTypeAtLeastOneLevel(const Type *Ty) {
761 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
762 Out << "i" << utostr(ITy->getBitWidth());
763 else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
764 printType(FTy->getReturnType());
766 for (FunctionType::param_iterator I = FTy->param_begin(),
767 E = FTy->param_end(); I != E; ++I) {
768 if (I != FTy->param_begin())
772 if (FTy->isVarArg()) {
773 if (FTy->getNumParams()) Out << ", ";
777 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
781 for (StructType::element_iterator I = STy->element_begin(),
782 E = STy->element_end(); I != E; ++I) {
783 if (I != STy->element_begin())
790 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
791 printType(PTy->getElementType());
792 if (unsigned AddressSpace = PTy->getAddressSpace())
793 Out << " addrspace(" << AddressSpace << ")";
795 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
796 Out << '[' << ATy->getNumElements() << " x ";
797 printType(ATy->getElementType()) << ']';
798 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
799 Out << '<' << PTy->getNumElements() << " x ";
800 printType(PTy->getElementType()) << '>';
802 else if (isa<OpaqueType>(Ty)) {
805 if (!Ty->isPrimitiveType())
806 Out << "<unknown derived type>";
813 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
815 Out << "<null operand!>";
817 if (PrintType) { Out << ' '; printType(Operand->getType()); }
818 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
822 void AssemblyWriter::writeParamOperand(const Value *Operand,
823 ParameterAttributes Attrs) {
825 Out << "<null operand!>";
829 printType(Operand->getType());
830 // Print parameter attributes list
831 if (Attrs != ParamAttr::None)
832 Out << ' ' << ParamAttr::getAsString(Attrs);
834 WriteAsOperandInternal(Out, Operand, TypeNames, &Machine);
838 void AssemblyWriter::printModule(const Module *M) {
839 if (!M->getModuleIdentifier().empty() &&
840 // Don't print the ID if it will start a new line (which would
841 // require a comment char before it).
842 M->getModuleIdentifier().find('\n') == std::string::npos)
843 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
845 if (!M->getDataLayout().empty())
846 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
847 if (!M->getTargetTriple().empty())
848 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
850 if (!M->getModuleInlineAsm().empty()) {
851 // Split the string into lines, to make it easier to read the .ll file.
852 std::string Asm = M->getModuleInlineAsm();
854 size_t NewLine = Asm.find_first_of('\n', CurPos);
855 while (NewLine != std::string::npos) {
856 // We found a newline, print the portion of the asm string from the
857 // last newline up to this newline.
858 Out << "module asm \"";
859 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
863 NewLine = Asm.find_first_of('\n', CurPos);
865 Out << "module asm \"";
866 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
870 // Loop over the dependent libraries and emit them.
871 Module::lib_iterator LI = M->lib_begin();
872 Module::lib_iterator LE = M->lib_end();
874 Out << "deplibs = [ ";
876 Out << '"' << *LI << '"';
884 // Loop over the symbol table, emitting all named constants.
885 printTypeSymbolTable(M->getTypeSymbolTable());
887 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
891 // Output all aliases.
892 if (!M->alias_empty()) Out << "\n";
893 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
897 // Output all of the functions.
898 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
902 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
903 if (GV->hasName()) Out << getLLVMName(GV->getName(), GlobalPrefix) << " = ";
905 if (!GV->hasInitializer()) {
906 switch (GV->getLinkage()) {
907 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
908 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
909 default: Out << "external "; break;
912 switch (GV->getLinkage()) {
913 case GlobalValue::InternalLinkage: Out << "internal "; break;
914 case GlobalValue::CommonLinkage: Out << "common "; break;
915 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
916 case GlobalValue::WeakLinkage: Out << "weak "; break;
917 case GlobalValue::AppendingLinkage: Out << "appending "; break;
918 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
919 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
920 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
921 case GlobalValue::ExternalLinkage: break;
922 case GlobalValue::GhostLinkage:
923 cerr << "GhostLinkage not allowed in AsmWriter!\n";
926 switch (GV->getVisibility()) {
927 default: assert(0 && "Invalid visibility style!");
928 case GlobalValue::DefaultVisibility: break;
929 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
930 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
934 if (GV->isThreadLocal()) Out << "thread_local ";
935 Out << (GV->isConstant() ? "constant " : "global ");
936 printType(GV->getType()->getElementType());
938 if (GV->hasInitializer()) {
939 Constant* C = cast<Constant>(GV->getInitializer());
940 assert(C && "GlobalVar initializer isn't constant?");
941 writeOperand(GV->getInitializer(), false);
944 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
945 Out << " addrspace(" << AddressSpace << ") ";
947 if (GV->hasSection())
948 Out << ", section \"" << GV->getSection() << '"';
949 if (GV->getAlignment())
950 Out << ", align " << GV->getAlignment();
952 printInfoComment(*GV);
956 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
957 // Don't crash when dumping partially built GA
959 Out << "<<nameless>> = ";
961 Out << getLLVMName(GA->getName(), GlobalPrefix) << " = ";
962 switch (GA->getVisibility()) {
963 default: assert(0 && "Invalid visibility style!");
964 case GlobalValue::DefaultVisibility: break;
965 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
966 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
971 switch (GA->getLinkage()) {
972 case GlobalValue::WeakLinkage: Out << "weak "; break;
973 case GlobalValue::InternalLinkage: Out << "internal "; break;
974 case GlobalValue::ExternalLinkage: break;
976 assert(0 && "Invalid alias linkage");
979 const Constant *Aliasee = GA->getAliasee();
981 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Aliasee)) {
982 printType(GV->getType());
983 Out << " " << getLLVMName(GV->getName(), GlobalPrefix);
984 } else if (const Function *F = dyn_cast<Function>(Aliasee)) {
985 printType(F->getFunctionType());
988 if (!F->getName().empty())
989 Out << getLLVMName(F->getName(), GlobalPrefix);
992 } else if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(Aliasee)) {
993 printType(GA->getType());
994 Out << " " << getLLVMName(GA->getName(), GlobalPrefix);
996 const ConstantExpr *CE = 0;
997 if ((CE = dyn_cast<ConstantExpr>(Aliasee)) &&
998 (CE->getOpcode() == Instruction::BitCast)) {
999 writeOperand(CE, false);
1001 assert(0 && "Unsupported aliasee");
1004 printInfoComment(*GA);
1008 void AssemblyWriter::printTypeSymbolTable(const TypeSymbolTable &ST) {
1010 for (TypeSymbolTable::const_iterator TI = ST.begin(), TE = ST.end();
1012 Out << "\t" << getLLVMName(TI->first, LocalPrefix) << " = type ";
1014 // Make sure we print out at least one level of the type structure, so
1015 // that we do not get %FILE = type %FILE
1017 printTypeAtLeastOneLevel(TI->second) << "\n";
1021 /// printFunction - Print all aspects of a function.
1023 void AssemblyWriter::printFunction(const Function *F) {
1024 // Print out the return type and name...
1027 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1029 if (F->isDeclaration())
1034 switch (F->getLinkage()) {
1035 case GlobalValue::InternalLinkage: Out << "internal "; break;
1036 case GlobalValue::LinkOnceLinkage: Out << "linkonce "; break;
1037 case GlobalValue::WeakLinkage: Out << "weak "; break;
1038 case GlobalValue::CommonLinkage: Out << "common "; break;
1039 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1040 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1041 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1042 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1043 case GlobalValue::ExternalLinkage: break;
1044 case GlobalValue::GhostLinkage:
1045 cerr << "GhostLinkage not allowed in AsmWriter!\n";
1048 switch (F->getVisibility()) {
1049 default: assert(0 && "Invalid visibility style!");
1050 case GlobalValue::DefaultVisibility: break;
1051 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1052 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1055 // Print the calling convention.
1056 switch (F->getCallingConv()) {
1057 case CallingConv::C: break; // default
1058 case CallingConv::Fast: Out << "fastcc "; break;
1059 case CallingConv::Cold: Out << "coldcc "; break;
1060 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1061 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1062 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1063 default: Out << "cc" << F->getCallingConv() << " "; break;
1066 const FunctionType *FT = F->getFunctionType();
1067 const PAListPtr &Attrs = F->getParamAttrs();
1068 printType(F->getReturnType()) << ' ';
1069 if (!F->getName().empty())
1070 Out << getLLVMName(F->getName(), GlobalPrefix);
1074 Machine.incorporateFunction(F);
1076 // Loop over the arguments, printing them...
1079 if (!F->isDeclaration()) {
1080 // If this isn't a declaration, print the argument names as well.
1081 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1083 // Insert commas as we go... the first arg doesn't get a comma
1084 if (I != F->arg_begin()) Out << ", ";
1085 printArgument(I, Attrs.getParamAttrs(Idx));
1089 // Otherwise, print the types from the function type.
1090 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1091 // Insert commas as we go... the first arg doesn't get a comma
1095 printType(FT->getParamType(i));
1097 ParameterAttributes ArgAttrs = Attrs.getParamAttrs(i+1);
1098 if (ArgAttrs != ParamAttr::None)
1099 Out << ' ' << ParamAttr::getAsString(ArgAttrs);
1103 // Finish printing arguments...
1104 if (FT->isVarArg()) {
1105 if (FT->getNumParams()) Out << ", ";
1106 Out << "..."; // Output varargs portion of signature!
1109 ParameterAttributes RetAttrs = Attrs.getParamAttrs(0);
1110 if (RetAttrs != ParamAttr::None)
1111 Out << ' ' << ParamAttr::getAsString(Attrs.getParamAttrs(0));
1112 if (F->hasSection())
1113 Out << " section \"" << F->getSection() << '"';
1114 if (F->getAlignment())
1115 Out << " align " << F->getAlignment();
1116 if (F->hasCollector())
1117 Out << " gc \"" << F->getCollector() << '"';
1119 if (F->isDeclaration()) {
1124 // Output all of its basic blocks... for the function
1125 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1131 Machine.purgeFunction();
1134 /// printArgument - This member is called for every argument that is passed into
1135 /// the function. Simply print it out
1137 void AssemblyWriter::printArgument(const Argument *Arg,
1138 ParameterAttributes Attrs) {
1140 printType(Arg->getType());
1142 // Output parameter attributes list
1143 if (Attrs != ParamAttr::None)
1144 Out << ' ' << ParamAttr::getAsString(Attrs);
1146 // Output name, if available...
1148 Out << ' ' << getLLVMName(Arg->getName(), LocalPrefix);
1151 /// printBasicBlock - This member is called for each basic block in a method.
1153 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1154 if (BB->hasName()) { // Print out the label if it exists...
1155 Out << "\n" << getLLVMName(BB->getName(), LabelPrefix) << ':';
1156 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1157 Out << "\n; <label>:";
1158 int Slot = Machine.getLocalSlot(BB);
1165 if (BB->getParent() == 0)
1166 Out << "\t\t; Error: Block without parent!";
1167 else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1168 // Output predecessors for the block...
1170 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1173 Out << " No predecessors!";
1176 writeOperand(*PI, false);
1177 for (++PI; PI != PE; ++PI) {
1179 writeOperand(*PI, false);
1186 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1188 // Output all of the instructions in the basic block...
1189 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1190 printInstruction(*I);
1192 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1196 /// printInfoComment - Print a little comment after the instruction indicating
1197 /// which slot it occupies.
1199 void AssemblyWriter::printInfoComment(const Value &V) {
1200 if (V.getType() != Type::VoidTy) {
1202 printType(V.getType()) << '>';
1206 if (const GlobalValue *GV = dyn_cast<GlobalValue>(&V))
1207 SlotNum = Machine.getGlobalSlot(GV);
1209 SlotNum = Machine.getLocalSlot(&V);
1213 Out << ':' << SlotNum; // Print out the def slot taken.
1215 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1219 // This member is called for each Instruction in a function..
1220 void AssemblyWriter::printInstruction(const Instruction &I) {
1221 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1225 // Print out name if it exists...
1227 Out << getLLVMName(I.getName(), LocalPrefix) << " = ";
1229 // If this is a volatile load or store, print out the volatile marker.
1230 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1231 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1233 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1234 // If this is a call, check if it's a tail call.
1238 // Print out the opcode...
1239 Out << I.getOpcodeName();
1241 // Print out the compare instruction predicates
1242 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1243 Out << " " << getPredicateText(CI->getPredicate());
1245 // Print out the type of the operands...
1246 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1248 // Special case conditional branches to swizzle the condition out to the front
1249 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1250 writeOperand(I.getOperand(2), true);
1252 writeOperand(Operand, true);
1254 writeOperand(I.getOperand(1), true);
1256 } else if (isa<SwitchInst>(I)) {
1257 // Special case switch statement to get formatting nice and correct...
1258 writeOperand(Operand , true); Out << ',';
1259 writeOperand(I.getOperand(1), true); Out << " [";
1261 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1263 writeOperand(I.getOperand(op ), true); Out << ',';
1264 writeOperand(I.getOperand(op+1), true);
1267 } else if (isa<PHINode>(I)) {
1269 printType(I.getType());
1272 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1273 if (op) Out << ", ";
1275 writeOperand(I.getOperand(op ), false); Out << ',';
1276 writeOperand(I.getOperand(op+1), false); Out << " ]";
1278 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1279 writeOperand(I.getOperand(0), true);
1280 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1282 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1283 writeOperand(I.getOperand(0), true); Out << ',';
1284 writeOperand(I.getOperand(1), true);
1285 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1287 } else if (isa<ReturnInst>(I) && !Operand) {
1289 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1290 // Print the calling convention being used.
1291 switch (CI->getCallingConv()) {
1292 case CallingConv::C: break; // default
1293 case CallingConv::Fast: Out << " fastcc"; break;
1294 case CallingConv::Cold: Out << " coldcc"; break;
1295 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1296 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1297 case CallingConv::X86_SSECall: Out << " x86_ssecallcc"; break;
1298 default: Out << " cc" << CI->getCallingConv(); break;
1301 const PointerType *PTy = cast<PointerType>(Operand->getType());
1302 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1303 const Type *RetTy = FTy->getReturnType();
1304 const PAListPtr &PAL = CI->getParamAttrs();
1306 // If possible, print out the short form of the call instruction. We can
1307 // only do this if the first argument is a pointer to a nonvararg function,
1308 // and if the return type is not a pointer to a function.
1310 if (!FTy->isVarArg() &&
1311 (!isa<PointerType>(RetTy) ||
1312 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1313 Out << ' '; printType(RetTy);
1314 writeOperand(Operand, false);
1316 writeOperand(Operand, true);
1319 for (unsigned op = 1, Eop = I.getNumOperands(); op < Eop; ++op) {
1322 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op));
1325 if (PAL.getParamAttrs(0) != ParamAttr::None)
1326 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1327 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1328 const PointerType *PTy = cast<PointerType>(Operand->getType());
1329 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1330 const Type *RetTy = FTy->getReturnType();
1331 const PAListPtr &PAL = II->getParamAttrs();
1333 // Print the calling convention being used.
1334 switch (II->getCallingConv()) {
1335 case CallingConv::C: break; // default
1336 case CallingConv::Fast: Out << " fastcc"; break;
1337 case CallingConv::Cold: Out << " coldcc"; break;
1338 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1339 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1340 case CallingConv::X86_SSECall: Out << "x86_ssecallcc "; break;
1341 default: Out << " cc" << II->getCallingConv(); break;
1344 // If possible, print out the short form of the invoke instruction. We can
1345 // only do this if the first argument is a pointer to a nonvararg function,
1346 // and if the return type is not a pointer to a function.
1348 if (!FTy->isVarArg() &&
1349 (!isa<PointerType>(RetTy) ||
1350 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1351 Out << ' '; printType(RetTy);
1352 writeOperand(Operand, false);
1354 writeOperand(Operand, true);
1358 for (unsigned op = 3, Eop = I.getNumOperands(); op < Eop; ++op) {
1361 writeParamOperand(I.getOperand(op), PAL.getParamAttrs(op-2));
1365 if (PAL.getParamAttrs(0) != ParamAttr::None)
1366 Out << ' ' << ParamAttr::getAsString(PAL.getParamAttrs(0));
1367 Out << "\n\t\t\tto";
1368 writeOperand(II->getNormalDest(), true);
1370 writeOperand(II->getUnwindDest(), true);
1372 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1374 printType(AI->getType()->getElementType());
1375 if (AI->isArrayAllocation()) {
1377 writeOperand(AI->getArraySize(), true);
1379 if (AI->getAlignment()) {
1380 Out << ", align " << AI->getAlignment();
1382 } else if (isa<CastInst>(I)) {
1383 if (Operand) writeOperand(Operand, true); // Work with broken code
1385 printType(I.getType());
1386 } else if (isa<VAArgInst>(I)) {
1387 if (Operand) writeOperand(Operand, true); // Work with broken code
1389 printType(I.getType());
1390 } else if (Operand) { // Print the normal way...
1392 // PrintAllTypes - Instructions who have operands of all the same type
1393 // omit the type from all but the first operand. If the instruction has
1394 // different type operands (for example br), then they are all printed.
1395 bool PrintAllTypes = false;
1396 const Type *TheType = Operand->getType();
1398 // Select, Store and ShuffleVector always print all types.
1399 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1400 || isa<ReturnInst>(I)) {
1401 PrintAllTypes = true;
1403 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1404 Operand = I.getOperand(i);
1405 if (Operand->getType() != TheType) {
1406 PrintAllTypes = true; // We have differing types! Print them all!
1412 if (!PrintAllTypes) {
1417 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1419 writeOperand(I.getOperand(i), PrintAllTypes);
1423 // Print post operand alignment for load/store
1424 if (isa<LoadInst>(I) && cast<LoadInst>(I).getAlignment()) {
1425 Out << ", align " << cast<LoadInst>(I).getAlignment();
1426 } else if (isa<StoreInst>(I) && cast<StoreInst>(I).getAlignment()) {
1427 Out << ", align " << cast<StoreInst>(I).getAlignment();
1430 printInfoComment(I);
1435 //===----------------------------------------------------------------------===//
1436 // External Interface declarations
1437 //===----------------------------------------------------------------------===//
1439 void Module::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1440 SlotMachine SlotTable(this);
1441 AssemblyWriter W(o, SlotTable, this, AAW);
1445 void GlobalVariable::print(std::ostream &o) const {
1446 SlotMachine SlotTable(getParent());
1447 AssemblyWriter W(o, SlotTable, getParent(), 0);
1451 void GlobalAlias::print(std::ostream &o) const {
1452 SlotMachine SlotTable(getParent());
1453 AssemblyWriter W(o, SlotTable, getParent(), 0);
1457 void Function::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1458 SlotMachine SlotTable(getParent());
1459 AssemblyWriter W(o, SlotTable, getParent(), AAW);
1464 void InlineAsm::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1465 WriteAsOperand(o, this, true, 0);
1468 void BasicBlock::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1469 SlotMachine SlotTable(getParent());
1470 AssemblyWriter W(o, SlotTable,
1471 getParent() ? getParent()->getParent() : 0, AAW);
1475 void Instruction::print(std::ostream &o, AssemblyAnnotationWriter *AAW) const {
1476 const Function *F = getParent() ? getParent()->getParent() : 0;
1477 SlotMachine SlotTable(F);
1478 AssemblyWriter W(o, SlotTable, F ? F->getParent() : 0, AAW);
1483 void Constant::print(std::ostream &o) const {
1484 if (this == 0) { o << "<null> constant value\n"; return; }
1486 o << ' ' << getType()->getDescription() << ' ';
1488 std::map<const Type *, std::string> TypeTable;
1489 WriteConstantInt(o, this, TypeTable, 0);
1492 void Type::print(std::ostream &o) const {
1496 o << getDescription();
1499 void Argument::print(std::ostream &o) const {
1500 WriteAsOperand(o, this, true, getParent() ? getParent()->getParent() : 0);
1503 // Value::dump - allow easy printing of Values from the debugger.
1504 // Located here because so much of the needed functionality is here.
1505 void Value::dump() const { print(*cerr.stream()); cerr << '\n'; }
1507 // Type::dump - allow easy printing of Values from the debugger.
1508 // Located here because so much of the needed functionality is here.
1509 void Type::dump() const { print(*cerr.stream()); cerr << '\n'; }
1511 //===----------------------------------------------------------------------===//
1512 // SlotMachine Implementation
1513 //===----------------------------------------------------------------------===//
1516 #define SC_DEBUG(X) cerr << X
1521 // Module level constructor. Causes the contents of the Module (sans functions)
1522 // to be added to the slot table.
1523 SlotMachine::SlotMachine(const Module *M)
1524 : TheModule(M) ///< Saved for lazy initialization.
1526 , FunctionProcessed(false)
1527 , mNext(0), fMap(), fNext(0)
1531 // Function level constructor. Causes the contents of the Module and the one
1532 // function provided to be added to the slot table.
1533 SlotMachine::SlotMachine(const Function *F)
1534 : TheModule(F ? F->getParent() : 0) ///< Saved for lazy initialization
1535 , TheFunction(F) ///< Saved for lazy initialization
1536 , FunctionProcessed(false)
1537 , mNext(0), fMap(), fNext(0)
1541 inline void SlotMachine::initialize() {
1544 TheModule = 0; ///< Prevent re-processing next time we're called.
1546 if (TheFunction && !FunctionProcessed)
1550 // Iterate through all the global variables, functions, and global
1551 // variable initializers and create slots for them.
1552 void SlotMachine::processModule() {
1553 SC_DEBUG("begin processModule!\n");
1555 // Add all of the unnamed global variables to the value table.
1556 for (Module::const_global_iterator I = TheModule->global_begin(),
1557 E = TheModule->global_end(); I != E; ++I)
1559 CreateModuleSlot(I);
1561 // Add all the unnamed functions to the table.
1562 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
1565 CreateModuleSlot(I);
1567 SC_DEBUG("end processModule!\n");
1571 // Process the arguments, basic blocks, and instructions of a function.
1572 void SlotMachine::processFunction() {
1573 SC_DEBUG("begin processFunction!\n");
1576 // Add all the function arguments with no names.
1577 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
1578 AE = TheFunction->arg_end(); AI != AE; ++AI)
1580 CreateFunctionSlot(AI);
1582 SC_DEBUG("Inserting Instructions:\n");
1584 // Add all of the basic blocks and instructions with no names.
1585 for (Function::const_iterator BB = TheFunction->begin(),
1586 E = TheFunction->end(); BB != E; ++BB) {
1588 CreateFunctionSlot(BB);
1589 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1590 if (I->getType() != Type::VoidTy && !I->hasName())
1591 CreateFunctionSlot(I);
1594 FunctionProcessed = true;
1596 SC_DEBUG("end processFunction!\n");
1599 /// Clean up after incorporating a function. This is the only way to get out of
1600 /// the function incorporation state that affects get*Slot/Create*Slot. Function
1601 /// incorporation state is indicated by TheFunction != 0.
1602 void SlotMachine::purgeFunction() {
1603 SC_DEBUG("begin purgeFunction!\n");
1604 fMap.clear(); // Simply discard the function level map
1606 FunctionProcessed = false;
1607 SC_DEBUG("end purgeFunction!\n");
1610 /// getGlobalSlot - Get the slot number of a global value.
1611 int SlotMachine::getGlobalSlot(const GlobalValue *V) {
1612 // Check for uninitialized state and do lazy initialization.
1615 // Find the type plane in the module map
1616 ValueMap::const_iterator MI = mMap.find(V);
1617 if (MI == mMap.end()) return -1;
1623 /// getLocalSlot - Get the slot number for a value that is local to a function.
1624 int SlotMachine::getLocalSlot(const Value *V) {
1625 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
1627 // Check for uninitialized state and do lazy initialization.
1630 ValueMap::const_iterator FI = fMap.find(V);
1631 if (FI == fMap.end()) return -1;
1637 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
1638 void SlotMachine::CreateModuleSlot(const GlobalValue *V) {
1639 assert(V && "Can't insert a null Value into SlotMachine!");
1640 assert(V->getType() != Type::VoidTy && "Doesn't need a slot!");
1641 assert(!V->hasName() && "Doesn't need a slot!");
1643 unsigned DestSlot = mNext++;
1646 SC_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
1648 // G = Global, F = Function, A = Alias, o = other
1649 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' :
1650 (isa<Function>(V) ? 'F' :
1651 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
1655 /// CreateSlot - Create a new slot for the specified value if it has no name.
1656 void SlotMachine::CreateFunctionSlot(const Value *V) {
1657 const Type *VTy = V->getType();
1658 assert(VTy != Type::VoidTy && !V->hasName() && "Doesn't need a slot!");
1660 unsigned DestSlot = fNext++;
1663 // G = Global, F = Function, o = other
1664 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1665 DestSlot << " [o]\n");