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/TargetRegistry.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
47 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
48 MipsFI = MF.getInfo<MipsFunctionInfo>();
49 AsmPrinter::runOnMachineFunction(MF);
53 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
54 MCOp = MCInstLowering.LowerOperand(MO);
55 return MCOp.isValid();
58 #include "MipsGenMCPseudoLowering.inc"
60 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
61 if (MI->isDebugValue()) {
63 raw_svector_ostream OS(Str);
65 PrintDebugValueComment(MI, OS);
69 // Do any auto-generated pseudo lowerings.
70 if (emitPseudoExpansionLowering(OutStreamer, MI))
73 MachineBasicBlock::const_instr_iterator I = MI;
74 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
78 MCInstLowering.Lower(I++, TmpInst0);
80 OutStreamer.EmitInstruction(TmpInst0);
81 } while ((I != E) && I->isInsideBundle()); // Delay slot check
84 //===----------------------------------------------------------------------===//
86 // Mips Asm Directives
88 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
89 // Describe the stack frame.
91 // -- Mask directives "(f)mask bitmask, offset"
92 // Tells the assembler which registers are saved and where.
93 // bitmask - contain a little endian bitset indicating which registers are
94 // saved on function prologue (e.g. with a 0x80000000 mask, the
95 // assembler knows the register 31 (RA) is saved at prologue.
96 // offset - the position before stack pointer subtraction indicating where
97 // the first saved register on prologue is located. (e.g. with a
99 // Consider the following function prologue:
102 // .mask 0xc0000000,-8
103 // addiu $sp, $sp, -48
107 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
108 // 30 (FP) are saved at prologue. As the save order on prologue is from
109 // left to right, RA is saved first. A -8 offset means that after the
110 // stack pointer subtration, the first register in the mask (RA) will be
111 // saved at address 48-8=40.
113 //===----------------------------------------------------------------------===//
115 //===----------------------------------------------------------------------===//
117 //===----------------------------------------------------------------------===//
119 // Create a bitmask with all callee saved registers for CPU or Floating Point
120 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
121 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
122 // CPU and FPU Saved Registers Bitmasks
123 unsigned CPUBitmask = 0, FPUBitmask = 0;
124 int CPUTopSavedRegOff, FPUTopSavedRegOff;
126 // Set the CPU and FPU Bitmasks
127 const MachineFrameInfo *MFI = MF->getFrameInfo();
128 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
129 // size of stack area to which FP callee-saved regs are saved.
130 unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
131 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
132 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
133 bool HasAFGR64Reg = false;
134 unsigned CSFPRegsSize = 0;
135 unsigned i, e = CSI.size();
138 for (i = 0; i != e; ++i) {
139 unsigned Reg = CSI[i].getReg();
140 if (Mips::CPURegsRegClass.contains(Reg))
143 unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
144 if (Mips::AFGR64RegClass.contains(Reg)) {
145 FPUBitmask |= (3 << RegNum);
146 CSFPRegsSize += AFGR64RegSize;
151 FPUBitmask |= (1 << RegNum);
152 CSFPRegsSize += FGR32RegSize;
156 for (; i != e; ++i) {
157 unsigned Reg = CSI[i].getReg();
158 unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
159 CPUBitmask |= (1 << RegNum);
162 // FP Regs are saved right below where the virtual frame pointer points to.
163 FPUTopSavedRegOff = FPUBitmask ?
164 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
166 // CPU Regs are saved below FP Regs.
167 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
170 O << "\t.mask \t"; printHex32(CPUBitmask, O);
171 O << ',' << CPUTopSavedRegOff << '\n';
174 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
175 O << "," << FPUTopSavedRegOff << '\n';
178 // Print a 32 bit hex number with all numbers.
179 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
181 for (int i = 7; i >= 0; i--)
182 O.write_hex((Value & (0xF << (i*4))) >> (i*4));
185 //===----------------------------------------------------------------------===//
186 // Frame and Set directives
187 //===----------------------------------------------------------------------===//
190 void MipsAsmPrinter::emitFrameDirective() {
191 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
193 unsigned stackReg = RI.getFrameRegister(*MF);
194 unsigned returnReg = RI.getRARegister();
195 unsigned stackSize = MF->getFrameInfo()->getStackSize();
197 if (OutStreamer.hasRawTextSupport())
198 OutStreamer.EmitRawText("\t.frame\t$" +
199 StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
200 "," + Twine(stackSize) + ",$" +
201 StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
204 /// Emit Set directives.
205 const char *MipsAsmPrinter::getCurrentABIString() const {
206 switch (Subtarget->getTargetABI()) {
207 case MipsSubtarget::O32: return "abi32";
208 case MipsSubtarget::N32: return "abiN32";
209 case MipsSubtarget::N64: return "abi64";
210 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
211 default: llvm_unreachable("Unknown Mips ABI");
215 void MipsAsmPrinter::EmitFunctionEntryLabel() {
216 if (OutStreamer.hasRawTextSupport()) {
217 if (Subtarget->inMips16Mode())
218 OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
220 OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
221 // leave out until FSF available gas has micromips changes
222 // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
223 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
225 OutStreamer.EmitLabel(CurrentFnSym);
228 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
229 /// the first basic block in the function.
230 void MipsAsmPrinter::EmitFunctionBodyStart() {
231 MCInstLowering.Initialize(Mang, &MF->getContext());
233 emitFrameDirective();
235 if (OutStreamer.hasRawTextSupport()) {
236 SmallString<128> Str;
237 raw_svector_ostream OS(Str);
238 printSavedRegsBitmask(OS);
239 OutStreamer.EmitRawText(OS.str());
241 OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
242 OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
243 OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
247 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
248 /// the last basic block in the function.
249 void MipsAsmPrinter::EmitFunctionBodyEnd() {
250 // There are instruction for this macros, but they must
251 // always be at the function end, and we can't emit and
252 // break with BB logic.
253 if (OutStreamer.hasRawTextSupport()) {
254 OutStreamer.EmitRawText(StringRef("\t.set\tat"));
255 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
256 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
257 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
261 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
262 /// exactly one predecessor and the control transfer mechanism between
263 /// the predecessor and this block is a fall-through.
264 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
266 // The predecessor has to be immediately before this block.
267 const MachineBasicBlock *Pred = *MBB->pred_begin();
269 // If the predecessor is a switch statement, assume a jump table
270 // implementation, so it is not a fall through.
271 if (const BasicBlock *bb = Pred->getBasicBlock())
272 if (isa<SwitchInst>(bb->getTerminator()))
275 // If this is a landing pad, it isn't a fall through. If it has no preds,
276 // then nothing falls through to it.
277 if (MBB->isLandingPad() || MBB->pred_empty())
280 // If there isn't exactly one predecessor, it can't be a fall through.
281 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
284 if (PI2 != MBB->pred_end())
287 // The predecessor has to be immediately before this block.
288 if (!Pred->isLayoutSuccessor(MBB))
291 // If the block is completely empty, then it definitely does fall through.
295 // Otherwise, check the last instruction.
296 // Check if the last terminator is an unconditional branch.
297 MachineBasicBlock::const_iterator I = Pred->end();
298 while (I != Pred->begin() && !(--I)->isTerminator()) ;
300 return !I->isBarrier();
303 // Print out an operand for an inline asm expression.
304 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
305 unsigned AsmVariant,const char *ExtraCode,
307 // Does this asm operand have a single letter operand modifier?
308 if (ExtraCode && ExtraCode[0]) {
309 if (ExtraCode[1] != 0) return true; // Unknown modifier.
311 const MachineOperand &MO = MI->getOperand(OpNum);
312 switch (ExtraCode[0]) {
314 // See if this is a generic print operand
315 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
316 case 'X': // hex const int
317 if ((MO.getType()) != MachineOperand::MO_Immediate)
319 O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
321 case 'x': // hex const int (low 16 bits)
322 if ((MO.getType()) != MachineOperand::MO_Immediate)
324 O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
326 case 'd': // decimal const int
327 if ((MO.getType()) != MachineOperand::MO_Immediate)
331 case 'm': // decimal const int minus 1
332 if ((MO.getType()) != MachineOperand::MO_Immediate)
334 O << MO.getImm() - 1;
337 // $0 if zero, regular printing otherwise
338 if (MO.getType() != MachineOperand::MO_Immediate)
340 int64_t Val = MO.getImm();
347 case 'D': // Second part of a double word register operand
348 case 'L': // Low order register of a double word register operand
349 case 'M': // High order register of a double word register operand
353 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
354 if (!FlagsOP.isImm())
356 unsigned Flags = FlagsOP.getImm();
357 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
358 // Number of registers represented by this operand. We are looking
359 // for 2 for 32 bit mode and 1 for 64 bit mode.
361 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
362 unsigned Reg = MO.getReg();
363 O << '$' << MipsInstPrinter::getRegisterName(Reg);
369 unsigned RegOp = OpNum;
370 if (!Subtarget->isGP64bit()){
371 // Endianess reverses which register holds the high or low value
373 switch(ExtraCode[0]) {
375 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
378 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
380 case 'D': // Always the second part
383 if (RegOp >= MI->getNumOperands())
385 const MachineOperand &MO = MI->getOperand(RegOp);
388 unsigned Reg = MO.getReg();
389 O << '$' << MipsInstPrinter::getRegisterName(Reg);
396 printOperand(MI, OpNum, O);
400 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
401 unsigned OpNum, unsigned AsmVariant,
402 const char *ExtraCode,
404 if (ExtraCode && ExtraCode[0])
405 return true; // Unknown modifier.
407 const MachineOperand &MO = MI->getOperand(OpNum);
408 assert(MO.isReg() && "unexpected inline asm memory operand");
409 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
414 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
416 const MachineOperand &MO = MI->getOperand(opNum);
419 if (MO.getTargetFlags())
422 switch(MO.getTargetFlags()) {
423 case MipsII::MO_GPREL: O << "%gp_rel("; break;
424 case MipsII::MO_GOT_CALL: O << "%call16("; break;
425 case MipsII::MO_GOT: O << "%got("; break;
426 case MipsII::MO_ABS_HI: O << "%hi("; break;
427 case MipsII::MO_ABS_LO: O << "%lo("; break;
428 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
429 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
430 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
431 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
432 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
433 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
434 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
435 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
436 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
439 switch (MO.getType()) {
440 case MachineOperand::MO_Register:
442 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
445 case MachineOperand::MO_Immediate:
449 case MachineOperand::MO_MachineBasicBlock:
450 O << *MO.getMBB()->getSymbol();
453 case MachineOperand::MO_GlobalAddress:
454 O << *Mang->getSymbol(MO.getGlobal());
457 case MachineOperand::MO_BlockAddress: {
458 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
463 case MachineOperand::MO_ExternalSymbol:
464 O << *GetExternalSymbolSymbol(MO.getSymbolName());
467 case MachineOperand::MO_JumpTableIndex:
468 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
469 << '_' << MO.getIndex();
472 case MachineOperand::MO_ConstantPoolIndex:
473 O << MAI->getPrivateGlobalPrefix() << "CPI"
474 << getFunctionNumber() << "_" << MO.getIndex();
476 O << "+" << MO.getOffset();
480 llvm_unreachable("<unknown operand type>");
483 if (closeP) O << ")";
486 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
488 const MachineOperand &MO = MI->getOperand(opNum);
490 O << (unsigned short int)MO.getImm();
492 printOperand(MI, opNum, O);
495 void MipsAsmPrinter::
496 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
497 // Load/Store memory operands -- imm($reg)
498 // If PIC target the target is loaded as the
499 // pattern lw $25,%call16($28)
500 printOperand(MI, opNum+1, O);
502 printOperand(MI, opNum, O);
506 void MipsAsmPrinter::
507 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
508 // when using stack locations for not load/store instructions
509 // print the same way as all normal 3 operand instructions.
510 printOperand(MI, opNum, O);
512 printOperand(MI, opNum+1, O);
516 void MipsAsmPrinter::
517 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
518 const char *Modifier) {
519 const MachineOperand &MO = MI->getOperand(opNum);
520 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
523 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
524 // FIXME: Use SwitchSection.
526 // Tell the assembler which ABI we are using
527 if (OutStreamer.hasRawTextSupport())
528 OutStreamer.EmitRawText("\t.section .mdebug." +
529 Twine(getCurrentABIString()));
531 // TODO: handle O64 ABI
532 if (OutStreamer.hasRawTextSupport()) {
533 if (Subtarget->isABI_EABI()) {
534 if (Subtarget->isGP32bit())
535 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
537 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
541 // return to previous section
542 if (OutStreamer.hasRawTextSupport())
543 OutStreamer.EmitRawText(StringRef("\t.previous"));
547 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
549 if (OutStreamer.hasRawTextSupport()) return;
551 // Emit Mips ELF register info
552 Subtarget->getMReginfo().emitMipsReginfoSectionCG(
553 OutStreamer, getObjFileLowering(), *Subtarget);
554 MipsELFStreamer & MES = static_cast<MipsELFStreamer &>(OutStreamer);
555 MES.emitELFHeaderFlagsCG(*Subtarget);
559 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
560 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
561 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
562 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
563 "Unexpected MachineOperand types");
564 return MachineLocation(MI->getOperand(0).getReg(),
565 MI->getOperand(1).getImm());
568 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
573 // Force static initialization.
574 extern "C" void LLVMInitializeMipsAsmPrinter() {
575 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
576 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
577 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
578 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);