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