rename method
[oota-llvm.git] / lib / CodeGen / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Module.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/Support/Mangler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include <iostream>
23 using namespace llvm;
24
25 AsmPrinter::AsmPrinter(std::ostream &o, TargetMachine &tm)
26 : FunctionNumber(0), O(o), TM(tm),
27   CommentString("#"),
28   GlobalPrefix(""),
29   PrivateGlobalPrefix("."),
30   GlobalVarAddrPrefix(""),
31   GlobalVarAddrSuffix(""),
32   FunctionAddrPrefix(""),
33   FunctionAddrSuffix(""),
34   ZeroDirective("\t.zero\t"),
35   AsciiDirective("\t.ascii\t"),
36   AscizDirective("\t.asciz\t"),
37   Data8bitsDirective("\t.byte\t"),
38   Data16bitsDirective("\t.short\t"),
39   Data32bitsDirective("\t.long\t"),
40   Data64bitsDirective("\t.quad\t"),
41   AlignDirective("\t.align\t"),
42   AlignmentIsInBytes(true),
43   SwitchToSectionDirective("\t.section\t"),
44   ConstantPoolSection("\t.section .rodata\n"),
45   StaticCtorsSection("\t.section .ctors,\"aw\",@progbits"),
46   StaticDtorsSection("\t.section .dtors,\"aw\",@progbits"),
47   LCOMMDirective(0),
48   COMMDirective("\t.comm\t"),
49   COMMDirectiveTakesAlignment(true),
50   HasDotTypeDotSizeDirective(true) {
51 }
52
53
54 /// SwitchSection - Switch to the specified section of the executable if we
55 /// are not already in it!
56 ///
57 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
58   std::string NS;
59   
60   if (GV && GV->hasSection())
61     NS = SwitchToSectionDirective + GV->getSection();
62   else
63     NS = std::string("\t")+NewSection;
64   
65   if (CurrentSection != NS) {
66     CurrentSection = NS;
67     if (!CurrentSection.empty())
68       O << CurrentSection << '\n';
69   }
70 }
71
72 bool AsmPrinter::doInitialization(Module &M) {
73   Mang = new Mangler(M, GlobalPrefix);
74   
75   if (!M.getModuleInlineAsm().empty())
76     O << CommentString << " Start of file scope inline assembly\n"
77       << M.getModuleInlineAsm()
78       << "\n" << CommentString << " End of file scope inline assembly\n";
79
80   SwitchSection("", 0);   // Reset back to no section.
81   return false;
82 }
83
84 bool AsmPrinter::doFinalization(Module &M) {
85   delete Mang; Mang = 0;
86   return false;
87 }
88
89 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
90   // What's my mangled name?
91   CurrentFnName = Mang->getValueName(MF.getFunction());
92   IncrementFunctionNumber();
93 }
94
95 /// EmitConstantPool - Print to the current output stream assembly
96 /// representations of the constants in the constant pool MCP. This is
97 /// used to print out constants which have been "spilled to memory" by
98 /// the code generator.
99 ///
100 void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) {
101   const std::vector<Constant*> &CP = MCP->getConstants();
102   if (CP.empty()) return;
103   const TargetData &TD = TM.getTargetData();
104   
105   SwitchSection(ConstantPoolSection, 0);
106   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
107     // FIXME: force doubles to be naturally aligned.  We should handle this
108     // more correctly in the future.
109     unsigned Alignment = TD.getTypeAlignmentShift(CP[i]->getType());
110     if (CP[i]->getType() == Type::DoubleTy && Alignment < 3) Alignment = 3;
111     
112     EmitAlignment(Alignment);
113     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << '_' << i
114       << ":\t\t\t\t\t" << CommentString << *CP[i] << '\n';
115     EmitGlobalConstant(CP[i]);
116   }
117 }
118
119 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
120 /// special global used by LLVM.  If so, emit it and return true, otherwise
121 /// do nothing and return false.
122 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
123   assert(GV->hasInitializer() && GV->hasAppendingLinkage() &&
124          "Not a special LLVM global!");
125   
126   if (GV->getName() == "llvm.used")
127     return true;  // No need to emit this at all.
128
129   if (GV->getName() == "llvm.global_ctors" && GV->use_empty()) {
130     SwitchSection(StaticCtorsSection, 0);
131     EmitAlignment(2, 0);
132     EmitXXStructorList(GV->getInitializer());
133     return true;
134   } 
135   
136   if (GV->getName() == "llvm.global_dtors" && GV->use_empty()) {
137     SwitchSection(StaticDtorsSection, 0);
138     EmitAlignment(2, 0);
139     EmitXXStructorList(GV->getInitializer());
140     return true;
141   }
142   
143   return false;
144 }
145
146 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
147 /// function pointers, ignoring the init priority.
148 void AsmPrinter::EmitXXStructorList(Constant *List) {
149   // Should be an array of '{ int, void ()* }' structs.  The first value is the
150   // init priority, which we ignore.
151   if (!isa<ConstantArray>(List)) return;
152   ConstantArray *InitList = cast<ConstantArray>(List);
153   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
154     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
155       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
156
157       if (CS->getOperand(1)->isNullValue())
158         return;  // Found a null terminator, exit printing.
159       // Emit the function pointer.
160       EmitGlobalConstant(CS->getOperand(1));
161     }
162 }
163
164
165 // EmitAlignment - Emit an alignment directive to the specified power of two.
166 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
167   if (GV && GV->getAlignment())
168     NumBits = Log2_32(GV->getAlignment());
169   if (NumBits == 0) return;   // No need to emit alignment.
170   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
171   O << AlignDirective << NumBits << "\n";
172 }
173
174 /// EmitZeros - Emit a block of zeros.
175 ///
176 void AsmPrinter::EmitZeros(uint64_t NumZeros) const {
177   if (NumZeros) {
178     if (ZeroDirective)
179       O << ZeroDirective << NumZeros << "\n";
180     else {
181       for (; NumZeros; --NumZeros)
182         O << Data8bitsDirective << "0\n";
183     }
184   }
185 }
186
187 // Print out the specified constant, without a storage class.  Only the
188 // constants valid in constant expressions can occur here.
189 void AsmPrinter::EmitConstantValueOnly(const Constant *CV) {
190   if (CV->isNullValue() || isa<UndefValue>(CV))
191     O << "0";
192   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
193     assert(CB == ConstantBool::True);
194     O << "1";
195   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
196     if (((CI->getValue() << 32) >> 32) == CI->getValue())
197       O << CI->getValue();
198     else
199       O << (uint64_t)CI->getValue();
200   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
201     O << CI->getValue();
202   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
203     // This is a constant address for a global variable or function. Use the
204     // name of the variable or function as the address value, possibly
205     // decorating it with GlobalVarAddrPrefix/Suffix or
206     // FunctionAddrPrefix/Suffix (these all default to "" )
207     if (isa<Function>(GV))
208       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
209     else
210       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
211   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
212     const TargetData &TD = TM.getTargetData();
213     switch(CE->getOpcode()) {
214     case Instruction::GetElementPtr: {
215       // generate a symbolic expression for the byte address
216       const Constant *ptrVal = CE->getOperand(0);
217       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
218       if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
219         if (Offset)
220           O << "(";
221         EmitConstantValueOnly(ptrVal);
222         if (Offset > 0)
223           O << ") + " << Offset;
224         else if (Offset < 0)
225           O << ") - " << -Offset;
226       } else {
227         EmitConstantValueOnly(ptrVal);
228       }
229       break;
230     }
231     case Instruction::Cast: {
232       // Support only non-converting or widening casts for now, that is, ones
233       // that do not involve a change in value.  This assertion is really gross,
234       // and may not even be a complete check.
235       Constant *Op = CE->getOperand(0);
236       const Type *OpTy = Op->getType(), *Ty = CE->getType();
237
238       // Remember, kids, pointers can be losslessly converted back and forth
239       // into 32-bit or wider integers, regardless of signedness. :-P
240       assert(((isa<PointerType>(OpTy)
241                && (Ty == Type::LongTy || Ty == Type::ULongTy
242                    || Ty == Type::IntTy || Ty == Type::UIntTy))
243               || (isa<PointerType>(Ty)
244                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
245                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
246               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
247                    && OpTy->isLosslesslyConvertibleTo(Ty))))
248              && "FIXME: Don't yet support this kind of constant cast expr");
249       EmitConstantValueOnly(Op);
250       break;
251     }
252     case Instruction::Add:
253       O << "(";
254       EmitConstantValueOnly(CE->getOperand(0));
255       O << ") + (";
256       EmitConstantValueOnly(CE->getOperand(1));
257       O << ")";
258       break;
259     default:
260       assert(0 && "Unsupported operator!");
261     }
262   } else {
263     assert(0 && "Unknown constant value!");
264   }
265 }
266
267 /// toOctal - Convert the low order bits of X into an octal digit.
268 ///
269 static inline char toOctal(int X) {
270   return (X&7)+'0';
271 }
272
273 /// printAsCString - Print the specified array as a C compatible string, only if
274 /// the predicate isString is true.
275 ///
276 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
277                            unsigned LastElt) {
278   assert(CVA->isString() && "Array is not string compatible!");
279
280   O << "\"";
281   for (unsigned i = 0; i != LastElt; ++i) {
282     unsigned char C =
283         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
284
285     if (C == '"') {
286       O << "\\\"";
287     } else if (C == '\\') {
288       O << "\\\\";
289     } else if (isprint(C)) {
290       O << C;
291     } else {
292       switch(C) {
293       case '\b': O << "\\b"; break;
294       case '\f': O << "\\f"; break;
295       case '\n': O << "\\n"; break;
296       case '\r': O << "\\r"; break;
297       case '\t': O << "\\t"; break;
298       default:
299         O << '\\';
300         O << toOctal(C >> 6);
301         O << toOctal(C >> 3);
302         O << toOctal(C >> 0);
303         break;
304       }
305     }
306   }
307   O << "\"";
308 }
309
310 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
311 ///
312 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
313   const TargetData &TD = TM.getTargetData();
314
315   if (CV->isNullValue() || isa<UndefValue>(CV)) {
316     EmitZeros(TD.getTypeSize(CV->getType()));
317     return;
318   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
319     if (CVA->isString()) {
320       unsigned NumElts = CVA->getNumOperands();
321       if (AscizDirective && NumElts && 
322           cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
323         O << AscizDirective;
324         printAsCString(O, CVA, NumElts-1);
325       } else {
326         O << AsciiDirective;
327         printAsCString(O, CVA, NumElts);
328       }
329       O << "\n";
330     } else { // Not a string.  Print the values in successive locations
331       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
332         EmitGlobalConstant(CVA->getOperand(i));
333     }
334     return;
335   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
336     // Print the fields in successive locations. Pad to align if needed!
337     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
338     uint64_t sizeSoFar = 0;
339     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
340       const Constant* field = CVS->getOperand(i);
341
342       // Check if padding is needed and insert one or more 0s.
343       uint64_t fieldSize = TD.getTypeSize(field->getType());
344       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
345                            : cvsLayout->MemberOffsets[i+1])
346                           - cvsLayout->MemberOffsets[i]) - fieldSize;
347       sizeSoFar += fieldSize + padSize;
348
349       // Now print the actual field value
350       EmitGlobalConstant(field);
351
352       // Insert the field padding unless it's zero bytes...
353       EmitZeros(padSize);
354     }
355     assert(sizeSoFar == cvsLayout->StructSize &&
356            "Layout of constant struct may be incorrect!");
357     return;
358   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
359     // FP Constants are printed as integer constants to avoid losing
360     // precision...
361     double Val = CFP->getValue();
362     if (CFP->getType() == Type::DoubleTy) {
363       if (Data64bitsDirective)
364         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
365           << " double value: " << Val << "\n";
366       else if (TD.isBigEndian()) {
367         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
368           << "\t" << CommentString << " double most significant word "
369           << Val << "\n";
370         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
371           << "\t" << CommentString << " double least significant word "
372           << Val << "\n";
373       } else {
374         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
375           << "\t" << CommentString << " double least significant word " << Val
376           << "\n";
377         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
378           << "\t" << CommentString << " double most significant word " << Val
379           << "\n";
380       }
381       return;
382     } else {
383       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
384         << " float " << Val << "\n";
385       return;
386     }
387   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
388     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
389       uint64_t Val = CI->getRawValue();
390
391       if (Data64bitsDirective)
392         O << Data64bitsDirective << Val << "\n";
393       else if (TD.isBigEndian()) {
394         O << Data32bitsDirective << unsigned(Val >> 32)
395           << "\t" << CommentString << " Double-word most significant word "
396           << Val << "\n";
397         O << Data32bitsDirective << unsigned(Val)
398           << "\t" << CommentString << " Double-word least significant word "
399           << Val << "\n";
400       } else {
401         O << Data32bitsDirective << unsigned(Val)
402           << "\t" << CommentString << " Double-word least significant word "
403           << Val << "\n";
404         O << Data32bitsDirective << unsigned(Val >> 32)
405           << "\t" << CommentString << " Double-word most significant word "
406           << Val << "\n";
407       }
408       return;
409     }
410   } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
411     const PackedType *PTy = CP->getType();
412     
413     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
414       EmitGlobalConstant(CP->getOperand(I));
415     
416     return;
417   }
418
419   const Type *type = CV->getType();
420   switch (type->getTypeID()) {
421   case Type::BoolTyID:
422   case Type::UByteTyID: case Type::SByteTyID:
423     O << Data8bitsDirective;
424     break;
425   case Type::UShortTyID: case Type::ShortTyID:
426     O << Data16bitsDirective;
427     break;
428   case Type::PointerTyID:
429     if (TD.getPointerSize() == 8) {
430       O << Data64bitsDirective;
431       break;
432     }
433     //Fall through for pointer size == int size
434   case Type::UIntTyID: case Type::IntTyID:
435     O << Data32bitsDirective;
436     break;
437   case Type::ULongTyID: case Type::LongTyID:
438     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
439     O << Data64bitsDirective;
440     break;
441   case Type::FloatTyID: case Type::DoubleTyID:
442     assert (0 && "Should have already output floating point constant.");
443   default:
444     assert (0 && "Can't handle printing this type of thing");
445     break;
446   }
447   EmitConstantValueOnly(CV);
448   O << "\n";
449 }