SparcAsmPrinter.cpp revision 07000c6f01d8f57170f2d4c77a86d934bdc5c696
1//===-- SparcAsmPrinter.cpp - Sparc 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 assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sparc.h"
16#include "SparcInstrInfo.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/AsmPrinter.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineInstr.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Support/Mangler.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringExtras.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/MathExtras.h"
32#include <cctype>
33#include <iostream>
34using namespace llvm;
35
36namespace {
37  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
38
39  struct SparcAsmPrinter : public AsmPrinter {
40    SparcAsmPrinter(std::ostream &O, TargetMachine &TM) : AsmPrinter(O, TM) {
41      Data16bitsDirective = "\t.half\t";
42      Data32bitsDirective = "\t.word\t";
43      Data64bitsDirective = 0;  // .xword is only supported by V9.
44      ZeroDirective = "\t.skip\t";
45      CommentString = "!";
46      ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
47    }
48
49    /// We name each basic block in a Function with a unique number, so
50    /// that we can consistently refer to them later. This is cleared
51    /// at the beginning of each call to runOnMachineFunction().
52    ///
53    typedef std::map<const Value *, unsigned> ValueMapTy;
54    ValueMapTy NumberForBB;
55
56    virtual const char *getPassName() const {
57      return "Sparc Assembly Printer";
58    }
59
60    void printOperand(const MachineInstr *MI, int opNum);
61    void printMemOperand(const MachineInstr *MI, int opNum,
62                         const char *Modifier = 0);
63    void printCCOperand(const MachineInstr *MI, int opNum);
64
65    bool printInstruction(const MachineInstr *MI);  // autogenerated.
66    bool runOnMachineFunction(MachineFunction &F);
67    bool doInitialization(Module &M);
68    bool doFinalization(Module &M);
69  };
70} // end of anonymous namespace
71
72#include "SparcGenAsmWriter.inc"
73
74/// createSparcCodePrinterPass - Returns a pass that prints the SPARC
75/// assembly code for a MachineFunction to the given output stream,
76/// using the given target machine description.  This should work
77/// regardless of whether the function is in SSA form.
78///
79FunctionPass *llvm::createSparcCodePrinterPass(std::ostream &o,
80                                               TargetMachine &tm) {
81  return new SparcAsmPrinter(o, tm);
82}
83
84/// runOnMachineFunction - This uses the printMachineInstruction()
85/// method to print assembly for each instruction.
86///
87bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
88  SetupMachineFunction(MF);
89
90  // Print out constants referenced by the function
91  EmitConstantPool(MF.getConstantPool());
92
93  // BBNumber is used here so that a given Printer will never give two
94  // BBs the same name. (If you have a better way, please let me know!)
95  static unsigned BBNumber = 0;
96
97  O << "\n\n";
98  // What's my mangled name?
99  CurrentFnName = Mang->getValueName(MF.getFunction());
100
101  // Print out labels for the function.
102  SwitchToTextSection(".text", MF.getFunction());
103  EmitAlignment(4, MF.getFunction());
104  O << "\t.globl\t" << CurrentFnName << "\n";
105  O << "\t.type\t" << CurrentFnName << ", #function\n";
106  O << CurrentFnName << ":\n";
107
108  // Number each basic block so that we can consistently refer to them
109  // in PC-relative references.
110  NumberForBB.clear();
111  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
112       I != E; ++I) {
113    NumberForBB[I->getBasicBlock()] = BBNumber++;
114  }
115
116  // Print out code for the function.
117  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
118       I != E; ++I) {
119    // Print a label for the basic block.
120    if (I != MF.begin()) {
121      printBasicBlockLabel(I, true);
122      O << '\n';
123    }
124    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
125         II != E; ++II) {
126      // Print the assembly for the instruction.
127      O << "\t";
128      printInstruction(II);
129      ++EmittedInsts;
130    }
131  }
132
133  // We didn't modify anything.
134  return false;
135}
136
137void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
138  const MachineOperand &MO = MI->getOperand (opNum);
139  const MRegisterInfo &RI = *TM.getRegisterInfo();
140  bool CloseParen = false;
141  if (MI->getOpcode() == SP::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
142    O << "%hi(";
143    CloseParen = true;
144  } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri)
145             && !MO.isRegister() && !MO.isImmediate()) {
146    O << "%lo(";
147    CloseParen = true;
148  }
149  switch (MO.getType()) {
150  case MachineOperand::MO_Register:
151    if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
152      O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
153    else
154      O << "%reg" << MO.getReg();
155    break;
156
157  case MachineOperand::MO_Immediate:
158    O << (int)MO.getImmedValue();
159    break;
160  case MachineOperand::MO_MachineBasicBlock:
161    printBasicBlockLabel(MO.getMachineBasicBlock());
162    return;
163  case MachineOperand::MO_GlobalAddress:
164    O << Mang->getValueName(MO.getGlobal());
165    break;
166  case MachineOperand::MO_ExternalSymbol:
167    O << MO.getSymbolName();
168    break;
169  case MachineOperand::MO_ConstantPoolIndex:
170    O << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << "_"
171      << MO.getConstantPoolIndex();
172    break;
173  default:
174    O << "<unknown operand type>"; abort (); break;
175  }
176  if (CloseParen) O << ")";
177}
178
179void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
180                                      const char *Modifier) {
181  printOperand(MI, opNum);
182
183  // If this is an ADD operand, emit it like normal operands.
184  if (Modifier && !strcmp(Modifier, "arith")) {
185    O << ", ";
186    printOperand(MI, opNum+1);
187    return;
188  }
189
190  MachineOperand::MachineOperandType OpTy = MI->getOperand(opNum+1).getType();
191
192  if (MI->getOperand(opNum+1).isRegister() &&
193      MI->getOperand(opNum+1).getReg() == SP::G0)
194    return;   // don't print "+%g0"
195  if (MI->getOperand(opNum+1).isImmediate() &&
196      MI->getOperand(opNum+1).getImmedValue() == 0)
197    return;   // don't print "+0"
198
199  O << "+";
200  if (MI->getOperand(opNum+1).isGlobalAddress() ||
201      MI->getOperand(opNum+1).isConstantPoolIndex()) {
202    O << "%lo(";
203    printOperand(MI, opNum+1);
204    O << ")";
205  } else {
206    printOperand(MI, opNum+1);
207  }
208}
209
210void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
211  int CC = (int)MI->getOperand(opNum).getImmedValue();
212  O << SPARCCondCodeToString((SPCC::CondCodes)CC);
213}
214
215
216
217bool SparcAsmPrinter::doInitialization(Module &M) {
218  Mang = new Mangler(M);
219  return false; // success
220}
221
222bool SparcAsmPrinter::doFinalization(Module &M) {
223  const TargetData *TD = TM.getTargetData();
224
225  // Print out module-level global variables here.
226  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
227       I != E; ++I)
228    if (I->hasInitializer()) {   // External global require no code
229      // Check to see if this is a special global used by LLVM, if so, emit it.
230      if (EmitSpecialLLVMGlobal(I))
231        continue;
232
233      O << "\n\n";
234      std::string name = Mang->getValueName(I);
235      Constant *C = I->getInitializer();
236      unsigned Size = TD->getTypeSize(C->getType());
237      unsigned Align = TD->getTypeAlignment(C->getType());
238
239      if (C->isNullValue() &&
240          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
241           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
242        SwitchToDataSection(".data", I);
243        if (I->hasInternalLinkage())
244          O << "\t.local " << name << "\n";
245
246        O << "\t.comm " << name << "," << TD->getTypeSize(C->getType())
247          << "," << (unsigned)TD->getTypeAlignment(C->getType());
248        O << "\t\t! ";
249        WriteAsOperand(O, I, true, true, &M);
250        O << "\n";
251      } else {
252        switch (I->getLinkage()) {
253        case GlobalValue::LinkOnceLinkage:
254        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
255          // Nonnull linkonce -> weak
256          O << "\t.weak " << name << "\n";
257          SwitchToDataSection("", I);
258          O << "\t.section\t\".llvm.linkonce.d." << name
259            << "\",\"aw\",@progbits\n";
260          break;
261
262        case GlobalValue::AppendingLinkage:
263          // FIXME: appending linkage variables should go into a section of
264          // their name or something.  For now, just emit them as external.
265        case GlobalValue::ExternalLinkage:
266          // If external or appending, declare as a global symbol
267          O << "\t.globl " << name << "\n";
268          // FALL THROUGH
269        case GlobalValue::InternalLinkage:
270          if (C->isNullValue())
271            SwitchToDataSection(".bss", I);
272          else
273            SwitchToDataSection(".data", I);
274          break;
275        case GlobalValue::GhostLinkage:
276          std::cerr << "Should not have any unmaterialized functions!\n";
277          abort();
278        }
279
280        O << "\t.align " << Align << "\n";
281        O << "\t.type " << name << ",#object\n";
282        O << "\t.size " << name << "," << Size << "\n";
283        O << name << ":\t\t\t\t! ";
284        WriteAsOperand(O, I, true, true, &M);
285        O << "\n";
286        EmitGlobalConstant(C);
287      }
288    }
289
290  AsmPrinter::doFinalization(M);
291  return false; // success
292}
293