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"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MCTargetDesc/MipsELFStreamer.h"
20 #include "MipsAsmPrinter.h"
21 #include "MipsInstrInfo.h"
22 #include "MipsMCInstLower.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Twine.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/IR/BasicBlock.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCInst.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/ELF.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/Mangler.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
48 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
49 // Initialize TargetLoweringObjectFile.
50 if (Subtarget->allowMixed16_32())
51 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
52 .Initialize(OutContext, TM);
53 MipsFI = MF.getInfo<MipsFunctionInfo>();
54 AsmPrinter::runOnMachineFunction(MF);
58 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
59 MCOp = MCInstLowering.LowerOperand(MO);
60 return MCOp.isValid();
63 #include "MipsGenMCPseudoLowering.inc"
65 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
66 if (MI->isDebugValue()) {
68 raw_svector_ostream OS(Str);
70 PrintDebugValueComment(MI, OS);
74 MachineBasicBlock::const_instr_iterator I = MI;
75 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
78 // Do any auto-generated pseudo lowerings.
79 if (emitPseudoExpansionLowering(OutStreamer, &*I))
82 // The inMips16Mode() test is not permanent.
83 // Some instructions are marked as pseudo right now which
84 // would make the test fail for the wrong reason but
85 // that will be fixed soon. We need this here because we are
86 // removing another test for this situation downstream in the
89 if (I->isPseudo() && !Subtarget->inMips16Mode())
90 llvm_unreachable("Pseudo opcode found in EmitInstruction()");
93 MCInstLowering.Lower(I, TmpInst0);
94 OutStreamer.EmitInstruction(TmpInst0);
95 } while ((++I != E) && I->isInsideBundle()); // Delay slot check
98 //===----------------------------------------------------------------------===//
100 // Mips Asm Directives
102 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
103 // Describe the stack frame.
105 // -- Mask directives "(f)mask bitmask, offset"
106 // Tells the assembler which registers are saved and where.
107 // bitmask - contain a little endian bitset indicating which registers are
108 // saved on function prologue (e.g. with a 0x80000000 mask, the
109 // assembler knows the register 31 (RA) is saved at prologue.
110 // offset - the position before stack pointer subtraction indicating where
111 // the first saved register on prologue is located. (e.g. with a
113 // Consider the following function prologue:
116 // .mask 0xc0000000,-8
117 // addiu $sp, $sp, -48
121 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
122 // 30 (FP) are saved at prologue. As the save order on prologue is from
123 // left to right, RA is saved first. A -8 offset means that after the
124 // stack pointer subtration, the first register in the mask (RA) will be
125 // saved at address 48-8=40.
127 //===----------------------------------------------------------------------===//
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
133 // Create a bitmask with all callee saved registers for CPU or Floating Point
134 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
135 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
136 // CPU and FPU Saved Registers Bitmasks
137 unsigned CPUBitmask = 0, FPUBitmask = 0;
138 int CPUTopSavedRegOff, FPUTopSavedRegOff;
140 // Set the CPU and FPU Bitmasks
141 const MachineFrameInfo *MFI = MF->getFrameInfo();
142 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
143 // size of stack area to which FP callee-saved regs are saved.
144 unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
145 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
146 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
147 bool HasAFGR64Reg = false;
148 unsigned CSFPRegsSize = 0;
149 unsigned i, e = CSI.size();
152 for (i = 0; i != e; ++i) {
153 unsigned Reg = CSI[i].getReg();
154 if (Mips::CPURegsRegClass.contains(Reg))
157 unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
158 if (Mips::AFGR64RegClass.contains(Reg)) {
159 FPUBitmask |= (3 << RegNum);
160 CSFPRegsSize += AFGR64RegSize;
165 FPUBitmask |= (1 << RegNum);
166 CSFPRegsSize += FGR32RegSize;
170 for (; i != e; ++i) {
171 unsigned Reg = CSI[i].getReg();
172 unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
173 CPUBitmask |= (1 << RegNum);
176 // FP Regs are saved right below where the virtual frame pointer points to.
177 FPUTopSavedRegOff = FPUBitmask ?
178 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
180 // CPU Regs are saved below FP Regs.
181 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
184 O << "\t.mask \t"; printHex32(CPUBitmask, O);
185 O << ',' << CPUTopSavedRegOff << '\n';
188 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
189 O << "," << FPUTopSavedRegOff << '\n';
192 // Print a 32 bit hex number with all numbers.
193 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
195 for (int i = 7; i >= 0; i--)
196 O.write_hex((Value & (0xF << (i*4))) >> (i*4));
199 //===----------------------------------------------------------------------===//
200 // Frame and Set directives
201 //===----------------------------------------------------------------------===//
204 void MipsAsmPrinter::emitFrameDirective() {
205 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
207 unsigned stackReg = RI.getFrameRegister(*MF);
208 unsigned returnReg = RI.getRARegister();
209 unsigned stackSize = MF->getFrameInfo()->getStackSize();
211 if (OutStreamer.hasRawTextSupport())
212 OutStreamer.EmitRawText("\t.frame\t$" +
213 StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
214 "," + Twine(stackSize) + ",$" +
215 StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
218 /// Emit Set directives.
219 const char *MipsAsmPrinter::getCurrentABIString() const {
220 switch (Subtarget->getTargetABI()) {
221 case MipsSubtarget::O32: return "abi32";
222 case MipsSubtarget::N32: return "abiN32";
223 case MipsSubtarget::N64: return "abi64";
224 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
225 default: llvm_unreachable("Unknown Mips ABI");
229 void MipsAsmPrinter::EmitFunctionEntryLabel() {
230 if (OutStreamer.hasRawTextSupport()) {
231 if (Subtarget->inMips16Mode())
232 OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
234 OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
235 // leave out until FSF available gas has micromips changes
236 // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
237 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
240 if (Subtarget->inMicroMipsMode())
241 if (MipsELFStreamer *MES = dyn_cast<MipsELFStreamer>(&OutStreamer))
242 MES->emitMipsSTOCG(*Subtarget, CurrentFnSym,
243 (unsigned)ELF::STO_MIPS_MICROMIPS);
244 OutStreamer.EmitLabel(CurrentFnSym);
247 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
248 /// the first basic block in the function.
249 void MipsAsmPrinter::EmitFunctionBodyStart() {
250 MCInstLowering.Initialize(Mang, &MF->getContext());
252 emitFrameDirective();
254 if (OutStreamer.hasRawTextSupport()) {
255 SmallString<128> Str;
256 raw_svector_ostream OS(Str);
257 printSavedRegsBitmask(OS);
258 OutStreamer.EmitRawText(OS.str());
259 if (!Subtarget->inMips16Mode()) {
260 OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
261 OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
262 OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
267 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
268 /// the last basic block in the function.
269 void MipsAsmPrinter::EmitFunctionBodyEnd() {
270 // There are instruction for this macros, but they must
271 // always be at the function end, and we can't emit and
272 // break with BB logic.
273 if (OutStreamer.hasRawTextSupport()) {
274 if (!Subtarget->inMips16Mode()) {
275 OutStreamer.EmitRawText(StringRef("\t.set\tat"));
276 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
277 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
279 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
283 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
284 /// exactly one predecessor and the control transfer mechanism between
285 /// the predecessor and this block is a fall-through.
286 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
288 // The predecessor has to be immediately before this block.
289 const MachineBasicBlock *Pred = *MBB->pred_begin();
291 // If the predecessor is a switch statement, assume a jump table
292 // implementation, so it is not a fall through.
293 if (const BasicBlock *bb = Pred->getBasicBlock())
294 if (isa<SwitchInst>(bb->getTerminator()))
297 // If this is a landing pad, it isn't a fall through. If it has no preds,
298 // then nothing falls through to it.
299 if (MBB->isLandingPad() || MBB->pred_empty())
302 // If there isn't exactly one predecessor, it can't be a fall through.
303 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
306 if (PI2 != MBB->pred_end())
309 // The predecessor has to be immediately before this block.
310 if (!Pred->isLayoutSuccessor(MBB))
313 // If the block is completely empty, then it definitely does fall through.
317 // Otherwise, check the last instruction.
318 // Check if the last terminator is an unconditional branch.
319 MachineBasicBlock::const_iterator I = Pred->end();
320 while (I != Pred->begin() && !(--I)->isTerminator()) ;
322 return !I->isBarrier();
325 // Print out an operand for an inline asm expression.
326 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
327 unsigned AsmVariant,const char *ExtraCode,
329 // Does this asm operand have a single letter operand modifier?
330 if (ExtraCode && ExtraCode[0]) {
331 if (ExtraCode[1] != 0) return true; // Unknown modifier.
333 const MachineOperand &MO = MI->getOperand(OpNum);
334 switch (ExtraCode[0]) {
336 // See if this is a generic print operand
337 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
338 case 'X': // hex const int
339 if ((MO.getType()) != MachineOperand::MO_Immediate)
341 O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
343 case 'x': // hex const int (low 16 bits)
344 if ((MO.getType()) != MachineOperand::MO_Immediate)
346 O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
348 case 'd': // decimal const int
349 if ((MO.getType()) != MachineOperand::MO_Immediate)
353 case 'm': // decimal const int minus 1
354 if ((MO.getType()) != MachineOperand::MO_Immediate)
356 O << MO.getImm() - 1;
359 // $0 if zero, regular printing otherwise
360 if (MO.getType() != MachineOperand::MO_Immediate)
362 int64_t Val = MO.getImm();
369 case 'D': // Second part of a double word register operand
370 case 'L': // Low order register of a double word register operand
371 case 'M': // High order register of a double word register operand
375 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
376 if (!FlagsOP.isImm())
378 unsigned Flags = FlagsOP.getImm();
379 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
380 // Number of registers represented by this operand. We are looking
381 // for 2 for 32 bit mode and 1 for 64 bit mode.
383 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
384 unsigned Reg = MO.getReg();
385 O << '$' << MipsInstPrinter::getRegisterName(Reg);
391 unsigned RegOp = OpNum;
392 if (!Subtarget->isGP64bit()){
393 // Endianess reverses which register holds the high or low value
395 switch(ExtraCode[0]) {
397 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
400 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
402 case 'D': // Always the second part
405 if (RegOp >= MI->getNumOperands())
407 const MachineOperand &MO = MI->getOperand(RegOp);
410 unsigned Reg = MO.getReg();
411 O << '$' << MipsInstPrinter::getRegisterName(Reg);
418 printOperand(MI, OpNum, O);
422 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
423 unsigned OpNum, unsigned AsmVariant,
424 const char *ExtraCode,
426 if (ExtraCode && ExtraCode[0])
427 return true; // Unknown modifier.
429 const MachineOperand &MO = MI->getOperand(OpNum);
430 assert(MO.isReg() && "unexpected inline asm memory operand");
431 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
436 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
438 const MachineOperand &MO = MI->getOperand(opNum);
441 if (MO.getTargetFlags())
444 switch(MO.getTargetFlags()) {
445 case MipsII::MO_GPREL: O << "%gp_rel("; break;
446 case MipsII::MO_GOT_CALL: O << "%call16("; break;
447 case MipsII::MO_GOT: O << "%got("; break;
448 case MipsII::MO_ABS_HI: O << "%hi("; break;
449 case MipsII::MO_ABS_LO: O << "%lo("; break;
450 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
451 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
452 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
453 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
454 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
455 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
456 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
457 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
458 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
461 switch (MO.getType()) {
462 case MachineOperand::MO_Register:
464 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
467 case MachineOperand::MO_Immediate:
471 case MachineOperand::MO_MachineBasicBlock:
472 O << *MO.getMBB()->getSymbol();
475 case MachineOperand::MO_GlobalAddress:
476 O << *Mang->getSymbol(MO.getGlobal());
479 case MachineOperand::MO_BlockAddress: {
480 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
485 case MachineOperand::MO_ExternalSymbol:
486 O << *GetExternalSymbolSymbol(MO.getSymbolName());
489 case MachineOperand::MO_JumpTableIndex:
490 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
491 << '_' << MO.getIndex();
494 case MachineOperand::MO_ConstantPoolIndex:
495 O << MAI->getPrivateGlobalPrefix() << "CPI"
496 << getFunctionNumber() << "_" << MO.getIndex();
498 O << "+" << MO.getOffset();
502 llvm_unreachable("<unknown operand type>");
505 if (closeP) O << ")";
508 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
510 const MachineOperand &MO = MI->getOperand(opNum);
512 O << (unsigned short int)MO.getImm();
514 printOperand(MI, opNum, O);
517 void MipsAsmPrinter::
518 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
519 // Load/Store memory operands -- imm($reg)
520 // If PIC target the target is loaded as the
521 // pattern lw $25,%call16($28)
522 printOperand(MI, opNum+1, O);
524 printOperand(MI, opNum, O);
528 void MipsAsmPrinter::
529 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
530 // when using stack locations for not load/store instructions
531 // print the same way as all normal 3 operand instructions.
532 printOperand(MI, opNum, O);
534 printOperand(MI, opNum+1, O);
538 void MipsAsmPrinter::
539 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
540 const char *Modifier) {
541 const MachineOperand &MO = MI->getOperand(opNum);
542 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
545 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
546 // FIXME: Use SwitchSection.
548 // Tell the assembler which ABI we are using
549 if (OutStreamer.hasRawTextSupport())
550 OutStreamer.EmitRawText("\t.section .mdebug." +
551 Twine(getCurrentABIString()));
553 // TODO: handle O64 ABI
554 if (OutStreamer.hasRawTextSupport()) {
555 if (Subtarget->isABI_EABI()) {
556 if (Subtarget->isGP32bit())
557 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
559 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
563 // return to previous section
564 if (OutStreamer.hasRawTextSupport())
565 OutStreamer.EmitRawText(StringRef("\t.previous"));
569 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
571 if (OutStreamer.hasRawTextSupport()) return;
573 // Emit Mips ELF register info
574 Subtarget->getMReginfo().emitMipsReginfoSectionCG(
575 OutStreamer, getObjFileLowering(), *Subtarget);
576 if (MipsELFStreamer *MES = dyn_cast<MipsELFStreamer>(&OutStreamer))
577 MES->emitELFHeaderFlagsCG(*Subtarget);
581 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
582 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
583 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
584 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
585 "Unexpected MachineOperand types");
586 return MachineLocation(MI->getOperand(0).getReg(),
587 MI->getOperand(1).getImm());
590 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
595 // Force static initialization.
596 extern "C" void LLVMInitializeMipsAsmPrinter() {
597 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
598 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
599 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
600 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);