Be a bit more efficient when processing the active and inactive
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9AsmPrinter.cpp
1 //===-- EmitAssembly.cpp - Emit SparcV9 Specific .s File -------------------==//
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 all of the stuff necessary to output a .s file from
11 // LLVM.  The code in this file assumes that the specified module has already
12 // been compiled into the internal data structures of the Module.
13 //
14 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
15 // The FunctionPass is pipelined together with all of the rest of the code
16 // generation stages, and the Pass runs at the end to emit code for global
17 // variables and such.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/Support/Mangler.h"
31 #include "Support/StringExtras.h"
32 #include "Support/Statistic.h"
33 #include "SparcV9Internals.h"
34 #include "MachineFunctionInfo.h"
35 #include <string>
36 using namespace llvm;
37
38 namespace {
39   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
40 }
41
42 namespace {
43   struct SparcV9AsmPrinter : public AsmPrinter {
44   public:
45     enum Sections {
46       Unknown,
47       Text,
48       ReadOnlyData,
49       InitRWData,
50       ZeroInitRWData,
51     } CurSection;
52
53     SparcV9AsmPrinter(std::ostream &OS, TargetMachine &TM)
54       : AsmPrinter(OS, TM), CurSection(Unknown) {
55       ZeroDirective       = 0;  // No way to get zeros.
56       Data16bitsDirective = "\t.half\t";
57       Data32bitsDirective = "\t.word\t";
58       Data64bitsDirective = "\t.xword\t";
59       CommentString = "!";
60     }
61
62     const char *getPassName() const {
63       return "SparcV9 Assembly Printer";
64     }
65
66     // Print a constant (which may be an aggregate) prefixed by all the
67     // appropriate directives.  Uses printConstantValueOnly() to print the
68     // value or values.
69     void printConstant(const Constant* CV, const std::string &valID) {
70       emitAlignment(TM.getTargetData().getTypeAlignmentShift(CV->getType()));
71       O << "\t.type" << "\t" << valID << ",#object\n";
72
73       unsigned constSize = TM.getTargetData().getTypeSize(CV->getType());
74       O << "\t.size" << "\t" << valID << "," << constSize << "\n";
75   
76       O << valID << ":\n";
77   
78       emitGlobalConstant(CV);
79     }
80
81     // enterSection - Use this method to enter a different section of the output
82     // executable.  This is used to only output necessary section transitions.
83     //
84     void enterSection(enum Sections S) {
85       if (S == CurSection) return;        // Only switch section if necessary
86       CurSection = S;
87
88       O << "\n\t.section ";
89       switch (S)
90       {
91       default: assert(0 && "Bad section name!");
92       case Text:         O << "\".text\""; break;
93       case ReadOnlyData: O << "\".rodata\",#alloc"; break;
94       case InitRWData:   O << "\".data\",#alloc,#write"; break;
95       case ZeroInitRWData: O << "\".bss\",#alloc,#write"; break;
96       }
97       O << "\n";
98     }
99
100     // getID Wrappers - Ensure consistent usage
101     // Symbol names in SparcV9 assembly language have these rules:
102     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
103     // (b) A name beginning in "." is treated as a local name.
104     std::string getID(const Function *F) {
105       return Mang->getValueName(F);
106     }
107     std::string getID(const BasicBlock *BB) {
108       return ".L_" + getID(BB->getParent()) + "_" + Mang->getValueName(BB);
109     }
110     std::string getID(const GlobalVariable *GV) {
111       return Mang->getValueName(GV);
112     }
113     std::string getID(const Constant *CV) {
114       return ".C_" + Mang->getValueName(CV);
115     }
116     std::string getID(const GlobalValue *GV) {
117       if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
118         return getID(V);
119       else if (const Function *F = dyn_cast<Function>(GV))
120         return getID(F);
121       assert(0 && "Unexpected type of GlobalValue!");
122       return "";
123     }
124
125     virtual bool runOnMachineFunction(MachineFunction &MF) {
126       setupMachineFunction(MF);
127       emitFunction(MF);
128       return false;
129     }
130
131     virtual bool doFinalization(Module &M) {
132       emitGlobals(M);
133       AsmPrinter::doFinalization(M);
134       return false;
135     }
136
137     void emitFunction(MachineFunction &F);
138   private :
139     void emitBasicBlock(const MachineBasicBlock &MBB);
140     void emitMachineInst(const MachineInstr *MI);
141   
142     unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
143     void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
144
145     bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
146     bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
147   
148     unsigned getOperandMask(unsigned Opcode) {
149       switch (Opcode) {
150       case V9::SUBccr:
151       case V9::SUBcci:   return 1 << 3;  // Remove CC argument
152       default:      return 0;       // By default, don't hack operands...
153       }
154     }
155
156     void emitGlobals(const Module &M);
157     void printGlobalVariable(const GlobalVariable *GV);
158   };
159
160 } // End anonymous namespace
161
162 inline bool
163 SparcV9AsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
164                                        unsigned int opNum) {
165   switch (MI->getOpcode()) {
166   case V9::JMPLCALLr:
167   case V9::JMPLCALLi:
168   case V9::JMPLRETr:
169   case V9::JMPLRETi:
170     return (opNum == 0);
171   default:
172     return false;
173   }
174 }
175
176 inline bool
177 SparcV9AsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
178                                        unsigned int opNum) {
179   if (TM.getInstrInfo()->isLoad(MI->getOpcode()))
180     return (opNum == 0);
181   else if (TM.getInstrInfo()->isStore(MI->getOpcode()))
182     return (opNum == 1);
183   else
184     return false;
185 }
186
187 unsigned int
188 SparcV9AsmPrinter::printOperands(const MachineInstr *MI, unsigned opNum) {
189   const MachineOperand& mop = MI->getOperand(opNum);
190   if (OpIsBranchTargetLabel(MI, opNum)) {
191     printOneOperand(mop, MI->getOpcode());
192     O << "+";
193     printOneOperand(MI->getOperand(opNum+1), MI->getOpcode());
194     return 2;
195   } else if (OpIsMemoryAddressBase(MI, opNum)) {
196     O << "[";
197     printOneOperand(mop, MI->getOpcode());
198     O << "+";
199     printOneOperand(MI->getOperand(opNum+1), MI->getOpcode());
200     O << "]";
201     return 2;
202   } else {
203     printOneOperand(mop, MI->getOpcode());
204     return 1;
205   }
206 }
207
208 void
209 SparcV9AsmPrinter::printOneOperand(const MachineOperand &mop,
210                                    MachineOpCode opCode)
211 {
212   bool needBitsFlag = true;
213   
214   if (mop.isHiBits32())
215     O << "%lm(";
216   else if (mop.isLoBits32())
217     O << "%lo(";
218   else if (mop.isHiBits64())
219     O << "%hh(";
220   else if (mop.isLoBits64())
221     O << "%hm(";
222   else
223     needBitsFlag = false;
224   
225   switch (mop.getType())
226     {
227     case MachineOperand::MO_VirtualRegister:
228     case MachineOperand::MO_CCRegister:
229     case MachineOperand::MO_MachineRegister:
230       {
231         int regNum = (int)mop.getReg();
232         
233         if (regNum == TM.getRegInfo()->getInvalidRegNum()) {
234           // better to print code with NULL registers than to die
235           O << "<NULL VALUE>";
236         } else {
237           O << "%" << TM.getRegInfo()->getUnifiedRegName(regNum);
238         }
239         break;
240       }
241     
242     case MachineOperand::MO_ConstantPoolIndex:
243       {
244         O << ".CPI_" << CurrentFnName << "_" << mop.getConstantPoolIndex();
245         break;
246       }
247
248     case MachineOperand::MO_PCRelativeDisp:
249       {
250         const Value *Val = mop.getVRegValue();
251         assert(Val && "\tNULL Value in SparcV9AsmPrinter");
252         
253         if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
254           O << getID(BB);
255         else if (const Function *F = dyn_cast<Function>(Val))
256           O << getID(F);
257         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
258           O << getID(GV);
259         else if (const Constant *CV = dyn_cast<Constant>(Val))
260           O << getID(CV);
261         else
262           assert(0 && "Unrecognized value in SparcV9AsmPrinter");
263         break;
264       }
265     
266     case MachineOperand::MO_SignExtendedImmed:
267       O << mop.getImmedValue();
268       break;
269
270     case MachineOperand::MO_UnextendedImmed:
271       O << (uint64_t) mop.getImmedValue();
272       break;
273     
274     default:
275       O << mop;      // use dump field
276       break;
277     }
278   
279   if (needBitsFlag)
280     O << ")";
281 }
282
283 void SparcV9AsmPrinter::emitMachineInst(const MachineInstr *MI) {
284   unsigned Opcode = MI->getOpcode();
285
286   if (Opcode == V9::PHI)
287     return;  // Ignore Machine-PHI nodes.
288
289   O << "\t" << TM.getInstrInfo()->getName(Opcode) << "\t";
290
291   unsigned Mask = getOperandMask(Opcode);
292   
293   bool NeedComma = false;
294   unsigned N = 1;
295   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
296     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
297       if (NeedComma) O << ", ";         // Handle comma outputting
298       NeedComma = true;
299       N = printOperands(MI, OpNum);
300     } else
301       N = 1;
302   
303   O << "\n";
304   ++EmittedInsts;
305 }
306
307 void SparcV9AsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB) {
308   // Emit a label for the basic block
309   O << getID(MBB.getBasicBlock()) << ":\n";
310
311   // Loop over all of the instructions in the basic block...
312   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
313        MII != MIE; ++MII)
314     emitMachineInst(MII);
315   O << "\n";  // Separate BB's with newlines
316 }
317
318 void SparcV9AsmPrinter::emitFunction(MachineFunction &MF) {
319   O << "!****** Outputing Function: " << CurrentFnName << " ******\n";
320
321   // Emit constant pool for this function
322   const MachineConstantPool *MCP = MF.getConstantPool();
323   const std::vector<Constant*> &CP = MCP->getConstants();
324
325   enterSection(ReadOnlyData);
326   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
327     std::string cpiName = ".CPI_" + CurrentFnName + "_" + utostr(i);
328     printConstant(CP[i], cpiName);
329   }
330
331   enterSection(Text);
332   O << "\t.align\t4\n\t.global\t" << CurrentFnName << "\n";
333   //O << "\t.type\t" << CurrentFnName << ",#function\n";
334   O << "\t.type\t" << CurrentFnName << ", 2\n";
335   O << CurrentFnName << ":\n";
336
337   // Output code for all of the basic blocks in the function...
338   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
339     emitBasicBlock(*I);
340
341   // Output a .size directive so the debugger knows the extents of the function
342   O << ".EndOf_" << CurrentFnName << ":\n\t.size "
343            << CurrentFnName << ", .EndOf_"
344            << CurrentFnName << "-" << CurrentFnName << "\n";
345
346   // Put some spaces between the functions
347   O << "\n\n";
348 }
349
350 void SparcV9AsmPrinter::printGlobalVariable(const GlobalVariable* GV) {
351   if (GV->hasExternalLinkage())
352     O << "\t.global\t" << getID(GV) << "\n";
353   
354   if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue()) {
355     printConstant(GV->getInitializer(), getID(GV));
356   } else {
357     const Type *ValTy = GV->getType()->getElementType();
358     emitAlignment(TM.getTargetData().getTypeAlignmentShift(ValTy));
359     O << "\t.type\t" << getID(GV) << ",#object\n";
360     O << "\t.reserve\t" << getID(GV) << ","
361       << TM.getTargetData().getTypeSize(GV->getType()->getElementType())
362       << "\n";
363   }
364 }
365
366 void SparcV9AsmPrinter::emitGlobals(const Module &M) {
367   // Output global variables...
368   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
369     if (! GI->isExternal()) {
370       assert(GI->hasInitializer());
371       if (GI->isConstant())
372         enterSection(ReadOnlyData);   // read-only, initialized data
373       else if (GI->getInitializer()->isNullValue())
374         enterSection(ZeroInitRWData); // read-write zero data
375       else
376         enterSection(InitRWData);     // read-write non-zero data
377
378       printGlobalVariable(GI);
379     }
380
381   O << "\n";
382 }
383
384 FunctionPass *llvm::createAsmPrinterPass(std::ostream &Out, TargetMachine &TM) {
385   return new SparcV9AsmPrinter(Out, TM);
386 }