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