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