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 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MCTargetDesc/MipsMCNaCl.h"
19 #include "MipsAsmPrinter.h"
20 #include "MipsInstrInfo.h"
21 #include "MipsMCInstLower.h"
22 #include "MipsTargetMachine.h"
23 #include "MipsTargetStreamer.h"
24 #include "llvm/ADT/SmallString.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/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCELFStreamer.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCInst.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSymbolELF.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "mips-asm-printer"
56 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const {
57 return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer());
60 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
61 Subtarget = &MF.getSubtarget<MipsSubtarget>();
63 MipsFI = MF.getInfo<MipsFunctionInfo>();
64 if (Subtarget->inMips16Mode())
67 const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
68 it = MipsFI->StubsNeeded.begin();
69 it != MipsFI->StubsNeeded.end(); ++it) {
70 const char *Symbol = it->first;
71 const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
72 if (StubsNeeded.find(Symbol) == StubsNeeded.end())
73 StubsNeeded[Symbol] = Signature;
75 MCP = MF.getConstantPool();
77 // In NaCl, all indirect jump targets must be aligned to bundle size.
78 if (Subtarget->isTargetNaCl())
79 NaClAlignIndirectJumpTargets(MF);
81 AsmPrinter::runOnMachineFunction(MF);
85 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
86 MCOp = MCInstLowering.LowerOperand(MO);
87 return MCOp.isValid();
90 #include "MipsGenMCPseudoLowering.inc"
92 // Lower PseudoReturn/PseudoIndirectBranch/PseudoIndirectBranch64 to JR, JR_MM,
93 // JALR, or JALR64 as appropriate for the target
94 void MipsAsmPrinter::emitPseudoIndirectBranch(MCStreamer &OutStreamer,
95 const MachineInstr *MI) {
96 bool HasLinkReg = false;
97 bool InMicroMipsMode = Subtarget->inMicroMipsMode();
100 if (Subtarget->hasMips64r6()) {
101 // MIPS64r6 should use (JALR64 ZERO_64, $rs)
102 TmpInst0.setOpcode(Mips::JALR64);
104 } else if (Subtarget->hasMips32r6()) {
105 // MIPS32r6 should use (JALR ZERO, $rs)
107 TmpInst0.setOpcode(Mips::JRC16_MMR6);
109 TmpInst0.setOpcode(Mips::JALR);
112 } else if (Subtarget->inMicroMipsMode())
113 // microMIPS should use (JR_MM $rs)
114 TmpInst0.setOpcode(Mips::JR_MM);
116 // Everything else should use (JR $rs)
117 TmpInst0.setOpcode(Mips::JR);
123 unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO;
124 TmpInst0.addOperand(MCOperand::createReg(ZeroReg));
127 lowerOperand(MI->getOperand(0), MCOp);
128 TmpInst0.addOperand(MCOp);
130 EmitToStreamer(OutStreamer, TmpInst0);
133 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
134 MipsTargetStreamer &TS = getTargetStreamer();
135 TS.forbidModuleDirective();
137 if (MI->isDebugValue()) {
138 SmallString<128> Str;
139 raw_svector_ostream OS(Str);
141 PrintDebugValueComment(MI, OS);
145 // If we just ended a constant pool, mark it as such.
146 if (InConstantPool && MI->getOpcode() != Mips::CONSTPOOL_ENTRY) {
147 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
148 InConstantPool = false;
150 if (MI->getOpcode() == Mips::CONSTPOOL_ENTRY) {
151 // CONSTPOOL_ENTRY - This instruction represents a floating
152 //constant pool in the function. The first operand is the ID#
153 // for this instruction, the second is the index into the
154 // MachineConstantPool that this is, the third is the size in
155 // bytes of this constant pool entry.
156 // The required alignment is specified on the basic block holding this MI.
158 unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
159 unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex();
161 // If this is the first entry of the pool, mark it.
162 if (!InConstantPool) {
163 OutStreamer->EmitDataRegion(MCDR_DataRegion);
164 InConstantPool = true;
167 OutStreamer->EmitLabel(GetCPISymbol(LabelId));
169 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
170 if (MCPE.isMachineConstantPoolEntry())
171 EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
173 EmitGlobalConstant(MF->getDataLayout(), MCPE.Val.ConstVal);
178 MachineBasicBlock::const_instr_iterator I = MI->getIterator();
179 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
182 // Do any auto-generated pseudo lowerings.
183 if (emitPseudoExpansionLowering(*OutStreamer, &*I))
186 if (I->getOpcode() == Mips::PseudoReturn ||
187 I->getOpcode() == Mips::PseudoReturn64 ||
188 I->getOpcode() == Mips::PseudoIndirectBranch ||
189 I->getOpcode() == Mips::PseudoIndirectBranch64 ||
190 I->getOpcode() == Mips::TAILCALLREG ||
191 I->getOpcode() == Mips::TAILCALLREG64) {
192 emitPseudoIndirectBranch(*OutStreamer, &*I);
196 // The inMips16Mode() test is not permanent.
197 // Some instructions are marked as pseudo right now which
198 // would make the test fail for the wrong reason but
199 // that will be fixed soon. We need this here because we are
200 // removing another test for this situation downstream in the
203 if (I->isPseudo() && !Subtarget->inMips16Mode()
204 && !isLongBranchPseudo(I->getOpcode()))
205 llvm_unreachable("Pseudo opcode found in EmitInstruction()");
208 MCInstLowering.Lower(&*I, TmpInst0);
209 EmitToStreamer(*OutStreamer, TmpInst0);
210 } while ((++I != E) && I->isInsideBundle()); // Delay slot check
213 //===----------------------------------------------------------------------===//
215 // Mips Asm Directives
217 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
218 // Describe the stack frame.
220 // -- Mask directives "(f)mask bitmask, offset"
221 // Tells the assembler which registers are saved and where.
222 // bitmask - contain a little endian bitset indicating which registers are
223 // saved on function prologue (e.g. with a 0x80000000 mask, the
224 // assembler knows the register 31 (RA) is saved at prologue.
225 // offset - the position before stack pointer subtraction indicating where
226 // the first saved register on prologue is located. (e.g. with a
228 // Consider the following function prologue:
231 // .mask 0xc0000000,-8
232 // addiu $sp, $sp, -48
236 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
237 // 30 (FP) are saved at prologue. As the save order on prologue is from
238 // left to right, RA is saved first. A -8 offset means that after the
239 // stack pointer subtration, the first register in the mask (RA) will be
240 // saved at address 48-8=40.
242 //===----------------------------------------------------------------------===//
244 //===----------------------------------------------------------------------===//
246 //===----------------------------------------------------------------------===//
248 // Create a bitmask with all callee saved registers for CPU or Floating Point
249 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
250 void MipsAsmPrinter::printSavedRegsBitmask() {
251 // CPU and FPU Saved Registers Bitmasks
252 unsigned CPUBitmask = 0, FPUBitmask = 0;
253 int CPUTopSavedRegOff, FPUTopSavedRegOff;
255 // Set the CPU and FPU Bitmasks
256 const MachineFrameInfo &MFI = MF->getFrameInfo();
257 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
258 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
259 // size of stack area to which FP callee-saved regs are saved.
260 unsigned CPURegSize = Mips::GPR32RegClass.getSize();
261 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
262 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
263 bool HasAFGR64Reg = false;
264 unsigned CSFPRegsSize = 0;
266 for (const auto &I : CSI) {
267 unsigned Reg = I.getReg();
268 unsigned RegNum = TRI->getEncodingValue(Reg);
270 // If it's a floating point register, set the FPU Bitmask.
271 // If it's a general purpose register, set the CPU Bitmask.
272 if (Mips::FGR32RegClass.contains(Reg)) {
273 FPUBitmask |= (1 << RegNum);
274 CSFPRegsSize += FGR32RegSize;
275 } else if (Mips::AFGR64RegClass.contains(Reg)) {
276 FPUBitmask |= (3 << RegNum);
277 CSFPRegsSize += AFGR64RegSize;
279 } else if (Mips::GPR32RegClass.contains(Reg))
280 CPUBitmask |= (1 << RegNum);
283 // FP Regs are saved right below where the virtual frame pointer points to.
284 FPUTopSavedRegOff = FPUBitmask ?
285 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
287 // CPU Regs are saved below FP Regs.
288 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
290 MipsTargetStreamer &TS = getTargetStreamer();
292 TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
295 TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
298 //===----------------------------------------------------------------------===//
299 // Frame and Set directives
300 //===----------------------------------------------------------------------===//
303 void MipsAsmPrinter::emitFrameDirective() {
304 const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo();
306 unsigned stackReg = RI.getFrameRegister(*MF);
307 unsigned returnReg = RI.getRARegister();
308 unsigned stackSize = MF->getFrameInfo().getStackSize();
310 getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
313 /// Emit Set directives.
314 const char *MipsAsmPrinter::getCurrentABIString() const {
315 switch (static_cast<MipsTargetMachine &>(TM).getABI().GetEnumValue()) {
316 case MipsABIInfo::ABI::O32: return "abi32";
317 case MipsABIInfo::ABI::N32: return "abiN32";
318 case MipsABIInfo::ABI::N64: return "abi64";
319 default: llvm_unreachable("Unknown Mips ABI");
323 void MipsAsmPrinter::EmitFunctionEntryLabel() {
324 MipsTargetStreamer &TS = getTargetStreamer();
326 // NaCl sandboxing requires that indirect call instructions are masked.
327 // This means that function entry points should be bundle-aligned.
328 if (Subtarget->isTargetNaCl())
329 EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
331 if (Subtarget->inMicroMipsMode()) {
332 TS.emitDirectiveSetMicroMips();
333 TS.setUsesMicroMips();
335 TS.emitDirectiveSetNoMicroMips();
337 if (Subtarget->inMips16Mode())
338 TS.emitDirectiveSetMips16();
340 TS.emitDirectiveSetNoMips16();
342 TS.emitDirectiveEnt(*CurrentFnSym);
343 OutStreamer->EmitLabel(CurrentFnSym);
346 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
347 /// the first basic block in the function.
348 void MipsAsmPrinter::EmitFunctionBodyStart() {
349 MipsTargetStreamer &TS = getTargetStreamer();
351 MCInstLowering.Initialize(&MF->getContext());
353 bool IsNakedFunction = MF->getFunction()->hasFnAttribute(Attribute::Naked);
354 if (!IsNakedFunction)
355 emitFrameDirective();
357 if (!IsNakedFunction)
358 printSavedRegsBitmask();
360 if (!Subtarget->inMips16Mode()) {
361 TS.emitDirectiveSetNoReorder();
362 TS.emitDirectiveSetNoMacro();
363 TS.emitDirectiveSetNoAt();
367 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
368 /// the last basic block in the function.
369 void MipsAsmPrinter::EmitFunctionBodyEnd() {
370 MipsTargetStreamer &TS = getTargetStreamer();
372 // There are instruction for this macros, but they must
373 // always be at the function end, and we can't emit and
374 // break with BB logic.
375 if (!Subtarget->inMips16Mode()) {
376 TS.emitDirectiveSetAt();
377 TS.emitDirectiveSetMacro();
378 TS.emitDirectiveSetReorder();
380 TS.emitDirectiveEnd(CurrentFnSym->getName());
381 // Make sure to terminate any constant pools that were at the end
385 InConstantPool = false;
386 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
389 void MipsAsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
390 MipsTargetStreamer &TS = getTargetStreamer();
392 TS.emitDirectiveInsn();
395 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
396 /// exactly one predecessor and the control transfer mechanism between
397 /// the predecessor and this block is a fall-through.
398 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
400 // The predecessor has to be immediately before this block.
401 const MachineBasicBlock *Pred = *MBB->pred_begin();
403 // If the predecessor is a switch statement, assume a jump table
404 // implementation, so it is not a fall through.
405 if (const BasicBlock *bb = Pred->getBasicBlock())
406 if (isa<SwitchInst>(bb->getTerminator()))
409 // If this is a landing pad, it isn't a fall through. If it has no preds,
410 // then nothing falls through to it.
411 if (MBB->isEHPad() || MBB->pred_empty())
414 // If there isn't exactly one predecessor, it can't be a fall through.
415 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
418 if (PI2 != MBB->pred_end())
421 // The predecessor has to be immediately before this block.
422 if (!Pred->isLayoutSuccessor(MBB))
425 // If the block is completely empty, then it definitely does fall through.
429 // Otherwise, check the last instruction.
430 // Check if the last terminator is an unconditional branch.
431 MachineBasicBlock::const_iterator I = Pred->end();
432 while (I != Pred->begin() && !(--I)->isTerminator()) ;
434 return !I->isBarrier();
437 // Print out an operand for an inline asm expression.
438 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
439 unsigned AsmVariant, const char *ExtraCode,
441 // Does this asm operand have a single letter operand modifier?
442 if (ExtraCode && ExtraCode[0]) {
443 if (ExtraCode[1] != 0) return true; // Unknown modifier.
445 const MachineOperand &MO = MI->getOperand(OpNum);
446 switch (ExtraCode[0]) {
448 // See if this is a generic print operand
449 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
450 case 'X': // hex const int
451 if ((MO.getType()) != MachineOperand::MO_Immediate)
453 O << "0x" << Twine::utohexstr(MO.getImm());
455 case 'x': // hex const int (low 16 bits)
456 if ((MO.getType()) != MachineOperand::MO_Immediate)
458 O << "0x" << Twine::utohexstr(MO.getImm() & 0xffff);
460 case 'd': // decimal const int
461 if ((MO.getType()) != MachineOperand::MO_Immediate)
465 case 'm': // decimal const int minus 1
466 if ((MO.getType()) != MachineOperand::MO_Immediate)
468 O << MO.getImm() - 1;
471 // $0 if zero, regular printing otherwise
472 if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) {
476 // If not, call printOperand as normal.
479 case 'D': // Second part of a double word register operand
480 case 'L': // Low order register of a double word register operand
481 case 'M': // High order register of a double word register operand
485 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
486 if (!FlagsOP.isImm())
488 unsigned Flags = FlagsOP.getImm();
489 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
490 // Number of registers represented by this operand. We are looking
491 // for 2 for 32 bit mode and 1 for 64 bit mode.
493 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
494 unsigned Reg = MO.getReg();
495 O << '$' << MipsInstPrinter::getRegisterName(Reg);
501 unsigned RegOp = OpNum;
502 if (!Subtarget->isGP64bit()){
503 // Endianness reverses which register holds the high or low value
505 switch(ExtraCode[0]) {
507 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
510 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
512 case 'D': // Always the second part
515 if (RegOp >= MI->getNumOperands())
517 const MachineOperand &MO = MI->getOperand(RegOp);
520 unsigned Reg = MO.getReg();
521 O << '$' << MipsInstPrinter::getRegisterName(Reg);
526 // Print MSA registers for the 'f' constraint
527 // In LLVM, the 'w' modifier doesn't need to do anything.
528 // We can just call printOperand as normal.
533 printOperand(MI, OpNum, O);
537 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
538 unsigned OpNum, unsigned AsmVariant,
539 const char *ExtraCode,
541 assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands");
542 const MachineOperand &BaseMO = MI->getOperand(OpNum);
543 const MachineOperand &OffsetMO = MI->getOperand(OpNum + 1);
544 assert(BaseMO.isReg() && "Unexpected base pointer for inline asm memory operand.");
545 assert(OffsetMO.isImm() && "Unexpected offset for inline asm memory operand.");
546 int Offset = OffsetMO.getImm();
548 // Currently we are expecting either no ExtraCode or 'D'
550 if (ExtraCode[0] == 'D')
553 return true; // Unknown modifier.
554 // FIXME: M = high order bits
555 // FIXME: L = low order bits
558 O << Offset << "($" << MipsInstPrinter::getRegisterName(BaseMO.getReg()) << ")";
563 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
565 const MachineOperand &MO = MI->getOperand(opNum);
568 if (MO.getTargetFlags())
571 switch(MO.getTargetFlags()) {
572 case MipsII::MO_GPREL: O << "%gp_rel("; break;
573 case MipsII::MO_GOT_CALL: O << "%call16("; break;
574 case MipsII::MO_GOT: O << "%got("; break;
575 case MipsII::MO_ABS_HI: O << "%hi("; break;
576 case MipsII::MO_ABS_LO: O << "%lo("; break;
577 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
578 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
579 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
580 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
581 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
582 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
583 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
584 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
585 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
588 switch (MO.getType()) {
589 case MachineOperand::MO_Register:
591 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
594 case MachineOperand::MO_Immediate:
598 case MachineOperand::MO_MachineBasicBlock:
599 MO.getMBB()->getSymbol()->print(O, MAI);
602 case MachineOperand::MO_GlobalAddress:
603 getSymbol(MO.getGlobal())->print(O, MAI);
606 case MachineOperand::MO_BlockAddress: {
607 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
612 case MachineOperand::MO_ConstantPoolIndex:
613 O << getDataLayout().getPrivateGlobalPrefix() << "CPI"
614 << getFunctionNumber() << "_" << MO.getIndex();
616 O << "+" << MO.getOffset();
620 llvm_unreachable("<unknown operand type>");
623 if (closeP) O << ")";
626 void MipsAsmPrinter::
627 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
628 // Load/Store memory operands -- imm($reg)
629 // If PIC target the target is loaded as the
630 // pattern lw $25,%call16($28)
632 // opNum can be invalid if instruction has reglist as operand.
633 // MemOperand is always last operand of instruction (base + offset).
634 switch (MI->getOpcode()) {
639 opNum = MI->getNumOperands() - 2;
643 printOperand(MI, opNum+1, O);
645 printOperand(MI, opNum, O);
649 void MipsAsmPrinter::
650 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
651 // when using stack locations for not load/store instructions
652 // print the same way as all normal 3 operand instructions.
653 printOperand(MI, opNum, O);
655 printOperand(MI, opNum+1, O);
659 void MipsAsmPrinter::
660 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
661 const char *Modifier) {
662 const MachineOperand &MO = MI->getOperand(opNum);
663 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
666 void MipsAsmPrinter::
667 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) {
668 for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) {
669 if (i != opNum) O << ", ";
670 printOperand(MI, i, O);
674 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
675 MipsTargetStreamer &TS = getTargetStreamer();
677 // MipsTargetStreamer has an initialization order problem when emitting an
678 // object file directly (see MipsTargetELFStreamer for full details). Work
679 // around it by re-initializing the PIC state here.
680 TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent());
682 // Compute MIPS architecture attributes based on the default subtarget
683 // that we'd have constructed. Module level directives aren't LTO
685 // FIXME: For ifunc related functions we could iterate over and look
686 // for a feature string that doesn't match the default one.
687 const Triple &TT = TM.getTargetTriple();
688 StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU());
689 StringRef FS = TM.getTargetFeatureString();
690 const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM);
691 const MipsSubtarget STI(TT, CPU, FS, MTM.isLittleEndian(), MTM);
693 bool IsABICalls = STI.isABICalls();
694 const MipsABIInfo &ABI = MTM.getABI();
696 TS.emitDirectiveAbiCalls();
697 // FIXME: This condition should be a lot more complicated that it is here.
698 // Ideally it should test for properties of the ABI and not the ABI
700 // For the moment, I'm only correcting enough to make MIPS-IV work.
701 if (!isPositionIndependent() && !ABI.IsN64())
702 TS.emitDirectiveOptionPic0();
705 // Tell the assembler which ABI we are using
706 std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
707 OutStreamer->SwitchSection(
708 OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0));
710 // NaN: At the moment we only support:
711 // 1. .nan legacy (default)
713 STI.isNaN2008() ? TS.emitDirectiveNaN2008()
714 : TS.emitDirectiveNaNLegacy();
716 // TODO: handle O64 ABI
718 TS.updateABIInfo(STI);
720 // We should always emit a '.module fp=...' but binutils 2.24 does not accept
721 // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or
722 // -mfp64) and omit it otherwise.
723 if (ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit()))
724 TS.emitDirectiveModuleFP();
726 // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
727 // accept it. We therefore emit it when it contradicts the default or an
728 // option has changed the default (i.e. FPXX) and omit it otherwise.
729 if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX()))
730 TS.emitDirectiveModuleOddSPReg();
733 void MipsAsmPrinter::emitInlineAsmStart() const {
734 MipsTargetStreamer &TS = getTargetStreamer();
736 // GCC's choice of assembler options for inline assembly code ('at', 'macro'
737 // and 'reorder') is different from LLVM's choice for generated code ('noat',
738 // 'nomacro' and 'noreorder').
739 // In order to maintain compatibility with inline assembly code which depends
740 // on GCC's assembler options being used, we have to switch to those options
741 // for the duration of the inline assembly block and then switch back.
742 TS.emitDirectiveSetPush();
743 TS.emitDirectiveSetAt();
744 TS.emitDirectiveSetMacro();
745 TS.emitDirectiveSetReorder();
746 OutStreamer->AddBlankLine();
749 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
750 const MCSubtargetInfo *EndInfo) const {
751 OutStreamer->AddBlankLine();
752 getTargetStreamer().emitDirectiveSetPop();
755 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) {
757 I.setOpcode(Mips::JAL);
759 MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext)));
760 OutStreamer->EmitInstruction(I, STI);
763 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode,
767 I.addOperand(MCOperand::createReg(Reg));
768 OutStreamer->EmitInstruction(I, STI);
771 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI,
772 unsigned Opcode, unsigned Reg1,
776 // Because of the current td files for Mips32, the operands for MTC1
777 // appear backwards from their normal assembly order. It's not a trivial
778 // change to fix this in the td file so we adjust for it here.
780 if (Opcode == Mips::MTC1) {
781 unsigned Temp = Reg1;
786 I.addOperand(MCOperand::createReg(Reg1));
787 I.addOperand(MCOperand::createReg(Reg2));
788 OutStreamer->EmitInstruction(I, STI);
791 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI,
792 unsigned Opcode, unsigned Reg1,
793 unsigned Reg2, unsigned Reg3) {
796 I.addOperand(MCOperand::createReg(Reg1));
797 I.addOperand(MCOperand::createReg(Reg2));
798 I.addOperand(MCOperand::createReg(Reg3));
799 OutStreamer->EmitInstruction(I, STI);
802 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI,
803 unsigned MovOpc, unsigned Reg1,
804 unsigned Reg2, unsigned FPReg1,
805 unsigned FPReg2, bool LE) {
807 unsigned temp = Reg1;
811 EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1);
812 EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2);
815 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI,
816 Mips16HardFloatInfo::FPParamVariant PV,
817 bool LE, bool ToFP) {
818 using namespace Mips16HardFloatInfo;
819 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
822 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
825 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
828 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
829 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
832 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
835 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
836 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
839 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
840 EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14);
847 void MipsAsmPrinter::EmitSwapFPIntRetval(
848 const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV,
850 using namespace Mips16HardFloatInfo;
851 unsigned MovOpc = Mips::MFC1;
854 EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0);
857 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
860 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
863 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
864 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
871 void MipsAsmPrinter::EmitFPCallStub(
872 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
873 MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol));
874 using namespace Mips16HardFloatInfo;
875 bool LE = getDataLayout().isLittleEndian();
876 // Construct a local MCSubtargetInfo here.
877 // This is because the MachineFunction won't exist (but have not yet been
878 // freed) and since we're at the global level we can use the default
879 // constructed subtarget.
880 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
881 TM.getTargetTriple().str(), TM.getTargetCPU(),
882 TM.getTargetFeatureString()));
887 OutStreamer->EmitSymbolAttribute(MSymbol, MCSA_Global);
890 // make the comment field identifying the return and parameter
891 // types of the floating point stub
892 // # Stub function to call rettype xxxx (params)
894 switch (Signature->RetSig) {
905 RetType = "double complex";
912 switch (Signature->ParamSig) {
917 Parms = "float, float";
920 Parms = "float, double";
926 Parms = "double, double";
929 Parms = "double, float";
935 OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " +
936 Twine(Symbol) + " (" + Twine(Parms) + ")");
938 // probably not necessary but we save and restore the current section state
940 OutStreamer->PushSection();
942 // .section mips16.call.fpxxxx,"ax",@progbits
944 MCSectionELF *M = OutContext.getELFSection(
945 ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
946 ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
947 OutStreamer->SwitchSection(M, nullptr);
951 OutStreamer->EmitValueToAlignment(4);
952 MipsTargetStreamer &TS = getTargetStreamer();
957 TS.emitDirectiveSetNoMips16();
958 TS.emitDirectiveSetNoMicroMips();
960 // .ent __call_stub_fp_xxxx
961 // .type __call_stub_fp_xxxx,@function
962 // __call_stub_fp_xxxx:
964 std::string x = "__call_stub_fp_" + std::string(Symbol);
966 cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x)));
967 TS.emitDirectiveEnt(*Stub);
969 OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
970 OutStreamer->EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
971 OutStreamer->EmitLabel(Stub);
973 // Only handle non-pic for now.
974 assert(!isPositionIndependent() &&
975 "should not be here if we are compiling pic");
976 TS.emitDirectiveSetReorder();
978 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
979 // stubs without raw text but this current patch is for compiler generated
980 // functions and they all return some value.
981 // The calling sequence for non pic is different in that case and we need
982 // to implement %lo and %hi in order to handle the case of no return value
983 // See the corresponding method in Mips16HardFloat for details.
985 // mov the return address to S2.
986 // we have no stack space to store it and we are about to make another call.
987 // We need to make sure that the enclosing function knows to save S2
988 // This should have already been handled.
992 EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO);
994 EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true);
998 EmitJal(*STI, MSymbol);
1000 // fix return values
1001 EmitSwapFPIntRetval(*STI, Signature->RetSig, LE);
1004 // if (Signature->RetSig == NoFPRet)
1005 // llvm_unreachable("should not be any stubs here with no return value");
1007 EmitInstrReg(*STI, Mips::JR, Mips::S2);
1009 MCSymbol *Tmp = OutContext.createTempSymbol();
1010 OutStreamer->EmitLabel(Tmp);
1011 const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext);
1012 const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext);
1013 const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext);
1014 OutStreamer->emitELFSize(Stub, T_min_E);
1015 TS.emitDirectiveEnd(x);
1016 OutStreamer->PopSection();
1019 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
1020 // Emit needed stubs
1024 const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
1025 it = StubsNeeded.begin();
1026 it != StubsNeeded.end(); ++it) {
1027 const char *Symbol = it->first;
1028 const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1029 EmitFPCallStub(Symbol, Signature);
1031 // return to the text section
1032 OutStreamer->SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
1035 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1040 // Emit .dtprelword or .dtpreldword directive
1041 // and value for debug thread local expression.
1042 void MipsAsmPrinter::EmitDebugValue(const MCExpr *Value,
1043 unsigned Size) const {
1046 OutStreamer->EmitDTPRel32Value(Value);
1049 OutStreamer->EmitDTPRel64Value(Value);
1052 llvm_unreachable("Unexpected size of expression value.");
1056 // Align all targets of indirect branches on bundle size. Used only if target
1058 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
1059 // Align all blocks that are jumped to through jump table.
1060 if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
1061 const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
1062 for (unsigned I = 0; I < JT.size(); ++I) {
1063 const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
1065 for (unsigned J = 0; J < MBBs.size(); ++J)
1066 MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1070 // If basic block address is taken, block can be target of indirect branch.
1071 for (auto &MBB : MF) {
1072 if (MBB.hasAddressTaken())
1073 MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1077 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1078 return (Opcode == Mips::LONG_BRANCH_LUi
1079 || Opcode == Mips::LONG_BRANCH_ADDiu
1080 || Opcode == Mips::LONG_BRANCH_DADDiu);
1083 // Force static initialization.
1084 extern "C" void LLVMInitializeMipsAsmPrinter() {
1085 RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget());
1086 RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget());
1087 RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target());
1088 RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget());