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