1 //===-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer -------------------===//
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"
17 #include "MipsAsmPrinter.h"
18 #include "MipsInstrInfo.h"
19 #include "MipsMCInstLower.h"
20 #include "InstPrinter/MipsInstPrinter.h"
21 #include "MCTargetDesc/MipsBaseInfo.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/BasicBlock.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/InlineAsm.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/DataLayout.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
46 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
47 MipsFI = MF.getInfo<MipsFunctionInfo>();
48 AsmPrinter::runOnMachineFunction(MF);
52 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
53 MCOp = MCInstLowering.LowerOperand(MO);
54 return MCOp.isValid();
57 #include "MipsGenMCPseudoLowering.inc"
59 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
60 if (MI->isDebugValue()) {
62 raw_svector_ostream OS(Str);
64 PrintDebugValueComment(MI, OS);
68 // Do any auto-generated pseudo lowerings.
69 if (emitPseudoExpansionLowering(OutStreamer, MI))
72 MachineBasicBlock::const_instr_iterator I = MI;
73 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
77 MCInstLowering.Lower(I++, TmpInst0);
79 OutStreamer.EmitInstruction(TmpInst0);
80 } while ((I != E) && I->isInsideBundle()); // Delay slot check
83 //===----------------------------------------------------------------------===//
85 // Mips Asm Directives
87 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
88 // Describe the stack frame.
90 // -- Mask directives "(f)mask bitmask, offset"
91 // Tells the assembler which registers are saved and where.
92 // bitmask - contain a little endian bitset indicating which registers are
93 // saved on function prologue (e.g. with a 0x80000000 mask, the
94 // assembler knows the register 31 (RA) is saved at prologue.
95 // offset - the position before stack pointer subtraction indicating where
96 // the first saved register on prologue is located. (e.g. with a
98 // Consider the following function prologue:
101 // .mask 0xc0000000,-8
102 // addiu $sp, $sp, -48
106 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
107 // 30 (FP) are saved at prologue. As the save order on prologue is from
108 // left to right, RA is saved first. A -8 offset means that after the
109 // stack pointer subtration, the first register in the mask (RA) will be
110 // saved at address 48-8=40.
112 //===----------------------------------------------------------------------===//
114 //===----------------------------------------------------------------------===//
116 //===----------------------------------------------------------------------===//
118 // Create a bitmask with all callee saved registers for CPU or Floating Point
119 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
120 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
121 // CPU and FPU Saved Registers Bitmasks
122 unsigned CPUBitmask = 0, FPUBitmask = 0;
123 int CPUTopSavedRegOff, FPUTopSavedRegOff;
125 // Set the CPU and FPU Bitmasks
126 const MachineFrameInfo *MFI = MF->getFrameInfo();
127 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
128 // size of stack area to which FP callee-saved regs are saved.
129 unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
130 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
131 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
132 bool HasAFGR64Reg = false;
133 unsigned CSFPRegsSize = 0;
134 unsigned i, e = CSI.size();
137 for (i = 0; i != e; ++i) {
138 unsigned Reg = CSI[i].getReg();
139 if (Mips::CPURegsRegClass.contains(Reg))
142 unsigned RegNum = getMipsRegisterNumbering(Reg);
143 if (Mips::AFGR64RegClass.contains(Reg)) {
144 FPUBitmask |= (3 << RegNum);
145 CSFPRegsSize += AFGR64RegSize;
150 FPUBitmask |= (1 << RegNum);
151 CSFPRegsSize += FGR32RegSize;
155 for (; i != e; ++i) {
156 unsigned Reg = CSI[i].getReg();
157 unsigned RegNum = getMipsRegisterNumbering(Reg);
158 CPUBitmask |= (1 << RegNum);
161 // FP Regs are saved right below where the virtual frame pointer points to.
162 FPUTopSavedRegOff = FPUBitmask ?
163 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
165 // CPU Regs are saved below FP Regs.
166 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
169 O << "\t.mask \t"; printHex32(CPUBitmask, O);
170 O << ',' << CPUTopSavedRegOff << '\n';
173 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
174 O << "," << FPUTopSavedRegOff << '\n';
177 // Print a 32 bit hex number with all numbers.
178 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
180 for (int i = 7; i >= 0; i--)
181 O.write_hex((Value & (0xF << (i*4))) >> (i*4));
184 //===----------------------------------------------------------------------===//
185 // Frame and Set directives
186 //===----------------------------------------------------------------------===//
189 void MipsAsmPrinter::emitFrameDirective() {
190 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
192 unsigned stackReg = RI.getFrameRegister(*MF);
193 unsigned returnReg = RI.getRARegister();
194 unsigned stackSize = MF->getFrameInfo()->getStackSize();
196 if (OutStreamer.hasRawTextSupport())
197 OutStreamer.EmitRawText("\t.frame\t$" +
198 StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
199 "," + Twine(stackSize) + ",$" +
200 StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
203 /// Emit Set directives.
204 const char *MipsAsmPrinter::getCurrentABIString() const {
205 switch (Subtarget->getTargetABI()) {
206 case MipsSubtarget::O32: return "abi32";
207 case MipsSubtarget::N32: return "abiN32";
208 case MipsSubtarget::N64: return "abi64";
209 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
210 default: llvm_unreachable("Unknown Mips ABI");
214 void MipsAsmPrinter::EmitFunctionEntryLabel() {
215 if (OutStreamer.hasRawTextSupport()) {
216 if (Subtarget->inMips16Mode())
217 OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
219 OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
220 // leave out until FSF available gas has micromips changes
221 // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
222 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
224 OutStreamer.EmitLabel(CurrentFnSym);
227 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
228 /// the first basic block in the function.
229 void MipsAsmPrinter::EmitFunctionBodyStart() {
230 MCInstLowering.Initialize(Mang, &MF->getContext());
232 emitFrameDirective();
234 if (OutStreamer.hasRawTextSupport()) {
235 SmallString<128> Str;
236 raw_svector_ostream OS(Str);
237 printSavedRegsBitmask(OS);
238 OutStreamer.EmitRawText(OS.str());
240 OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
241 OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
242 OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
246 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
247 /// the last basic block in the function.
248 void MipsAsmPrinter::EmitFunctionBodyEnd() {
249 // There are instruction for this macros, but they must
250 // always be at the function end, and we can't emit and
251 // break with BB logic.
252 if (OutStreamer.hasRawTextSupport()) {
253 OutStreamer.EmitRawText(StringRef("\t.set\tat"));
254 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
255 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
256 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
260 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
261 /// exactly one predecessor and the control transfer mechanism between
262 /// the predecessor and this block is a fall-through.
263 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
265 // The predecessor has to be immediately before this block.
266 const MachineBasicBlock *Pred = *MBB->pred_begin();
268 // If the predecessor is a switch statement, assume a jump table
269 // implementation, so it is not a fall through.
270 if (const BasicBlock *bb = Pred->getBasicBlock())
271 if (isa<SwitchInst>(bb->getTerminator()))
274 // If this is a landing pad, it isn't a fall through. If it has no preds,
275 // then nothing falls through to it.
276 if (MBB->isLandingPad() || MBB->pred_empty())
279 // If there isn't exactly one predecessor, it can't be a fall through.
280 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
283 if (PI2 != MBB->pred_end())
286 // The predecessor has to be immediately before this block.
287 if (!Pred->isLayoutSuccessor(MBB))
290 // If the block is completely empty, then it definitely does fall through.
294 // Otherwise, check the last instruction.
295 // Check if the last terminator is an unconditional branch.
296 MachineBasicBlock::const_iterator I = Pred->end();
297 while (I != Pred->begin() && !(--I)->isTerminator()) ;
299 return !I->isBarrier();
302 // Print out an operand for an inline asm expression.
303 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
304 unsigned AsmVariant,const char *ExtraCode,
306 // Does this asm operand have a single letter operand modifier?
307 if (ExtraCode && ExtraCode[0]) {
308 if (ExtraCode[1] != 0) return true; // Unknown modifier.
310 const MachineOperand &MO = MI->getOperand(OpNum);
311 switch (ExtraCode[0]) {
313 // See if this is a generic print operand
314 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
315 case 'X': // hex const int
316 if ((MO.getType()) != MachineOperand::MO_Immediate)
318 O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
320 case 'x': // hex const int (low 16 bits)
321 if ((MO.getType()) != MachineOperand::MO_Immediate)
323 O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
325 case 'd': // decimal const int
326 if ((MO.getType()) != MachineOperand::MO_Immediate)
330 case 'm': // decimal const int minus 1
331 if ((MO.getType()) != MachineOperand::MO_Immediate)
333 O << MO.getImm() - 1;
336 // $0 if zero, regular printing otherwise
337 if (MO.getType() != MachineOperand::MO_Immediate)
339 int64_t Val = MO.getImm();
346 case 'D': // Second part of a double word register operand
347 case 'L': // Low order register of a double word register operand
348 case 'M': // High order register of a double word register operand
352 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
353 if (!FlagsOP.isImm())
355 unsigned Flags = FlagsOP.getImm();
356 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
357 // Number of registers represented by this operand. We are looking
358 // for 2 for 32 bit mode and 1 for 64 bit mode.
360 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
361 unsigned Reg = MO.getReg();
362 O << '$' << MipsInstPrinter::getRegisterName(Reg);
368 unsigned RegOp = OpNum;
369 if (!Subtarget->isGP64bit()){
370 // Endianess reverses which register holds the high or low value
372 switch(ExtraCode[0]) {
374 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
377 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
379 case 'D': // Always the second part
382 if (RegOp >= MI->getNumOperands())
384 const MachineOperand &MO = MI->getOperand(RegOp);
387 unsigned Reg = MO.getReg();
388 O << '$' << MipsInstPrinter::getRegisterName(Reg);
395 printOperand(MI, OpNum, O);
399 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
400 unsigned OpNum, unsigned AsmVariant,
401 const char *ExtraCode,
403 if (ExtraCode && ExtraCode[0])
404 return true; // Unknown modifier.
406 const MachineOperand &MO = MI->getOperand(OpNum);
407 assert(MO.isReg() && "unexpected inline asm memory operand");
408 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
413 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
415 const MachineOperand &MO = MI->getOperand(opNum);
418 if (MO.getTargetFlags())
421 switch(MO.getTargetFlags()) {
422 case MipsII::MO_GPREL: O << "%gp_rel("; break;
423 case MipsII::MO_GOT_CALL: O << "%call16("; break;
424 case MipsII::MO_GOT: O << "%got("; break;
425 case MipsII::MO_ABS_HI: O << "%hi("; break;
426 case MipsII::MO_ABS_LO: O << "%lo("; break;
427 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
428 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
429 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
430 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
431 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
432 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
433 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
434 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
435 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
438 switch (MO.getType()) {
439 case MachineOperand::MO_Register:
441 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
444 case MachineOperand::MO_Immediate:
448 case MachineOperand::MO_MachineBasicBlock:
449 O << *MO.getMBB()->getSymbol();
452 case MachineOperand::MO_GlobalAddress:
453 O << *Mang->getSymbol(MO.getGlobal());
456 case MachineOperand::MO_BlockAddress: {
457 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
462 case MachineOperand::MO_ExternalSymbol:
463 O << *GetExternalSymbolSymbol(MO.getSymbolName());
466 case MachineOperand::MO_JumpTableIndex:
467 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
468 << '_' << MO.getIndex();
471 case MachineOperand::MO_ConstantPoolIndex:
472 O << MAI->getPrivateGlobalPrefix() << "CPI"
473 << getFunctionNumber() << "_" << MO.getIndex();
475 O << "+" << MO.getOffset();
479 llvm_unreachable("<unknown operand type>");
482 if (closeP) O << ")";
485 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
487 const MachineOperand &MO = MI->getOperand(opNum);
489 O << (unsigned short int)MO.getImm();
491 printOperand(MI, opNum, O);
494 void MipsAsmPrinter::
495 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
496 // Load/Store memory operands -- imm($reg)
497 // If PIC target the target is loaded as the
498 // pattern lw $25,%call16($28)
499 printOperand(MI, opNum+1, O);
501 printOperand(MI, opNum, O);
505 void MipsAsmPrinter::
506 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
507 // when using stack locations for not load/store instructions
508 // print the same way as all normal 3 operand instructions.
509 printOperand(MI, opNum, O);
511 printOperand(MI, opNum+1, O);
515 void MipsAsmPrinter::
516 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
517 const char *Modifier) {
518 const MachineOperand &MO = MI->getOperand(opNum);
519 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
522 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
523 // FIXME: Use SwitchSection.
525 // Tell the assembler which ABI we are using
526 if (OutStreamer.hasRawTextSupport())
527 OutStreamer.EmitRawText("\t.section .mdebug." +
528 Twine(getCurrentABIString()));
530 // TODO: handle O64 ABI
531 if (OutStreamer.hasRawTextSupport()) {
532 if (Subtarget->isABI_EABI()) {
533 if (Subtarget->isGP32bit())
534 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
536 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
540 // return to previous section
541 if (OutStreamer.hasRawTextSupport())
542 OutStreamer.EmitRawText(StringRef("\t.previous"));
546 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
547 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
548 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
549 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
550 "Unexpected MachineOperand types");
551 return MachineLocation(MI->getOperand(0).getReg(),
552 MI->getOperand(1).getImm());
555 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
560 // Force static initialization.
561 extern "C" void LLVMInitializeMipsAsmPrinter() {
562 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
563 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
564 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
565 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);