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