Add section switching to common code generator code. Add a couple of
[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/CodeGen/AsmPrinter.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Module.h"
17 #include "llvm/Support/Mangler.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Target/TargetMachine.h"
20 using namespace llvm;
21
22 /// SwitchSection - Switch to the specified section of the executable if we
23 /// are not already in it!
24 ///
25 void AsmPrinter::SwitchSection(const char *NewSection, const GlobalValue *GV) {
26   std::string NS;
27   
28   if (GV && GV->hasSection())
29     NS = ".section " + GV->getSection();
30   else
31     NS = NewSection;
32   
33   if (CurrentSection != NS) {
34     CurrentSection = NS;
35     if (!CurrentSection.empty())
36       O << "\t" << CurrentSection << "\n";
37   }
38 }
39
40 bool AsmPrinter::doInitialization(Module &M) {
41   Mang = new Mangler(M, GlobalPrefix);
42   SwitchSection("", 0);   // Reset back to no section.
43   return false;
44 }
45
46 bool AsmPrinter::doFinalization(Module &M) {
47   delete Mang; Mang = 0;
48   return false;
49 }
50
51 void AsmPrinter::setupMachineFunction(MachineFunction &MF) {
52   // What's my mangled name?
53   CurrentFnName = Mang->getValueName(MF.getFunction());
54 }
55
56 // emitAlignment - Emit an alignment directive to the specified power of two.
57 void AsmPrinter::emitAlignment(unsigned NumBits, const GlobalValue *GV) const {
58   if (GV && GV->getAlignment())
59     NumBits = Log2_32(GV->getAlignment());
60   if (NumBits == 0) return;   // No need to emit alignment.
61   if (AlignmentIsInBytes) NumBits = 1 << NumBits;
62   O << AlignDirective << NumBits << "\n";
63 }
64
65 /// emitZeros - Emit a block of zeros.
66 ///
67 void AsmPrinter::emitZeros(uint64_t NumZeros) const {
68   if (NumZeros) {
69     if (ZeroDirective)
70       O << ZeroDirective << NumZeros << "\n";
71     else {
72       for (; NumZeros; --NumZeros)
73         O << Data8bitsDirective << "0\n";
74     }
75   }
76 }
77
78 // Print out the specified constant, without a storage class.  Only the
79 // constants valid in constant expressions can occur here.
80 void AsmPrinter::emitConstantValueOnly(const Constant *CV) {
81   if (CV->isNullValue() || isa<UndefValue>(CV))
82     O << "0";
83   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
84     assert(CB == ConstantBool::True);
85     O << "1";
86   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
87     if (((CI->getValue() << 32) >> 32) == CI->getValue())
88       O << CI->getValue();
89     else
90       O << (uint64_t)CI->getValue();
91   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
92     O << CI->getValue();
93   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
94     // This is a constant address for a global variable or function. Use the
95     // name of the variable or function as the address value, possibly
96     // decorating it with GlobalVarAddrPrefix/Suffix or
97     // FunctionAddrPrefix/Suffix (these all default to "" )
98     if (isa<Function>(GV))
99       O << FunctionAddrPrefix << Mang->getValueName(GV) << FunctionAddrSuffix;
100     else
101       O << GlobalVarAddrPrefix << Mang->getValueName(GV) << GlobalVarAddrSuffix;
102   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
103     const TargetData &TD = TM.getTargetData();
104     switch(CE->getOpcode()) {
105     case Instruction::GetElementPtr: {
106       // generate a symbolic expression for the byte address
107       const Constant *ptrVal = CE->getOperand(0);
108       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
109       if (int64_t Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
110         if (Offset)
111           O << "(";
112         emitConstantValueOnly(ptrVal);
113         if (Offset > 0)
114           O << ") + " << Offset;
115         else if (Offset < 0)
116           O << ") - " << -Offset;
117       } else {
118         emitConstantValueOnly(ptrVal);
119       }
120       break;
121     }
122     case Instruction::Cast: {
123       // Support only non-converting or widening casts for now, that is, ones
124       // that do not involve a change in value.  This assertion is really gross,
125       // and may not even be a complete check.
126       Constant *Op = CE->getOperand(0);
127       const Type *OpTy = Op->getType(), *Ty = CE->getType();
128
129       // Remember, kids, pointers can be losslessly converted back and forth
130       // into 32-bit or wider integers, regardless of signedness. :-P
131       assert(((isa<PointerType>(OpTy)
132                && (Ty == Type::LongTy || Ty == Type::ULongTy
133                    || Ty == Type::IntTy || Ty == Type::UIntTy))
134               || (isa<PointerType>(Ty)
135                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
136                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
137               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
138                    && OpTy->isLosslesslyConvertibleTo(Ty))))
139              && "FIXME: Don't yet support this kind of constant cast expr");
140       emitConstantValueOnly(Op);
141       break;
142     }
143     case Instruction::Add:
144       O << "(";
145       emitConstantValueOnly(CE->getOperand(0));
146       O << ") + (";
147       emitConstantValueOnly(CE->getOperand(1));
148       O << ")";
149       break;
150     default:
151       assert(0 && "Unsupported operator!");
152     }
153   } else {
154     assert(0 && "Unknown constant value!");
155   }
156 }
157
158 /// toOctal - Convert the low order bits of X into an octal digit.
159 ///
160 static inline char toOctal(int X) {
161   return (X&7)+'0';
162 }
163
164 /// printAsCString - Print the specified array as a C compatible string, only if
165 /// the predicate isString is true.
166 ///
167 static void printAsCString(std::ostream &O, const ConstantArray *CVA,
168                            unsigned LastElt) {
169   assert(CVA->isString() && "Array is not string compatible!");
170
171   O << "\"";
172   for (unsigned i = 0; i != LastElt; ++i) {
173     unsigned char C =
174         (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
175
176     if (C == '"') {
177       O << "\\\"";
178     } else if (C == '\\') {
179       O << "\\\\";
180     } else if (isprint(C)) {
181       O << C;
182     } else {
183       switch(C) {
184       case '\b': O << "\\b"; break;
185       case '\f': O << "\\f"; break;
186       case '\n': O << "\\n"; break;
187       case '\r': O << "\\r"; break;
188       case '\t': O << "\\t"; break;
189       default:
190         O << '\\';
191         O << toOctal(C >> 6);
192         O << toOctal(C >> 3);
193         O << toOctal(C >> 0);
194         break;
195       }
196     }
197   }
198   O << "\"";
199 }
200
201 /// emitGlobalConstant - Print a general LLVM constant to the .s file.
202 ///
203 void AsmPrinter::emitGlobalConstant(const Constant *CV) {
204   const TargetData &TD = TM.getTargetData();
205
206   if (CV->isNullValue() || isa<UndefValue>(CV)) {
207     emitZeros(TD.getTypeSize(CV->getType()));
208     return;
209   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
210     if (CVA->isString()) {
211       unsigned NumElts = CVA->getNumOperands();
212       if (AscizDirective && NumElts && 
213           cast<ConstantInt>(CVA->getOperand(NumElts-1))->getRawValue() == 0) {
214         O << AscizDirective;
215         printAsCString(O, CVA, NumElts-1);
216       } else {
217         O << AsciiDirective;
218         printAsCString(O, CVA, NumElts);
219       }
220       O << "\n";
221     } else { // Not a string.  Print the values in successive locations
222       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
223         emitGlobalConstant(CVA->getOperand(i));
224     }
225     return;
226   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
227     // Print the fields in successive locations. Pad to align if needed!
228     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
229     uint64_t sizeSoFar = 0;
230     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
231       const Constant* field = CVS->getOperand(i);
232
233       // Check if padding is needed and insert one or more 0s.
234       uint64_t fieldSize = TD.getTypeSize(field->getType());
235       uint64_t padSize = ((i == e-1? cvsLayout->StructSize
236                            : cvsLayout->MemberOffsets[i+1])
237                           - cvsLayout->MemberOffsets[i]) - fieldSize;
238       sizeSoFar += fieldSize + padSize;
239
240       // Now print the actual field value
241       emitGlobalConstant(field);
242
243       // Insert the field padding unless it's zero bytes...
244       emitZeros(padSize);
245     }
246     assert(sizeSoFar == cvsLayout->StructSize &&
247            "Layout of constant struct may be incorrect!");
248     return;
249   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
250     // FP Constants are printed as integer constants to avoid losing
251     // precision...
252     double Val = CFP->getValue();
253     if (CFP->getType() == Type::DoubleTy) {
254       if (Data64bitsDirective)
255         O << Data64bitsDirective << DoubleToBits(Val) << "\t" << CommentString
256           << " double value: " << Val << "\n";
257       else if (TD.isBigEndian()) {
258         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
259           << "\t" << CommentString << " double most significant word "
260           << Val << "\n";
261         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
262           << "\t" << CommentString << " double least significant word "
263           << Val << "\n";
264       } else {
265         O << Data32bitsDirective << unsigned(DoubleToBits(Val))
266           << "\t" << CommentString << " double least significant word " << Val
267           << "\n";
268         O << Data32bitsDirective << unsigned(DoubleToBits(Val) >> 32)
269           << "\t" << CommentString << " double most significant word " << Val
270           << "\n";
271       }
272       return;
273     } else {
274       O << Data32bitsDirective << FloatToBits(Val) << "\t" << CommentString
275         << " float " << Val << "\n";
276       return;
277     }
278   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
279     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
280       uint64_t Val = CI->getRawValue();
281
282       if (Data64bitsDirective)
283         O << Data64bitsDirective << Val << "\n";
284       else if (TD.isBigEndian()) {
285         O << Data32bitsDirective << unsigned(Val >> 32)
286           << "\t" << CommentString << " Double-word most significant word "
287           << Val << "\n";
288         O << Data32bitsDirective << unsigned(Val)
289           << "\t" << CommentString << " Double-word least significant word "
290           << Val << "\n";
291       } else {
292         O << Data32bitsDirective << unsigned(Val)
293           << "\t" << CommentString << " Double-word least significant word "
294           << Val << "\n";
295         O << Data32bitsDirective << unsigned(Val >> 32)
296           << "\t" << CommentString << " Double-word most significant word "
297           << Val << "\n";
298       }
299       return;
300     }
301   }
302
303   const Type *type = CV->getType();
304   switch (type->getTypeID()) {
305   case Type::BoolTyID:
306   case Type::UByteTyID: case Type::SByteTyID:
307     O << Data8bitsDirective;
308     break;
309   case Type::UShortTyID: case Type::ShortTyID:
310     O << Data16bitsDirective;
311     break;
312   case Type::PointerTyID:
313     if (TD.getPointerSize() == 8) {
314       O << Data64bitsDirective;
315       break;
316     }
317     //Fall through for pointer size == int size
318   case Type::UIntTyID: case Type::IntTyID:
319     O << Data32bitsDirective;
320     break;
321   case Type::ULongTyID: case Type::LongTyID:
322     assert(Data64bitsDirective &&"Target cannot handle 64-bit constant exprs!");
323     O << Data64bitsDirective;
324     break;
325   case Type::FloatTyID: case Type::DoubleTyID:
326     assert (0 && "Should have already output floating point constant.");
327   default:
328     assert (0 && "Can't handle printing this type of thing");
329     break;
330   }
331   emitConstantValueOnly(CV);
332   O << "\n";
333 }