remove some dead code
[oota-llvm.git] / lib / Target / Sparc / SparcAsmPrinter.cpp
1 //===-- SparcV8AsmPrinter.cpp - SparcV8 LLVM assembly writer --------------===//
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 contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format Sparc V8 assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcV8.h"
16 #include "SparcV8InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Mangler.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/MathExtras.h"
30 #include <cctype>
31 using namespace llvm;
32
33 namespace {
34   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
35
36   struct SparcV8AsmPrinter : public MachineFunctionPass {
37     /// Output stream on which we're printing assembly code.
38     ///
39     std::ostream &O;
40
41     /// Target machine description which we query for reg. names, data
42     /// layout, etc.
43     ///
44     TargetMachine &TM;
45
46     /// Name-mangler for global names.
47     ///
48     Mangler *Mang;
49
50     SparcV8AsmPrinter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
51
52     /// We name each basic block in a Function with a unique number, so
53     /// that we can consistently refer to them later. This is cleared
54     /// at the beginning of each call to runOnMachineFunction().
55     ///
56     typedef std::map<const Value *, unsigned> ValueMapTy;
57     ValueMapTy NumberForBB;
58
59     /// Cache of mangled name for current function. This is
60     /// recalculated at the beginning of each call to
61     /// runOnMachineFunction().
62     ///
63     std::string CurrentFnName;
64
65     virtual const char *getPassName() const {
66       return "SparcV8 Assembly Printer";
67     }
68
69     void emitConstantValueOnly(const Constant *CV);
70     void emitGlobalConstant(const Constant *CV);
71     void printConstantPool(MachineConstantPool *MCP);
72     void printOperand(const MachineInstr *MI, int opNum);
73     void printMachineInstruction(const MachineInstr *MI);
74     bool printInstruction(const MachineInstr *MI);  // autogenerated.
75     bool runOnMachineFunction(MachineFunction &F);
76     bool doInitialization(Module &M);
77     bool doFinalization(Module &M);
78   };
79 } // end of anonymous namespace
80
81 #include "SparcV8GenAsmWriter.inc"
82
83 /// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
84 /// assembly code for a MachineFunction to the given output stream,
85 /// using the given target machine description.  This should work
86 /// regardless of whether the function is in SSA form.
87 ///
88 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
89                                                   TargetMachine &tm) {
90   return new SparcV8AsmPrinter(o, tm);
91 }
92
93 /// toOctal - Convert the low order bits of X into an octal digit.
94 ///
95 static inline char toOctal(int X) {
96   return (X&7)+'0';
97 }
98
99 /// getAsCString - Return the specified array as a C compatible
100 /// string, only if the predicate isStringCompatible is true.
101 ///
102 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
103   assert(CVA->isString() && "Array is not string compatible!");
104
105   O << "\"";
106   for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
107     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
108
109     if (C == '"') {
110       O << "\\\"";
111     } else if (C == '\\') {
112       O << "\\\\";
113     } else if (isprint(C)) {
114       O << C;
115     } else {
116       switch(C) {
117       case '\b': O << "\\b"; break;
118       case '\f': O << "\\f"; break;
119       case '\n': O << "\\n"; break;
120       case '\r': O << "\\r"; break;
121       case '\t': O << "\\t"; break;
122       default:
123         O << '\\';
124         O << toOctal(C >> 6);
125         O << toOctal(C >> 3);
126         O << toOctal(C >> 0);
127         break;
128       }
129     }
130   }
131   O << "\"";
132 }
133
134 // Print out the specified constant, without a storage class.  Only the
135 // constants valid in constant expressions can occur here.
136 void SparcV8AsmPrinter::emitConstantValueOnly(const Constant *CV) {
137   if (CV->isNullValue() || isa<UndefValue> (CV))
138     O << "0";
139   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
140     assert(CB == ConstantBool::True);
141     O << "1";
142   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
143     if (((CI->getValue() << 32) >> 32) == CI->getValue())
144       O << CI->getValue();
145     else
146       O << (unsigned long long)CI->getValue();
147   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
148     O << CI->getValue();
149   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
150     // This is a constant address for a global variable or function.  Use the
151     // name of the variable or function as the address value.
152     O << Mang->getValueName(GV);
153   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
154     const TargetData &TD = TM.getTargetData();
155     switch(CE->getOpcode()) {
156     case Instruction::GetElementPtr: {
157       // generate a symbolic expression for the byte address
158       const Constant *ptrVal = CE->getOperand(0);
159       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
160       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
161         O << "(";
162         emitConstantValueOnly(ptrVal);
163         O << ") + " << Offset;
164       } else {
165         emitConstantValueOnly(ptrVal);
166       }
167       break;
168     }
169     case Instruction::Cast: {
170       // Support only non-converting or widening casts for now, that is, ones
171       // that do not involve a change in value.  This assertion is really gross,
172       // and may not even be a complete check.
173       Constant *Op = CE->getOperand(0);
174       const Type *OpTy = Op->getType(), *Ty = CE->getType();
175
176       // Pointers on ILP32 machines can be losslessly converted back and
177       // forth into 32-bit or wider integers, regardless of signedness.
178       assert(((isa<PointerType>(OpTy)
179                && (Ty == Type::LongTy || Ty == Type::ULongTy
180                    || Ty == Type::IntTy || Ty == Type::UIntTy))
181               || (isa<PointerType>(Ty)
182                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
183                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
184               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
185                    && OpTy->isLosslesslyConvertibleTo(Ty))))
186              && "FIXME: Don't yet support this kind of constant cast expr");
187       O << "(";
188       emitConstantValueOnly(Op);
189       O << ")";
190       break;
191     }
192     case Instruction::Add:
193       O << "(";
194       emitConstantValueOnly(CE->getOperand(0));
195       O << ") + (";
196       emitConstantValueOnly(CE->getOperand(1));
197       O << ")";
198       break;
199     default:
200       assert(0 && "Unsupported operator!");
201     }
202   } else {
203     assert(0 && "Unknown constant value!");
204   }
205 }
206
207 // Print a constant value or values, with the appropriate storage class as a
208 // prefix.
209 void SparcV8AsmPrinter::emitGlobalConstant(const Constant *CV) {
210   const TargetData &TD = TM.getTargetData();
211
212   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
213     if (CVA->isString()) {
214       O << "\t.ascii\t";
215       printAsCString(O, CVA);
216       O << "\n";
217     } else { // Not a string.  Print the values in successive locations
218       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; i++)
219         emitGlobalConstant(CVA->getOperand(i));
220     }
221     return;
222   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
223     // Print the fields in successive locations. Pad to align if needed!
224     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
225     unsigned sizeSoFar = 0;
226     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
227       const Constant* field = CVS->getOperand(i);
228
229       // Check if padding is needed and insert one or more 0s.
230       unsigned fieldSize = TD.getTypeSize(field->getType());
231       unsigned padSize = ((i == e-1? cvsLayout->StructSize
232                            : cvsLayout->MemberOffsets[i+1])
233                           - cvsLayout->MemberOffsets[i]) - fieldSize;
234       sizeSoFar += fieldSize + padSize;
235
236       // Now print the actual field value
237       emitGlobalConstant(field);
238
239       // Insert the field padding unless it's zero bytes...
240       if (padSize)
241         O << "\t.skip\t " << padSize << "\n";
242     }
243     assert(sizeSoFar == cvsLayout->StructSize &&
244            "Layout of constant struct may be incorrect!");
245     return;
246   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
247     // FP Constants are printed as integer constants to avoid losing
248     // precision...
249     double Val = CFP->getValue();
250     switch (CFP->getType()->getTypeID()) {
251     default: assert(0 && "Unknown floating point type!");
252     case Type::FloatTyID: {
253       O << ".long\t" << FloatToBits(Val) << "\t! float " << Val << "\n";
254       return;
255     }
256     case Type::DoubleTyID: {
257       O << ".word\t0x" << std::hex << (DoubleToBits(Val) >> 32) << std::dec << "\t! double " << Val << "\n";
258       O << ".word\t0x" << std::hex << (DoubleToBits(Val) & 0xffffffffUL) << std::dec << "\t! double " << Val << "\n";
259       return;
260     }
261     }
262   } else if (isa<UndefValue> (CV)) {
263     unsigned size = TD.getTypeSize (CV->getType ());
264     O << "\t.skip\t " << size << "\n";
265     return;
266   } else if (isa<ConstantAggregateZero> (CV)) {
267     unsigned size = TD.getTypeSize (CV->getType ());
268     for (unsigned i = 0; i < size; ++i)
269       O << "\t.byte 0\n";
270     return;
271   }
272
273   const Type *type = CV->getType();
274   O << "\t";
275   switch (type->getTypeID()) {
276   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
277     O << ".byte";
278     break;
279   case Type::UShortTyID: case Type::ShortTyID:
280     O << ".half";
281     break;
282   case Type::FloatTyID: case Type::PointerTyID:
283   case Type::UIntTyID: case Type::IntTyID:
284     O << ".word";
285     break;
286   case Type::DoubleTyID:
287   case Type::ULongTyID: case Type::LongTyID:
288     O << ".xword";
289     break;
290   default:
291     assert (0 && "Can't handle printing this type of thing");
292     break;
293   }
294   O << "\t";
295   emitConstantValueOnly(CV);
296   O << "\n";
297 }
298
299 /// printConstantPool - Print to the current output stream assembly
300 /// representations of the constants in the constant pool MCP. This is
301 /// used to print out constants which have been "spilled to memory" by
302 /// the code generator.
303 ///
304 void SparcV8AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
305   const std::vector<Constant*> &CP = MCP->getConstants();
306   const TargetData &TD = TM.getTargetData();
307
308   if (CP.empty()) return;
309
310   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
311     O << "\t.section \".rodata\"\n";
312     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
313       << "\n";
314     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t!"
315       << *CP[i] << "\n";
316     emitGlobalConstant(CP[i]);
317   }
318 }
319
320 /// runOnMachineFunction - This uses the printMachineInstruction()
321 /// method to print assembly for each instruction.
322 ///
323 bool SparcV8AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
324   // BBNumber is used here so that a given Printer will never give two
325   // BBs the same name. (If you have a better way, please let me know!)
326   static unsigned BBNumber = 0;
327
328   O << "\n\n";
329   // What's my mangled name?
330   CurrentFnName = Mang->getValueName(MF.getFunction());
331
332   // Print out constants referenced by the function
333   printConstantPool(MF.getConstantPool());
334
335   // Print out labels for the function.
336   O << "\t.text\n";
337   O << "\t.align 16\n";
338   O << "\t.globl\t" << CurrentFnName << "\n";
339   O << "\t.type\t" << CurrentFnName << ", #function\n";
340   O << CurrentFnName << ":\n";
341
342   // Number each basic block so that we can consistently refer to them
343   // in PC-relative references.
344   NumberForBB.clear();
345   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
346        I != E; ++I) {
347     NumberForBB[I->getBasicBlock()] = BBNumber++;
348   }
349
350   // Print out code for the function.
351   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
352        I != E; ++I) {
353     // Print a label for the basic block.
354     O << ".LBB" << Mang->getValueName(MF.getFunction ())
355       << "_" << I->getNumber () << ":\t! "
356       << I->getBasicBlock ()->getName () << "\n";
357     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
358          II != E; ++II) {
359       // Print the assembly for the instruction.
360       printMachineInstruction(II);
361     }
362   }
363
364   // We didn't modify anything.
365   return false;
366 }
367
368 void SparcV8AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
369   const MachineOperand &MO = MI->getOperand (opNum);
370   const MRegisterInfo &RI = *TM.getRegisterInfo();
371   bool CloseParen = false;
372   if (MI->getOpcode() == V8::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
373     O << "%hi(";
374     CloseParen = true;
375   } else if (MI->getOpcode() ==V8::ORri &&!MO.isRegister() &&!MO.isImmediate())
376   {
377     O << "%lo(";
378     CloseParen = true;
379   }
380   switch (MO.getType()) {
381   case MachineOperand::MO_VirtualRegister:
382     if (Value *V = MO.getVRegValueOrNull()) {
383       O << "<" << V->getName() << ">";
384       break;
385     }
386     // FALLTHROUGH
387   case MachineOperand::MO_MachineRegister:
388     if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
389       O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
390     else
391       O << "%reg" << MO.getReg();
392     break;
393
394   case MachineOperand::MO_SignExtendedImmed:
395   case MachineOperand::MO_UnextendedImmed:
396     O << (int)MO.getImmedValue();
397     break;
398   case MachineOperand::MO_MachineBasicBlock: {
399     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
400     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
401       << "_" << MBBOp->getNumber () << "\t! "
402       << MBBOp->getBasicBlock ()->getName ();
403     return;
404   }
405   case MachineOperand::MO_PCRelativeDisp:
406     std::cerr << "Shouldn't use addPCDisp() when building SparcV8 MachineInstrs";
407     abort ();
408     return;
409   case MachineOperand::MO_GlobalAddress:
410     O << Mang->getValueName(MO.getGlobal());
411     break;
412   case MachineOperand::MO_ExternalSymbol:
413     O << MO.getSymbolName();
414     break;
415   case MachineOperand::MO_ConstantPoolIndex:
416     O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
417     break;
418   default:
419     O << "<unknown operand type>"; abort (); break;
420   }
421   if (CloseParen) O << ")";
422 }
423
424 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
425 /// MI in GAS syntax to the current output stream.
426 ///
427 void SparcV8AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
428   O << "\t";
429   if (printInstruction(MI)) return;
430
431   unsigned Opcode = MI->getOpcode();
432   const TargetInstrInfo &TII = *TM.getInstrInfo();
433   const TargetInstrDescriptor &Desc = TII.get(Opcode);
434
435   O << Desc.Name << " ";
436
437   // print non-immediate, non-register-def operands
438   // then print immediate operands
439   // then print register-def operands.
440   std::vector<int> print_order;
441   for (unsigned i = 0; i < MI->getNumOperands (); ++i)
442     if (!(MI->getOperand (i).isImmediate ()
443           || (MI->getOperand (i).isRegister ()
444               && MI->getOperand (i).isDef ())))
445       print_order.push_back (i);
446   for (unsigned i = 0; i < MI->getNumOperands (); ++i)
447     if (MI->getOperand (i).isImmediate ())
448       print_order.push_back (i);
449   for (unsigned i = 0; i < MI->getNumOperands (); ++i)
450     if (MI->getOperand (i).isRegister () && MI->getOperand (i).isDef ())
451       print_order.push_back (i);
452   for (unsigned i = 0, e = print_order.size (); i != e; ++i) {
453     printOperand (MI, print_order[i]);
454     if (i != (print_order.size () - 1))
455       O << ", ";
456   }
457   O << "\n";
458 }
459
460 bool SparcV8AsmPrinter::doInitialization(Module &M) {
461   Mang = new Mangler(M);
462   return false; // success
463 }
464
465 // SwitchSection - Switch to the specified section of the executable if we are
466 // not already in it!
467 //
468 static void SwitchSection(std::ostream &OS, std::string &CurSection,
469                           const char *NewSection) {
470   if (CurSection != NewSection) {
471     CurSection = NewSection;
472     if (!CurSection.empty())
473       OS << "\t.section \"" << NewSection << "\"\n";
474   }
475 }
476
477 bool SparcV8AsmPrinter::doFinalization(Module &M) {
478   const TargetData &TD = TM.getTargetData();
479   std::string CurSection;
480
481   // Print out module-level global variables here.
482   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
483     if (I->hasInitializer()) {   // External global require no code
484       O << "\n\n";
485       std::string name = Mang->getValueName(I);
486       Constant *C = I->getInitializer();
487       unsigned Size = TD.getTypeSize(C->getType());
488       unsigned Align = TD.getTypeAlignment(C->getType());
489
490       if (C->isNullValue() &&
491           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
492            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
493         SwitchSection(O, CurSection, ".data");
494         if (I->hasInternalLinkage())
495           O << "\t.local " << name << "\n";
496
497         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
498           << "," << (unsigned)TD.getTypeAlignment(C->getType());
499         O << "\t\t! ";
500         WriteAsOperand(O, I, true, true, &M);
501         O << "\n";
502       } else {
503         switch (I->getLinkage()) {
504         case GlobalValue::LinkOnceLinkage:
505         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
506           // Nonnull linkonce -> weak
507           O << "\t.weak " << name << "\n";
508           SwitchSection(O, CurSection, "");
509           O << "\t.section\t\".llvm.linkonce.d." << name << "\",\"aw\",@progbits\n";
510           break;
511
512         case GlobalValue::AppendingLinkage:
513           // FIXME: appending linkage variables should go into a section of
514           // their name or something.  For now, just emit them as external.
515         case GlobalValue::ExternalLinkage:
516           // If external or appending, declare as a global symbol
517           O << "\t.globl " << name << "\n";
518           // FALL THROUGH
519         case GlobalValue::InternalLinkage:
520           if (C->isNullValue())
521             SwitchSection(O, CurSection, ".bss");
522           else
523             SwitchSection(O, CurSection, ".data");
524           break;
525         case GlobalValue::GhostLinkage:
526           std::cerr << "Should not have any unmaterialized functions!\n";
527           abort();
528         }
529
530         O << "\t.align " << Align << "\n";
531         O << "\t.type " << name << ",#object\n";
532         O << "\t.size " << name << "," << Size << "\n";
533         O << name << ":\t\t\t\t! ";
534         WriteAsOperand(O, I, true, true, &M);
535         O << " = ";
536         WriteAsOperand(O, C, false, false, &M);
537         O << "\n";
538         emitGlobalConstant(C);
539       }
540     }
541
542   delete Mang;
543   return false; // success
544 }