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