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