1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-asm-printer"
16 #include "MipsAsmPrinter.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"
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;
53 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
55 raw_svector_ostream OS(Str);
57 if (MI->isDebugValue()) {
58 PrintDebugValueComment(MI, OS);
62 MipsMCInstLower MCInstLowering(Mang, *MF, *this);
63 unsigned Opc = MI->getOpcode();
65 MCInstLowering.Lower(MI, TmpInst0);
67 // Enclose unaligned load or store with .macro & .nomacro directives.
68 if (isUnalignedLoadStore(Opc)) {
70 Directive.setOpcode(Mips::MACRO);
71 OutStreamer.EmitInstruction(Directive);
72 OutStreamer.EmitInstruction(TmpInst0);
73 Directive.setOpcode(Mips::NOMACRO);
74 OutStreamer.EmitInstruction(Directive);
78 OutStreamer.EmitInstruction(TmpInst0);
81 //===----------------------------------------------------------------------===//
83 // Mips Asm Directives
85 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
86 // Describe the stack frame.
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
96 // Consider the following function prologue:
99 // .mask 0xc0000000,-8
100 // addiu $sp, $sp, -48
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.
110 //===----------------------------------------------------------------------===//
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
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;
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();
135 for (i = 0; i != e; ++i) {
136 unsigned Reg = CSI[i].getReg();
137 if (Mips::CPURegsRegisterClass->contains(Reg))
140 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
141 if (Mips::AFGR64RegisterClass->contains(Reg)) {
142 FPUBitmask |= (3 << RegNum);
143 CSFPRegsSize += AFGR64RegSize;
148 FPUBitmask |= (1 << RegNum);
149 CSFPRegsSize += FGR32RegSize;
153 for (; i != e; ++i) {
154 unsigned Reg = CSI[i].getReg();
155 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
156 CPUBitmask |= (1 << RegNum);
159 // FP Regs are saved right below where the virtual frame pointer points to.
160 FPUTopSavedRegOff = FPUBitmask ?
161 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
163 // CPU Regs are saved below FP Regs.
164 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
167 O << "\t.mask \t"; printHex32(CPUBitmask, O);
168 O << ',' << CPUTopSavedRegOff << '\n';
171 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
172 O << "," << FPUTopSavedRegOff << '\n';
175 // Print a 32 bit hex number with all numbers.
176 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
178 for (int i = 7; i >= 0; i--)
179 O.write_hex((Value & (0xF << (i*4))) >> (i*4));
182 //===----------------------------------------------------------------------===//
183 // Frame and Set directives
184 //===----------------------------------------------------------------------===//
187 void MipsAsmPrinter::emitFrameDirective() {
188 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
190 unsigned stackReg = RI.getFrameRegister(*MF);
191 unsigned returnReg = RI.getRARegister();
192 unsigned stackSize = MF->getFrameInfo()->getStackSize();
194 OutStreamer.EmitRawText("\t.frame\t$" +
195 StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
196 "," + Twine(stackSize) + ",$" +
197 StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
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
210 llvm_unreachable("Unknown Mips ABI");
214 void MipsAsmPrinter::EmitFunctionEntryLabel() {
215 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
216 OutStreamer.EmitLabel(CurrentFnSym);
219 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
220 /// the first basic block in the function.
221 void MipsAsmPrinter::EmitFunctionBodyStart() {
222 emitFrameDirective();
224 SmallString<128> Str;
225 raw_svector_ostream OS(Str);
226 printSavedRegsBitmask(OS);
227 OutStreamer.EmitRawText(OS.str());
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()));
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*
247 // The predecessor has to be immediately before this block.
248 const MachineBasicBlock *Pred = *MBB->pred_begin();
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()))
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())
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;
265 if (PI2 != MBB->pred_end())
268 // The predecessor has to be immediately before this block.
269 if (!Pred->isLayoutSuccessor(MBB))
272 // If the block is completely empty, then it definitely does fall through.
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()) ;
281 return !I->getDesc().isBarrier();
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,
288 // Does this asm operand have a single letter operand modifier?
289 if (ExtraCode && ExtraCode[0])
290 return true; // Unknown modifier.
292 printOperand(MI, OpNo, O);
296 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
297 unsigned OpNum, unsigned AsmVariant,
298 const char *ExtraCode,
300 if (ExtraCode && ExtraCode[0])
301 return true; // Unknown modifier.
303 const MachineOperand &MO = MI->getOperand(OpNum);
304 assert(MO.isReg() && "unexpected inline asm memory operand");
305 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
309 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
311 const MachineOperand &MO = MI->getOperand(opNum);
314 if (MO.getTargetFlags())
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;
334 switch (MO.getType()) {
335 case MachineOperand::MO_Register:
337 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
340 case MachineOperand::MO_Immediate:
344 case MachineOperand::MO_MachineBasicBlock:
345 O << *MO.getMBB()->getSymbol();
348 case MachineOperand::MO_GlobalAddress:
349 O << *Mang->getSymbol(MO.getGlobal());
352 case MachineOperand::MO_BlockAddress: {
353 MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
358 case MachineOperand::MO_ExternalSymbol:
359 O << *GetExternalSymbolSymbol(MO.getSymbolName());
362 case MachineOperand::MO_JumpTableIndex:
363 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
364 << '_' << MO.getIndex();
367 case MachineOperand::MO_ConstantPoolIndex:
368 O << MAI->getPrivateGlobalPrefix() << "CPI"
369 << getFunctionNumber() << "_" << MO.getIndex();
371 O << "+" << MO.getOffset();
375 llvm_unreachable("<unknown operand type>");
378 if (closeP) O << ")";
381 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
383 const MachineOperand &MO = MI->getOperand(opNum);
385 O << (unsigned short int)MO.getImm();
387 printOperand(MI, opNum, O);
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);
397 printOperand(MI, opNum, O);
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);
407 printOperand(MI, opNum+1, O);
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());
418 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
419 // FIXME: Use SwitchSection.
421 // Tell the assembler which ABI we are using
422 OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
424 // TODO: handle O64 ABI
425 if (Subtarget->isABI_EABI()) {
426 if (Subtarget->isGP32bit())
427 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
429 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
432 // return to previous section
433 OutStreamer.EmitRawText(StringRef("\t.previous"));
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());
446 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
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);