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