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