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