Improve Mips back-end's handling of DBG_VALUE.
[oota-llvm.git] / lib / Target / Mips / MipsAsmPrinter.cpp
1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 MIPS assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-asm-printer"
16 #include "Mips.h"
17 #include "MipsSubtarget.h"
18 #include "MipsInstrInfo.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsMachineFunction.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetRegistry.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Analysis/DebugInfo.h"
42
43 using namespace llvm;
44
45 namespace {
46   class MipsAsmPrinter : public AsmPrinter {
47     const MipsSubtarget *Subtarget;
48   public:
49     explicit MipsAsmPrinter(TargetMachine &TM,  MCStreamer &Streamer)
50       : AsmPrinter(TM, Streamer) {
51       Subtarget = &TM.getSubtarget<MipsSubtarget>();
52     }
53
54     virtual const char *getPassName() const {
55       return "Mips Assembly Printer";
56     }
57
58     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
59                          unsigned AsmVariant, const char *ExtraCode,
60                          raw_ostream &O);
61     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
62                                unsigned AsmVariant, const char *ExtraCode,
63                                raw_ostream &O);
64     void printOperand(const MachineInstr *MI, int opNum, raw_ostream &O);
65     void printUnsignedImm(const MachineInstr *MI, int opNum, raw_ostream &O);
66     void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
67                          const char *Modifier = 0);
68     void printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
69                          const char *Modifier = 0);
70     void printSavedRegsBitmask(raw_ostream &O);
71     void printHex32(unsigned int Value, raw_ostream &O);
72
73     const char *getCurrentABIString() const;
74     void emitFrameDirective();
75
76     void printInstruction(const MachineInstr *MI, raw_ostream &O); // autogen'd.
77     void EmitInstruction(const MachineInstr *MI) {
78       SmallString<128> Str;
79       raw_svector_ostream OS(Str);
80
81       if (MI->isDebugValue())
82         PrintDebugValueComment(MI, OS);
83
84       printInstruction(MI, OS);
85       OutStreamer.EmitRawText(OS.str());
86     }
87     virtual void EmitFunctionBodyStart();
88     virtual void EmitFunctionBodyEnd();
89     virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
90                                                    MBB) const;
91     static const char *getRegisterName(unsigned RegNo);
92
93     virtual void EmitFunctionEntryLabel();
94     void EmitStartOfAsmFile(Module &M);
95     virtual MachineLocation getDebugValueLocation(const MachineInstr *MI) const;
96
97     void PrintDebugValueComment(const MachineInstr *MI, raw_ostream &OS);
98   };
99 } // end of anonymous namespace
100
101 #include "MipsGenAsmWriter.inc"
102
103 //===----------------------------------------------------------------------===//
104 //
105 //  Mips Asm Directives
106 //
107 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
108 //  Describe the stack frame.
109 //
110 //  -- Mask directives "(f)mask  bitmask, offset"
111 //  Tells the assembler which registers are saved and where.
112 //  bitmask - contain a little endian bitset indicating which registers are
113 //            saved on function prologue (e.g. with a 0x80000000 mask, the
114 //            assembler knows the register 31 (RA) is saved at prologue.
115 //  offset  - the position before stack pointer subtraction indicating where
116 //            the first saved register on prologue is located. (e.g. with a
117 //
118 //  Consider the following function prologue:
119 //
120 //    .frame  $fp,48,$ra
121 //    .mask   0xc0000000,-8
122 //       addiu $sp, $sp, -48
123 //       sw $ra, 40($sp)
124 //       sw $fp, 36($sp)
125 //
126 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
127 //    30 (FP) are saved at prologue. As the save order on prologue is from
128 //    left to right, RA is saved first. A -8 offset means that after the
129 //    stack pointer subtration, the first register in the mask (RA) will be
130 //    saved at address 48-8=40.
131 //
132 //===----------------------------------------------------------------------===//
133
134 //===----------------------------------------------------------------------===//
135 // Mask directives
136 //===----------------------------------------------------------------------===//
137
138 // Create a bitmask with all callee saved registers for CPU or Floating Point
139 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
140 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
141   // CPU and FPU Saved Registers Bitmasks
142   unsigned CPUBitmask = 0, FPUBitmask = 0;
143   int CPUTopSavedRegOff, FPUTopSavedRegOff;
144
145   // Set the CPU and FPU Bitmasks
146   const MachineFrameInfo *MFI = MF->getFrameInfo();
147   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
148   // size of stack area to which FP callee-saved regs are saved.
149   unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
150   unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
151   unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
152   bool HasAFGR64Reg = false;
153   unsigned CSFPRegsSize = 0;
154   unsigned i, e = CSI.size();
155
156   // Set FPU Bitmask.
157   for (i = 0; i != e; ++i) {
158     unsigned Reg = CSI[i].getReg();
159     if (Mips::CPURegsRegisterClass->contains(Reg))
160       break;
161
162     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
163     if (Mips::AFGR64RegisterClass->contains(Reg)) {
164       FPUBitmask |= (3 << RegNum);
165       CSFPRegsSize += AFGR64RegSize;
166       HasAFGR64Reg = true;
167       continue;
168     }
169
170     FPUBitmask |= (1 << RegNum);
171     CSFPRegsSize += FGR32RegSize;
172   }
173
174   // Set CPU Bitmask.
175   for (; i != e; ++i) {
176     unsigned Reg = CSI[i].getReg();
177     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
178     CPUBitmask |= (1 << RegNum);
179   }
180
181   // FP Regs are saved right below where the virtual frame pointer points to.
182   FPUTopSavedRegOff = FPUBitmask ?
183     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
184
185   // CPU Regs are saved below FP Regs.
186   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
187
188   // Print CPUBitmask
189   O << "\t.mask \t"; printHex32(CPUBitmask, O);
190   O << ',' << CPUTopSavedRegOff << '\n';
191
192   // Print FPUBitmask
193   O << "\t.fmask\t"; printHex32(FPUBitmask, O);
194   O << "," << FPUTopSavedRegOff << '\n';
195 }
196
197 // Print a 32 bit hex number with all numbers.
198 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
199   O << "0x";
200   for (int i = 7; i >= 0; i--)
201     O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
202 }
203
204 //===----------------------------------------------------------------------===//
205 // Frame and Set directives
206 //===----------------------------------------------------------------------===//
207
208 /// Frame Directive
209 void MipsAsmPrinter::emitFrameDirective() {
210   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
211
212   unsigned stackReg  = RI.getFrameRegister(*MF);
213   unsigned returnReg = RI.getRARegister();
214   unsigned stackSize = MF->getFrameInfo()->getStackSize();
215
216   OutStreamer.EmitRawText("\t.frame\t$" +
217                           Twine(LowercaseString(getRegisterName(stackReg))) +
218                           "," + Twine(stackSize) + ",$" +
219                           Twine(LowercaseString(getRegisterName(returnReg))));
220 }
221
222 /// Emit Set directives.
223 const char *MipsAsmPrinter::getCurrentABIString() const {
224   switch (Subtarget->getTargetABI()) {
225   case MipsSubtarget::O32:  return "abi32";
226   case MipsSubtarget::O64:  return "abiO64";
227   case MipsSubtarget::N32:  return "abiN32";
228   case MipsSubtarget::N64:  return "abi64";
229   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
230   default: break;
231   }
232
233   llvm_unreachable("Unknown Mips ABI");
234   return NULL;
235 }
236
237 void MipsAsmPrinter::EmitFunctionEntryLabel() {
238   OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
239   OutStreamer.EmitLabel(CurrentFnSym);
240 }
241
242 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
243 /// the first basic block in the function.
244 void MipsAsmPrinter::EmitFunctionBodyStart() {
245   emitFrameDirective();
246
247   SmallString<128> Str;
248   raw_svector_ostream OS(Str);
249   printSavedRegsBitmask(OS);
250   OutStreamer.EmitRawText(OS.str());
251 }
252
253 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
254 /// the last basic block in the function.
255 void MipsAsmPrinter::EmitFunctionBodyEnd() {
256   // There are instruction for this macros, but they must
257   // always be at the function end, and we can't emit and
258   // break with BB logic.
259   OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
260   OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
261   OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
262 }
263
264
265 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
266 /// exactly one predecessor and the control transfer mechanism between
267 /// the predecessor and this block is a fall-through.
268 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
269                                                        MBB) const {
270   // The predecessor has to be immediately before this block.
271   const MachineBasicBlock *Pred = *MBB->pred_begin();
272
273   // If the predecessor is a switch statement, assume a jump table
274   // implementation, so it is not a fall through.
275   if (const BasicBlock *bb = Pred->getBasicBlock())
276     if (isa<SwitchInst>(bb->getTerminator()))
277       return false;
278
279   // If this is a landing pad, it isn't a fall through.  If it has no preds,
280   // then nothing falls through to it.
281   if (MBB->isLandingPad() || MBB->pred_empty())
282     return false;
283
284   // If there isn't exactly one predecessor, it can't be a fall through.
285   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
286   ++PI2;
287  
288   if (PI2 != MBB->pred_end())
289     return false;  
290
291   // The predecessor has to be immediately before this block.
292   if (!Pred->isLayoutSuccessor(MBB))
293     return false;
294    
295   // If the block is completely empty, then it definitely does fall through.
296   if (Pred->empty())
297     return true;
298   
299   // Otherwise, check the last instruction.
300   // Check if the last terminator is an unconditional branch.
301   MachineBasicBlock::const_iterator I = Pred->end();
302   while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
303
304   return !I->getDesc().isBarrier();
305 }
306
307 // Print out an operand for an inline asm expression.
308 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
309                                      unsigned AsmVariant,const char *ExtraCode,
310                                      raw_ostream &O) {
311   // Does this asm operand have a single letter operand modifier?
312   if (ExtraCode && ExtraCode[0])
313     return true; // Unknown modifier.
314
315   printOperand(MI, OpNo, O);
316   return false;
317 }
318
319 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
320                                            unsigned OpNum, unsigned AsmVariant,
321                                            const char *ExtraCode,
322                                            raw_ostream &O) {
323   if (ExtraCode && ExtraCode[0])
324      return true; // Unknown modifier.
325    
326   const MachineOperand &MO = MI->getOperand(OpNum);
327   assert(MO.isReg() && "unexpected inline asm memory operand");
328   O << "0($" << MipsAsmPrinter::getRegisterName(MO.getReg()) << ")";
329   return false;
330 }
331
332 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
333                                   raw_ostream &O) {
334   const MachineOperand &MO = MI->getOperand(opNum);
335   bool closeP = false;
336
337   if (MO.getTargetFlags())
338     closeP = true;
339
340   switch(MO.getTargetFlags()) {
341   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
342   case MipsII::MO_GOT_CALL: O << "%call16("; break;
343   case MipsII::MO_GOT:      O << "%got(";    break;
344   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
345   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
346   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
347   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
348   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
349   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
350   }
351
352   switch (MO.getType()) {
353     case MachineOperand::MO_Register:
354       O << '$' << LowercaseString(getRegisterName(MO.getReg()));
355       break;
356
357     case MachineOperand::MO_Immediate:
358       O << MO.getImm();
359       break;
360
361     case MachineOperand::MO_MachineBasicBlock:
362       O << *MO.getMBB()->getSymbol();
363       return;
364
365     case MachineOperand::MO_GlobalAddress:
366       O << *Mang->getSymbol(MO.getGlobal());
367       break;
368
369     case MachineOperand::MO_BlockAddress: {
370       MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
371       O << BA->getName();
372       break;
373     }
374
375     case MachineOperand::MO_ExternalSymbol:
376       O << *GetExternalSymbolSymbol(MO.getSymbolName());
377       break;
378
379     case MachineOperand::MO_JumpTableIndex:
380       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
381         << '_' << MO.getIndex();
382       break;
383
384     case MachineOperand::MO_ConstantPoolIndex:
385       O << MAI->getPrivateGlobalPrefix() << "CPI"
386         << getFunctionNumber() << "_" << MO.getIndex();
387       if (MO.getOffset())
388         O << "+" << MO.getOffset();
389       break;
390
391     default:
392       llvm_unreachable("<unknown operand type>");
393   }
394
395   if (closeP) O << ")";
396 }
397
398 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
399                                       raw_ostream &O) {
400   const MachineOperand &MO = MI->getOperand(opNum);
401   if (MO.isImm())
402     O << (unsigned short int)MO.getImm();
403   else
404     printOperand(MI, opNum, O);
405 }
406
407 void MipsAsmPrinter::
408 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
409                 const char *Modifier) {
410   // when using stack locations for not load/store instructions
411   // print the same way as all normal 3 operand instructions.
412   if (Modifier && !strcmp(Modifier, "stackloc")) {
413     printOperand(MI, opNum+1, O);
414     O << ", ";
415     printOperand(MI, opNum, O);
416     return;
417   }
418
419   // Load/Store memory operands -- imm($reg)
420   // If PIC target the target is loaded as the
421   // pattern lw $25,%call16($28)
422   printOperand(MI, opNum, O);
423   O << "(";
424   printOperand(MI, opNum+1, O);
425   O << ")";
426 }
427
428 void MipsAsmPrinter::
429 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
430                 const char *Modifier) {
431   const MachineOperand& MO = MI->getOperand(opNum);
432   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
433 }
434
435 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
436   // FIXME: Use SwitchSection.
437
438   // Tell the assembler which ABI we are using
439   OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
440
441   // TODO: handle O64 ABI
442   if (Subtarget->isABI_EABI()) {
443     if (Subtarget->isGP32bit())
444       OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
445     else
446       OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
447   }
448
449   // return to previous section
450   OutStreamer.EmitRawText(StringRef("\t.previous"));
451 }
452
453 MachineLocation
454 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
455   // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
456   assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
457   assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
458          "Unexpected MachineOperand types");
459   return MachineLocation(MI->getOperand(0).getReg(),
460                          MI->getOperand(1).getImm());
461 }
462
463 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
464                                            raw_ostream &OS) {
465   // TODO: implement
466 }
467
468 // Force static initialization.
469 extern "C" void LLVMInitializeMipsAsmPrinter() {
470   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
471   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
472 }