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