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