1//===- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer --------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to GAS-format MIPS assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MipsAsmPrinter.h"
15#include "MCTargetDesc/MipsABIInfo.h"
16#include "MCTargetDesc/MipsBaseInfo.h"
17#include "MCTargetDesc/MipsInstPrinter.h"
18#include "MCTargetDesc/MipsMCAsmInfo.h"
19#include "MCTargetDesc/MipsMCTargetDesc.h"
20#include "MCTargetDesc/MipsTargetStreamer.h"
21#include "Mips.h"
22#include "MipsMCInstLower.h"
23#include "MipsMachineFunction.h"
24#include "MipsSubtarget.h"
25#include "MipsTargetMachine.h"
26#include "TargetInfo/MipsTargetInfo.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/Twine.h"
30#include "llvm/BinaryFormat/ELF.h"
31#include "llvm/CodeGen/MachineBasicBlock.h"
32#include "llvm/CodeGen/MachineConstantPool.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineJumpTableInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
40#include "llvm/IR/Attributes.h"
41#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/InlineAsm.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/Module.h"
47#include "llvm/MC/MCContext.h"
48#include "llvm/MC/MCExpr.h"
49#include "llvm/MC/MCInst.h"
50#include "llvm/MC/MCInstBuilder.h"
51#include "llvm/MC/MCObjectFileInfo.h"
52#include "llvm/MC/MCSectionELF.h"
53#include "llvm/MC/MCSymbol.h"
54#include "llvm/MC/TargetRegistry.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/Support/ErrorHandling.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Target/TargetLoweringObjectFile.h"
60#include "llvm/Target/TargetMachine.h"
61#include "llvm/TargetParser/Triple.h"
62#include <cassert>
63#include <cstdint>
64#include <map>
65#include <memory>
66#include <string>
67#include <vector>
68
69using namespace llvm;
70
71#define DEBUG_TYPE "mips-asm-printer"
72
73MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const {
74 return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer());
75}
76
77bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
78 Subtarget = &MF.getSubtarget<MipsSubtarget>();
79
80 MipsFI = MF.getInfo<MipsFunctionInfo>();
81 if (Subtarget->inMips16Mode())
82 for (const auto &I : MipsFI->StubsNeeded)
83 StubsNeeded.insert(x: I);
84 MCP = MF.getConstantPool();
85
86 AsmPrinter::runOnMachineFunction(MF);
87
88 emitXRayTable();
89
90 return true;
91}
92
93bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
94 MCOp = MCInstLowering.LowerOperand(MO);
95 return MCOp.isValid();
96}
97
98#include "MipsGenMCPseudoLowering.inc"
99
100// Lower PseudoReturn/PseudoIndirectBranch/PseudoIndirectBranch64 to JR, JR_MM,
101// JALR, or JALR64 as appropriate for the target.
102void MipsAsmPrinter::emitPseudoIndirectBranch(MCStreamer &OutStreamer,
103 const MachineInstr *MI) {
104 bool HasLinkReg = false;
105 bool InMicroMipsMode = Subtarget->inMicroMipsMode();
106 MCInst TmpInst0;
107
108 if (Subtarget->hasMips64r6()) {
109 // MIPS64r6 should use (JALR64 ZERO_64, $rs)
110 TmpInst0.setOpcode(Mips::JALR64);
111 HasLinkReg = true;
112 } else if (Subtarget->hasMips32r6()) {
113 // MIPS32r6 should use (JALR ZERO, $rs)
114 if (InMicroMipsMode)
115 TmpInst0.setOpcode(Mips::JRC16_MMR6);
116 else {
117 TmpInst0.setOpcode(Mips::JALR);
118 HasLinkReg = true;
119 }
120 } else if (Subtarget->inMicroMipsMode())
121 // microMIPS should use (JR_MM $rs)
122 TmpInst0.setOpcode(Mips::JR_MM);
123 else {
124 // Everything else should use (JR $rs)
125 TmpInst0.setOpcode(Mips::JR);
126 }
127
128 MCOperand MCOp;
129
130 if (HasLinkReg) {
131 unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::R0_64 : Mips::R0;
132 TmpInst0.addOperand(Op: MCOperand::createReg(Reg: ZeroReg));
133 }
134
135 lowerOperand(MO: MI->getOperand(i: 0), MCOp);
136 TmpInst0.addOperand(Op: MCOp);
137
138 EmitToStreamer(S&: OutStreamer, Inst: TmpInst0);
139}
140
141// If there is an MO_JALR operand, insert:
142//
143// .reloc tmplabel, R_{MICRO}MIPS_JALR, symbol
144// tmplabel:
145//
146// This is an optimization hint for the linker which may then replace
147// an indirect call with a direct branch.
148void MipsAsmPrinter::emitDirectiveRelocJalr(const MachineInstr &MI,
149 MCContext &OutContext,
150 TargetMachine &TM,
151 MCStreamer &OutStreamer,
152 const MipsSubtarget &Subtarget) {
153 for (const MachineOperand &MO :
154 llvm::drop_begin(RangeOrContainer: MI.operands(), N: MI.getDesc().getNumOperands())) {
155 if (MO.isMCSymbol() && (MO.getTargetFlags() & MipsII::MO_JALR)) {
156 MCSymbol *Callee = MO.getMCSymbol();
157 if (Callee && !Callee->getName().empty()) {
158 MCSymbol *Sym = GetExternalSymbolSymbol(Sym: Callee->getName());
159 MCSymbol *OffsetLabel = OutContext.createTempSymbol();
160 const MCExpr *OffsetExpr =
161 MCSymbolRefExpr::create(Symbol: OffsetLabel, Ctx&: OutContext);
162 const MCExpr *CaleeExpr = MCSymbolRefExpr::create(Symbol: Sym, Ctx&: OutContext);
163 OutStreamer.emitRelocDirective(
164 Offset: *OffsetExpr,
165 Name: Subtarget.inMicroMipsMode() ? "R_MICROMIPS_JALR" : "R_MIPS_JALR",
166 Expr: CaleeExpr);
167 OutStreamer.emitLabel(Symbol: OffsetLabel);
168 return;
169 }
170 }
171 }
172}
173
174void MipsAsmPrinter::emitInstruction(const MachineInstr *MI) {
175 // FIXME: Enable feature predicate checks once all the test pass.
176 // Mips_MC::verifyInstructionPredicates(MI->getOpcode(),
177 // getSubtargetInfo().getFeatureBits());
178
179 MipsTargetStreamer &TS = getTargetStreamer();
180 unsigned Opc = MI->getOpcode();
181 TS.forbidModuleDirective();
182
183 if (MI->isDebugValue()) {
184 SmallString<128> Str;
185 raw_svector_ostream OS(Str);
186
187 PrintDebugValueComment(MI, OS);
188 return;
189 }
190 if (MI->isDebugLabel())
191 return;
192
193 // If we just ended a constant pool, mark it as such.
194 if (InConstantPool && Opc != Mips::CONSTPOOL_ENTRY) {
195 OutStreamer->emitDataRegion(Kind: MCDR_DataRegionEnd);
196 InConstantPool = false;
197 }
198 if (Opc == Mips::CONSTPOOL_ENTRY) {
199 // CONSTPOOL_ENTRY - This instruction represents a floating
200 // constant pool in the function. The first operand is the ID#
201 // for this instruction, the second is the index into the
202 // MachineConstantPool that this is, the third is the size in
203 // bytes of this constant pool entry.
204 // The required alignment is specified on the basic block holding this MI.
205 //
206 unsigned LabelId = (unsigned)MI->getOperand(i: 0).getImm();
207 unsigned CPIdx = (unsigned)MI->getOperand(i: 1).getIndex();
208
209 // If this is the first entry of the pool, mark it.
210 if (!InConstantPool) {
211 OutStreamer->emitDataRegion(Kind: MCDR_DataRegion);
212 InConstantPool = true;
213 }
214
215 OutStreamer->emitLabel(Symbol: GetCPISymbol(CPID: LabelId));
216
217 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
218 if (MCPE.isMachineConstantPoolEntry())
219 emitMachineConstantPoolValue(MCPV: MCPE.Val.MachineCPVal);
220 else
221 emitGlobalConstant(DL: MF->getDataLayout(), CV: MCPE.Val.ConstVal);
222 return;
223 }
224
225 switch (Opc) {
226 case Mips::PATCHABLE_FUNCTION_ENTER:
227 LowerPATCHABLE_FUNCTION_ENTER(MI: *MI);
228 return;
229 case Mips::PATCHABLE_FUNCTION_EXIT:
230 LowerPATCHABLE_FUNCTION_EXIT(MI: *MI);
231 return;
232 case Mips::PATCHABLE_TAIL_CALL:
233 LowerPATCHABLE_TAIL_CALL(MI: *MI);
234 return;
235 }
236
237 if (Subtarget->getMCCLOpts().jalr_reloc &&
238 (MI->isReturn() || MI->isCall() || MI->isIndirectBranch())) {
239 emitDirectiveRelocJalr(MI: *MI, OutContext, TM, OutStreamer&: *OutStreamer, Subtarget: *Subtarget);
240 }
241
242 MachineBasicBlock::const_instr_iterator I = MI->getIterator();
243 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
244
245 do {
246 // Do any auto-generated pseudo lowerings.
247 if (MCInst OutInst; lowerPseudoInstExpansion(MI: &*I, Inst&: OutInst)) {
248 EmitToStreamer(S&: *OutStreamer, Inst: OutInst);
249 continue;
250 }
251
252 // Skip the BUNDLE pseudo instruction and lower the contents
253 if (I->isBundle())
254 continue;
255
256 if (I->getOpcode() == Mips::PseudoReturn ||
257 I->getOpcode() == Mips::PseudoReturn64 ||
258 I->getOpcode() == Mips::PseudoIndirectBranch ||
259 I->getOpcode() == Mips::PseudoIndirectBranch64 ||
260 I->getOpcode() == Mips::TAILCALLREG ||
261 I->getOpcode() == Mips::TAILCALLREG64) {
262 emitPseudoIndirectBranch(OutStreamer&: *OutStreamer, MI: &*I);
263 continue;
264 }
265
266 // The inMips16Mode() test is not permanent.
267 // Some instructions are marked as pseudo right now which
268 // would make the test fail for the wrong reason but
269 // that will be fixed soon. We need this here because we are
270 // removing another test for this situation downstream in the
271 // callchain.
272 //
273 if (I->isPseudo() && !Subtarget->inMips16Mode()
274 && !isLongBranchPseudo(Opcode: I->getOpcode()))
275 llvm_unreachable("Pseudo opcode found in emitInstruction()");
276
277 MCInst TmpInst0;
278 MCInstLowering.Lower(MI: &*I, OutMI&: TmpInst0);
279 EmitToStreamer(S&: *OutStreamer, Inst: TmpInst0);
280 } while ((++I != E) && I->isInsideBundle()); // Delay slot check
281}
282
283//===----------------------------------------------------------------------===//
284//
285// Mips Asm Directives
286//
287// -- Frame directive "frame Stackpointer, Stacksize, RARegister"
288// Describe the stack frame.
289//
290// -- Mask directives "(f)mask bitmask, offset"
291// Tells the assembler which registers are saved and where.
292// bitmask - contain a little endian bitset indicating which registers are
293// saved on function prologue (e.g. with a 0x80000000 mask, the
294// assembler knows the register 31 (RA) is saved at prologue.
295// offset - the position before stack pointer subtraction indicating where
296// the first saved register on prologue is located. (e.g. with a
297//
298// Consider the following function prologue:
299//
300// .frame $fp,48,$ra
301// .mask 0xc0000000,-8
302// addiu $sp, $sp, -48
303// sw $ra, 40($sp)
304// sw $fp, 36($sp)
305//
306// With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
307// 30 (FP) are saved at prologue. As the save order on prologue is from
308// left to right, RA is saved first. A -8 offset means that after the
309// stack pointer subtration, the first register in the mask (RA) will be
310// saved at address 48-8=40.
311//
312//===----------------------------------------------------------------------===//
313
314//===----------------------------------------------------------------------===//
315// Mask directives
316//===----------------------------------------------------------------------===//
317
318// Create a bitmask with all callee saved registers for CPU or Floating Point
319// registers. For CPU registers consider RA, GP and FP for saving if necessary.
320void MipsAsmPrinter::printSavedRegsBitmask() {
321 // CPU and FPU Saved Registers Bitmasks
322 unsigned CPUBitmask = 0, FPUBitmask = 0;
323 int CPUTopSavedRegOff, FPUTopSavedRegOff;
324
325 // Set the CPU and FPU Bitmasks
326 const MachineFrameInfo &MFI = MF->getFrameInfo();
327 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
328 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
329 // size of stack area to which FP callee-saved regs are saved.
330 unsigned CPURegSize = TRI->getRegSizeInBits(RC: Mips::GPR32RegClass) / 8;
331 unsigned FGR32RegSize = TRI->getRegSizeInBits(RC: Mips::FGR32RegClass) / 8;
332 unsigned AFGR64RegSize = TRI->getRegSizeInBits(RC: Mips::AFGR64RegClass) / 8;
333 bool HasAFGR64Reg = false;
334 unsigned CSFPRegsSize = 0;
335
336 for (const auto &I : CSI) {
337 Register Reg = I.getReg();
338 unsigned RegNum = TRI->getEncodingValue(Reg);
339
340 // If it's a floating point register, set the FPU Bitmask.
341 // If it's a general purpose register, set the CPU Bitmask.
342 if (Mips::FGR32RegClass.contains(Reg)) {
343 FPUBitmask |= (1 << RegNum);
344 CSFPRegsSize += FGR32RegSize;
345 } else if (Mips::AFGR64RegClass.contains(Reg)) {
346 FPUBitmask |= (3 << RegNum);
347 CSFPRegsSize += AFGR64RegSize;
348 HasAFGR64Reg = true;
349 } else if (Mips::GPR32RegClass.contains(Reg))
350 CPUBitmask |= (1 << RegNum);
351 }
352
353 // FP Regs are saved right below where the virtual frame pointer points to.
354 FPUTopSavedRegOff = FPUBitmask ?
355 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
356
357 // CPU Regs are saved below FP Regs.
358 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
359
360 MipsTargetStreamer &TS = getTargetStreamer();
361 // Print CPUBitmask
362 TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
363
364 // Print FPUBitmask
365 TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
366}
367
368//===----------------------------------------------------------------------===//
369// Frame and Set directives
370//===----------------------------------------------------------------------===//
371
372/// Frame Directive
373void MipsAsmPrinter::emitFrameDirective() {
374 const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo();
375
376 Register stackReg = RI.getFrameRegister(MF: *MF);
377 MCRegister returnReg = RI.getRARegister();
378 unsigned stackSize = MF->getFrameInfo().getStackSize();
379
380 getTargetStreamer().emitFrame(StackReg: stackReg, StackSize: stackSize, ReturnReg: returnReg);
381}
382
383/// Emit Set directives.
384static const char *getABIString(const MipsABIInfo &ABI) {
385 switch (ABI.GetEnumValue()) {
386 case MipsABIInfo::ABI::O32: return "abi32";
387 case MipsABIInfo::ABI::N32: return "abiN32";
388 case MipsABIInfo::ABI::N64: return "abi64";
389 default: llvm_unreachable("Unknown Mips ABI");
390 }
391}
392
393void MipsAsmPrinter::emitFunctionEntryLabel() {
394 MipsTargetStreamer &TS = getTargetStreamer();
395
396 if (Subtarget->inMicroMipsMode()) {
397 TS.emitDirectiveSetMicroMips();
398 TS.setUsesMicroMips();
399 TS.updateABIInfo(P: *Subtarget);
400 } else
401 TS.emitDirectiveSetNoMicroMips();
402
403 if (Subtarget->inMips16Mode())
404 TS.emitDirectiveSetMips16();
405 else
406 TS.emitDirectiveSetNoMips16();
407
408 TS.emitDirectiveEnt(Symbol: *CurrentFnSym);
409 OutStreamer->emitLabel(Symbol: CurrentFnSym);
410}
411
412/// EmitFunctionBodyStart - Targets can override this to emit stuff before
413/// the first basic block in the function.
414void MipsAsmPrinter::emitFunctionBodyStart() {
415 MipsTargetStreamer &TS = getTargetStreamer();
416
417 MCInstLowering.Initialize(C: &MF->getContext());
418
419 bool IsNakedFunction = MF->getFunction().hasFnAttribute(Kind: Attribute::Naked);
420 if (!IsNakedFunction)
421 emitFrameDirective();
422
423 if (!IsNakedFunction)
424 printSavedRegsBitmask();
425
426 if (!Subtarget->inMips16Mode()) {
427 TS.emitDirectiveSetNoReorder();
428 TS.emitDirectiveSetNoMacro();
429 TS.emitDirectiveSetNoAt();
430 }
431}
432
433/// EmitFunctionBodyEnd - Targets can override this to emit stuff after
434/// the last basic block in the function.
435void MipsAsmPrinter::emitFunctionBodyEnd() {
436 MipsTargetStreamer &TS = getTargetStreamer();
437
438 // There are instruction for this macros, but they must
439 // always be at the function end, and we can't emit and
440 // break with BB logic.
441 if (!Subtarget->inMips16Mode()) {
442 TS.emitDirectiveSetAt();
443 TS.emitDirectiveSetMacro();
444 TS.emitDirectiveSetReorder();
445 }
446 TS.emitDirectiveEnd(Name: CurrentFnSym->getName());
447 // Make sure to terminate any constant pools that were at the end
448 // of the function.
449 if (!InConstantPool)
450 return;
451 InConstantPool = false;
452 OutStreamer->emitDataRegion(Kind: MCDR_DataRegionEnd);
453}
454
455void MipsAsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {
456 AsmPrinter::emitBasicBlockEnd(MBB);
457 MipsTargetStreamer &TS = getTargetStreamer();
458 if (MBB.empty())
459 TS.emitDirectiveInsn();
460}
461
462// Print out an operand for an inline asm expression.
463bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
464 const char *ExtraCode, raw_ostream &O) {
465 // Does this asm operand have a single letter operand modifier?
466 if (ExtraCode && ExtraCode[0]) {
467 if (ExtraCode[1] != 0) return true; // Unknown modifier.
468
469 const MachineOperand &MO = MI->getOperand(i: OpNum);
470 switch (ExtraCode[0]) {
471 default:
472 // See if this is a generic print operand
473 return AsmPrinter::PrintAsmOperand(MI, OpNo: OpNum, ExtraCode, OS&: O);
474 case 'X': // hex const int
475 if (!MO.isImm())
476 return true;
477 O << "0x" << Twine::utohexstr(Val: MO.getImm());
478 return false;
479 case 'x': // hex const int (low 16 bits)
480 if (!MO.isImm())
481 return true;
482 O << "0x" << Twine::utohexstr(Val: MO.getImm() & 0xffff);
483 return false;
484 case 'd': // decimal const int
485 if (!MO.isImm())
486 return true;
487 O << MO.getImm();
488 return false;
489 case 'm': // decimal const int minus 1
490 if (!MO.isImm())
491 return true;
492 O << MO.getImm() - 1;
493 return false;
494 case 'y': // exact log2
495 if (!MO.isImm())
496 return true;
497 if (!isPowerOf2_64(Value: MO.getImm()))
498 return true;
499 O << Log2_64(Value: MO.getImm());
500 return false;
501 case 'z':
502 // $0 if zero, regular printing otherwise
503 if (MO.isImm() && MO.getImm() == 0) {
504 O << "$0";
505 return false;
506 }
507 // If not, call printOperand as normal.
508 break;
509 case 'D': // Second part of a double word register operand
510 case 'L': // Low order register of a double word register operand
511 case 'M': // High order register of a double word register operand
512 {
513 if (OpNum == 0)
514 return true;
515 const MachineOperand &FlagsOP = MI->getOperand(i: OpNum - 1);
516 if (!FlagsOP.isImm())
517 return true;
518 const InlineAsm::Flag Flags(FlagsOP.getImm());
519 const unsigned NumVals = Flags.getNumOperandRegisters();
520 // Number of registers represented by this operand. We are looking
521 // for 2 for 32 bit mode and 1 for 64 bit mode.
522 if (NumVals != 2) {
523 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
524 Register Reg = MO.getReg();
525 O << '$' << MipsInstPrinter::getRegisterName(Reg);
526 return false;
527 }
528 return true;
529 }
530
531 unsigned RegOp = OpNum;
532 if (!Subtarget->isGP64bit()){
533 // Endianness reverses which register holds the high or low value
534 // between M and L.
535 switch(ExtraCode[0]) {
536 case 'M':
537 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
538 break;
539 case 'L':
540 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
541 break;
542 case 'D': // Always the second part
543 RegOp = OpNum + 1;
544 }
545 if (RegOp >= MI->getNumOperands())
546 return true;
547 const MachineOperand &MO = MI->getOperand(i: RegOp);
548 if (!MO.isReg())
549 return true;
550 Register Reg = MO.getReg();
551 O << '$' << MipsInstPrinter::getRegisterName(Reg);
552 return false;
553 }
554 break;
555 }
556 case 'w': {
557 MCRegister w = getMSARegFromFReg(Reg: MO.getReg());
558 if (w != Mips::NoRegister) {
559 O << '$' << MipsInstPrinter::getRegisterName(Reg: w);
560 return false;
561 }
562 break;
563 }
564 }
565 }
566
567 printOperand(MI, opNum: OpNum, O);
568 return false;
569}
570
571bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
572 unsigned OpNum,
573 const char *ExtraCode,
574 raw_ostream &O) {
575 assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands");
576 const MachineOperand &BaseMO = MI->getOperand(i: OpNum);
577 const MachineOperand &OffsetMO = MI->getOperand(i: OpNum + 1);
578 assert(BaseMO.isReg() &&
579 "Unexpected base pointer for inline asm memory operand.");
580 assert(OffsetMO.isImm() &&
581 "Unexpected offset for inline asm memory operand.");
582 int Offset = OffsetMO.getImm();
583
584 // Currently we are expecting either no ExtraCode or 'D','M','L'.
585 if (ExtraCode) {
586 switch (ExtraCode[0]) {
587 case 'D':
588 Offset += 4;
589 break;
590 case 'M':
591 if (Subtarget->isLittle())
592 Offset += 4;
593 break;
594 case 'L':
595 if (!Subtarget->isLittle())
596 Offset += 4;
597 break;
598 default:
599 return true; // Unknown modifier.
600 }
601 }
602
603 O << Offset << "($" << MipsInstPrinter::getRegisterName(Reg: BaseMO.getReg())
604 << ")";
605
606 return false;
607}
608
609void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
610 raw_ostream &O) {
611 const MachineOperand &MO = MI->getOperand(i: opNum);
612 bool closeP = false;
613
614 if (MO.getTargetFlags())
615 closeP = true;
616
617 switch(MO.getTargetFlags()) {
618 case MipsII::MO_GPREL: O << "%gp_rel("; break;
619 case MipsII::MO_GOT_CALL: O << "%call16("; break;
620 case MipsII::MO_GOT: O << "%got("; break;
621 case MipsII::MO_ABS_HI: O << "%hi("; break;
622 case MipsII::MO_ABS_LO: O << "%lo("; break;
623 case MipsII::MO_HIGHER: O << "%higher("; break;
624 case MipsII::MO_HIGHEST: O << "%highest(("; break;
625 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
626 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
627 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
628 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
629 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
630 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
631 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
632 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
633 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
634 }
635
636 switch (MO.getType()) {
637 case MachineOperand::MO_Register:
638 O << '$'
639 << StringRef(MipsInstPrinter::getRegisterName(Reg: MO.getReg())).lower();
640 break;
641
642 case MachineOperand::MO_Immediate:
643 O << MO.getImm();
644 break;
645
646 case MachineOperand::MO_MachineBasicBlock:
647 MO.getMBB()->getSymbol()->print(OS&: O, MAI);
648 return;
649
650 case MachineOperand::MO_GlobalAddress:
651 PrintSymbolOperand(MO, OS&: O);
652 break;
653
654 case MachineOperand::MO_BlockAddress: {
655 MCSymbol *BA = GetBlockAddressSymbol(BA: MO.getBlockAddress());
656 O << BA->getName();
657 break;
658 }
659
660 case MachineOperand::MO_ConstantPoolIndex:
661 O << getDataLayout().getInternalSymbolPrefix() << "CPI"
662 << getFunctionNumber() << "_" << MO.getIndex();
663 if (MO.getOffset())
664 O << "+" << MO.getOffset();
665 break;
666
667 default:
668 llvm_unreachable("<unknown operand type>");
669 }
670
671 if (closeP) O << ")";
672}
673
674void MipsAsmPrinter::printFCCOperand(const MachineInstr *MI, int opNum,
675 raw_ostream &O) {
676 const MachineOperand &MO = MI->getOperand(i: opNum);
677 O << Mips::MipsFCCToString(CC: (Mips::CondCode)MO.getImm());
678}
679
680void MipsAsmPrinter::
681printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) {
682 for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) {
683 if (i != opNum) O << ", ";
684 printOperand(MI, opNum: i, O);
685 }
686}
687
688void MipsAsmPrinter::emitStartOfAsmFile(Module &M) {
689 const Triple &TT = M.getTargetTriple();
690
691 if (TT.isOSBinFormatELF()) {
692 MipsTargetStreamer &TS = getTargetStreamer();
693
694 // MipsTargetStreamer has an initialization order problem when emitting an
695 // object file directly (see MipsTargetELFStreamer for full details). Work
696 // around it by re-initializing the PIC state here.
697 TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent());
698
699 // Try to get target-features from the first function.
700 StringRef FS = TM.getTargetFeatureString();
701 Module::iterator F = M.begin();
702 if (FS.empty() && M.size() && F->hasFnAttribute(Kind: "target-features"))
703 FS = F->getFnAttribute(Kind: "target-features").getValueAsString();
704
705 std::string strFS = FS.str();
706 if (M.size() && F->getFnAttribute(Kind: "use-soft-float").getValueAsBool())
707 strFS += strFS.empty() ? "+soft-float" : ",+soft-float";
708
709 // Compute MIPS architecture attributes based on the default subtarget
710 // that we'd have constructed.
711 // FIXME: For ifunc related functions we could iterate over and look
712 // for a feature string that doesn't match the default one.
713 StringRef CPU = MIPS_MC::selectMipsCPU(TT, CPU: TM.getTargetCPU());
714 const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM);
715 const MipsSubtarget STI(TT, CPU, StringRef(strFS), MTM.getTargetABIName(M),
716 MTM.isLittleEndian(), MTM, std::nullopt);
717
718 bool IsABICalls = STI.isABICalls();
719 const MipsABIInfo &ABI = STI.getABI();
720 if (IsABICalls) {
721 TS.emitDirectiveAbiCalls();
722 // FIXME: This condition should be a lot more complicated that it is here.
723 // Ideally it should test for properties of the ABI and not the ABI
724 // itself.
725 // For the moment, I'm only correcting enough to make MIPS-IV work.
726 if (!isPositionIndependent() && STI.hasSym32())
727 TS.emitDirectiveOptionPic0();
728 }
729
730 // Tell the assembler which ABI we are using
731 std::string SectionName = std::string(".mdebug.") + getABIString(ABI);
732 OutStreamer->switchSection(
733 Section: OutContext.getELFSection(Section: SectionName, Type: ELF::SHT_PROGBITS, Flags: 0));
734
735 // NaN: At the moment we only support:
736 // 1. .nan legacy (default)
737 // 2. .nan 2008
738 STI.isNaN2008() ? TS.emitDirectiveNaN2008() : TS.emitDirectiveNaNLegacy();
739
740 // TODO: handle O64 ABI
741
742 TS.updateABIInfo(P: STI);
743
744 // We should always emit a '.module fp=...' but binutils 2.24 does not
745 // accept it. We therefore emit it when it contradicts the ABI defaults
746 // (-mfpxx or -mfp64) and omit it otherwise.
747 // Single-float uses its own ABI even when 64-bit FPRs are enabled.
748 if ((ABI.IsO32() && !STI.isSingleFloat() &&
749 (STI.isABI_FPXX() || STI.isFP64bit())) ||
750 STI.useSoftFloat())
751 TS.emitDirectiveModuleFP();
752
753 // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
754 // accept it. We therefore emit it when it contradicts the default or an
755 // option has changed the default (i.e. FPXX) and omit it otherwise.
756 if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX()))
757 TS.emitDirectiveModuleOddSPReg();
758
759 // Switch to the .text section.
760 OutStreamer->switchSection(Section: getObjFileLowering().getTextSection());
761 }
762}
763
764void MipsAsmPrinter::emitInlineAsmStart() const {
765 MipsTargetStreamer &TS = getTargetStreamer();
766
767 // GCC's choice of assembler options for inline assembly code ('at', 'macro'
768 // and 'reorder') is different from LLVM's choice for generated code ('noat',
769 // 'nomacro' and 'noreorder').
770 // In order to maintain compatibility with inline assembly code which depends
771 // on GCC's assembler options being used, we have to switch to those options
772 // for the duration of the inline assembly block and then switch back.
773 TS.emitDirectiveSetPush();
774 TS.emitDirectiveSetAt();
775 TS.emitDirectiveSetMacro();
776 TS.emitDirectiveSetReorder();
777 OutStreamer->addBlankLine();
778}
779
780void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
781 const MCSubtargetInfo *EndInfo,
782 const MachineInstr *MI) {
783 OutStreamer->addBlankLine();
784 getTargetStreamer().emitDirectiveSetPop();
785}
786
787void MipsAsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo &MJTI,
788 const MachineBasicBlock *MBB,
789 unsigned uid) const {
790 MCSymbol *MBBSym = MBB->getSymbol();
791 switch (MJTI.getEntryKind()) {
792 case MachineJumpTableInfo::EK_BlockAddress:
793 OutStreamer->emitValue(Value: MCSymbolRefExpr::create(Symbol: MBBSym, Ctx&: OutContext),
794 Size: getDataLayout().getPointerSize());
795 break;
796 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
797 // Each entry is a GP-relative value targeting the block symbol.
798 getTargetStreamer().emitGPRel32Value(
799 MCSymbolRefExpr::create(Symbol: MBBSym, Ctx&: OutContext));
800 break;
801 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
802 getTargetStreamer().emitGPRel64Value(
803 MCSymbolRefExpr::create(Symbol: MBBSym, Ctx&: OutContext));
804 break;
805 default:
806 llvm_unreachable("");
807 }
808}
809
810void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) {
811 MCInst I;
812 I.setOpcode(Mips::JAL);
813 I.addOperand(
814 Op: MCOperand::createExpr(Val: MCSymbolRefExpr::create(Symbol, Ctx&: OutContext)));
815 OutStreamer->emitInstruction(Inst: I, STI);
816}
817
818void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode,
819 unsigned Reg) {
820 MCInst I;
821 I.setOpcode(Opcode);
822 I.addOperand(Op: MCOperand::createReg(Reg));
823 OutStreamer->emitInstruction(Inst: I, STI);
824}
825
826void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI,
827 unsigned Opcode, unsigned Reg1,
828 unsigned Reg2) {
829 MCInst I;
830 //
831 // Because of the current td files for Mips32, the operands for MTC1
832 // appear backwards from their normal assembly order. It's not a trivial
833 // change to fix this in the td file so we adjust for it here.
834 //
835 if (Opcode == Mips::MTC1) {
836 unsigned Temp = Reg1;
837 Reg1 = Reg2;
838 Reg2 = Temp;
839 }
840 I.setOpcode(Opcode);
841 I.addOperand(Op: MCOperand::createReg(Reg: Reg1));
842 I.addOperand(Op: MCOperand::createReg(Reg: Reg2));
843 OutStreamer->emitInstruction(Inst: I, STI);
844}
845
846void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI,
847 unsigned Opcode, unsigned Reg1,
848 unsigned Reg2, unsigned Reg3) {
849 MCInst I;
850 I.setOpcode(Opcode);
851 I.addOperand(Op: MCOperand::createReg(Reg: Reg1));
852 I.addOperand(Op: MCOperand::createReg(Reg: Reg2));
853 I.addOperand(Op: MCOperand::createReg(Reg: Reg3));
854 OutStreamer->emitInstruction(Inst: I, STI);
855}
856
857void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI,
858 unsigned MovOpc, unsigned Reg1,
859 unsigned Reg2, unsigned FPReg1,
860 unsigned FPReg2, bool LE) {
861 if (!LE) {
862 unsigned temp = Reg1;
863 Reg1 = Reg2;
864 Reg2 = temp;
865 }
866 EmitInstrRegReg(STI, Opcode: MovOpc, Reg1, Reg2: FPReg1);
867 EmitInstrRegReg(STI, Opcode: MovOpc, Reg1: Reg2, Reg2: FPReg2);
868}
869
870void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI,
871 Mips16HardFloatInfo::FPParamVariant PV,
872 bool LE, bool ToFP) {
873 using namespace Mips16HardFloatInfo;
874
875 const MipsABIInfo &ABI = Subtarget->getABI();
876 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
877 switch (PV) {
878 case FSig:
879 EmitInstrRegReg(STI, Opcode: MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: Mips::F12);
880 break;
881 case FFSig:
882 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: ABI.getArgReg(I: 1), FPReg1: Mips::F12,
883 FPReg2: Mips::F14, LE);
884 break;
885 case FDSig:
886 EmitInstrRegReg(STI, Opcode: MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: Mips::F12);
887 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 2), Reg2: ABI.getArgReg(I: 3), FPReg1: Mips::F14,
888 FPReg2: Mips::F15, LE);
889 break;
890 case DSig:
891 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: ABI.getArgReg(I: 1), FPReg1: Mips::F12,
892 FPReg2: Mips::F13, LE);
893 break;
894 case DDSig:
895 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: ABI.getArgReg(I: 1), FPReg1: Mips::F12,
896 FPReg2: Mips::F13, LE);
897 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 2), Reg2: ABI.getArgReg(I: 3), FPReg1: Mips::F14,
898 FPReg2: Mips::F15, LE);
899 break;
900 case DFSig:
901 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: ABI.getArgReg(I: 1), FPReg1: Mips::F12,
902 FPReg2: Mips::F13, LE);
903 EmitInstrRegReg(STI, Opcode: MovOpc, Reg1: ABI.getArgReg(I: 2), Reg2: Mips::F14);
904 break;
905 case NoSig:
906 return;
907 }
908}
909
910void MipsAsmPrinter::EmitSwapFPIntRetval(
911 const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV,
912 bool LE) {
913 using namespace Mips16HardFloatInfo;
914
915 const MipsABIInfo &ABI = Subtarget->getABI();
916 unsigned MovOpc = Mips::MFC1;
917 switch (RV) {
918 case FRet:
919 EmitInstrRegReg(STI, Opcode: MovOpc, Reg1: ABI.getReturnReg(I: 0), Reg2: Mips::F0);
920 break;
921 case DRet:
922 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getReturnReg(I: 0), Reg2: ABI.getReturnReg(I: 1),
923 FPReg1: Mips::F0, FPReg2: Mips::F1, LE);
924 break;
925 case CFRet:
926 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getReturnReg(I: 0), Reg2: ABI.getReturnReg(I: 1),
927 FPReg1: Mips::F0, FPReg2: Mips::F1, LE);
928 break;
929 case CDRet:
930 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getReturnReg(I: 0), Reg2: ABI.getReturnReg(I: 1),
931 FPReg1: Mips::F0, FPReg2: Mips::F1, LE);
932 EmitMovFPIntPair(STI, MovOpc, Reg1: ABI.getArgReg(I: 0), Reg2: ABI.getArgReg(I: 1), FPReg1: Mips::F2,
933 FPReg2: Mips::F3, LE);
934 break;
935 case NoFPRet:
936 break;
937 }
938}
939
940void MipsAsmPrinter::EmitFPCallStub(
941 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
942 using namespace Mips16HardFloatInfo;
943
944 MCSymbol *MSymbol = OutContext.getOrCreateSymbol(Name: StringRef(Symbol));
945 bool LE = getDataLayout().isLittleEndian();
946 // Construct a local MCSubtargetInfo here.
947 // This is because the MachineFunction won't exist (but have not yet been
948 // freed) and since we're at the global level we can use the default
949 // constructed subtarget.
950 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
951 TheTriple: TM.getTargetTriple(), CPU: TM.getTargetCPU(), Features: TM.getTargetFeatureString()));
952
953 //
954 // .global xxxx
955 //
956 OutStreamer->emitSymbolAttribute(Symbol: MSymbol, Attribute: MCSA_Global);
957 const char *RetType;
958 //
959 // make the comment field identifying the return and parameter
960 // types of the floating point stub
961 // # Stub function to call rettype xxxx (params)
962 //
963 switch (Signature->RetSig) {
964 case FRet:
965 RetType = "float";
966 break;
967 case DRet:
968 RetType = "double";
969 break;
970 case CFRet:
971 RetType = "complex";
972 break;
973 case CDRet:
974 RetType = "double complex";
975 break;
976 case NoFPRet:
977 RetType = "";
978 break;
979 }
980 const char *Parms;
981 switch (Signature->ParamSig) {
982 case FSig:
983 Parms = "float";
984 break;
985 case FFSig:
986 Parms = "float, float";
987 break;
988 case FDSig:
989 Parms = "float, double";
990 break;
991 case DSig:
992 Parms = "double";
993 break;
994 case DDSig:
995 Parms = "double, double";
996 break;
997 case DFSig:
998 Parms = "double, float";
999 break;
1000 case NoSig:
1001 Parms = "";
1002 break;
1003 }
1004 OutStreamer->AddComment(T: "\t# Stub function to call " + Twine(RetType) + " " +
1005 Twine(Symbol) + " (" + Twine(Parms) + ")");
1006 //
1007 // probably not necessary but we save and restore the current section state
1008 //
1009 OutStreamer->pushSection();
1010 //
1011 // .section mips16.call.fpxxxx,"ax",@progbits
1012 //
1013 MCSectionELF *M = OutContext.getELFSection(
1014 Section: ".mips16.call.fp." + std::string(Symbol), Type: ELF::SHT_PROGBITS,
1015 Flags: ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
1016 OutStreamer->switchSection(Section: M);
1017 //
1018 // .align 2
1019 //
1020 OutStreamer->emitValueToAlignment(Alignment: Align(4));
1021 MipsTargetStreamer &TS = getTargetStreamer();
1022 //
1023 // .set nomips16
1024 // .set nomicromips
1025 //
1026 TS.emitDirectiveSetNoMips16();
1027 TS.emitDirectiveSetNoMicroMips();
1028 //
1029 // .ent __call_stub_fp_xxxx
1030 // .type __call_stub_fp_xxxx,@function
1031 // __call_stub_fp_xxxx:
1032 //
1033 std::string x = "__call_stub_fp_" + std::string(Symbol);
1034 MCSymbol *Stub = OutContext.getOrCreateSymbol(Name: StringRef(x));
1035 TS.emitDirectiveEnt(Symbol: *Stub);
1036 MCSymbol *MType =
1037 OutContext.getOrCreateSymbol(Name: "__call_stub_fp_" + Twine(Symbol));
1038 OutStreamer->emitSymbolAttribute(Symbol: MType, Attribute: MCSA_ELF_TypeFunction);
1039 OutStreamer->emitLabel(Symbol: Stub);
1040
1041 // Only handle non-pic for now.
1042 assert(!isPositionIndependent() &&
1043 "should not be here if we are compiling pic");
1044 TS.emitDirectiveSetReorder();
1045 //
1046 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
1047 // stubs without raw text but this current patch is for compiler generated
1048 // functions and they all return some value.
1049 // The calling sequence for non pic is different in that case and we need
1050 // to implement %lo and %hi in order to handle the case of no return value
1051 // See the corresponding method in Mips16HardFloat for details.
1052 //
1053 // mov the return address to S2.
1054 // we have no stack space to store it and we are about to make another call.
1055 // We need to make sure that the enclosing function knows to save S2
1056 // This should have already been handled.
1057 //
1058 // Mov $18, $31
1059
1060 EmitInstrRegRegReg(STI: *STI, Opcode: Mips::OR, Reg1: Subtarget->getABI().getSavedReg(I: 2),
1061 Reg2: Mips::RA, Reg3: Mips::R0);
1062
1063 EmitSwapFPIntParams(STI: *STI, PV: Signature->ParamSig, LE, ToFP: true);
1064
1065 // Jal xxxx
1066 //
1067 EmitJal(STI: *STI, Symbol: MSymbol);
1068
1069 // fix return values
1070 EmitSwapFPIntRetval(STI: *STI, RV: Signature->RetSig, LE);
1071 //
1072 // do the return
1073 // if (Signature->RetSig == NoFPRet)
1074 // llvm_unreachable("should not be any stubs here with no return value");
1075 // else
1076 EmitInstrReg(STI: *STI, Opcode: Mips::JR, Reg: Subtarget->getABI().getSavedReg(I: 2));
1077
1078 MCSymbol *Tmp = OutContext.createTempSymbol();
1079 OutStreamer->emitLabel(Symbol: Tmp);
1080 const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Symbol: Stub, Ctx&: OutContext);
1081 const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Symbol: Tmp, Ctx&: OutContext);
1082 const MCExpr *T_min_E = MCBinaryExpr::createSub(LHS: T, RHS: E, Ctx&: OutContext);
1083 OutStreamer->emitELFSize(Symbol: Stub, Value: T_min_E);
1084 TS.emitDirectiveEnd(Name: x);
1085 OutStreamer->popSection();
1086}
1087
1088void MipsAsmPrinter::emitEndOfAsmFile(Module &M) {
1089 // Emit needed stubs
1090 //
1091 for (std::map<
1092 const char *,
1093 const Mips16HardFloatInfo::FuncSignature *>::const_iterator
1094 it = StubsNeeded.begin();
1095 it != StubsNeeded.end(); ++it) {
1096 const char *Symbol = it->first;
1097 const Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1098 EmitFPCallStub(Symbol, Signature);
1099 }
1100 // return to the text section
1101 OutStreamer->switchSection(Section: OutContext.getObjectFileInfo()->getTextSection());
1102}
1103
1104void MipsAsmPrinter::EmitSled(const MachineInstr &MI, SledKind Kind) {
1105 const uint8_t NoopsInSledCount = Subtarget->isGP64bit() ? 15 : 11;
1106 // For mips32 we want to emit the following pattern:
1107 //
1108 // .Lxray_sled_N:
1109 // ALIGN
1110 // B .tmpN
1111 // 11 NOP instructions (44 bytes)
1112 // ADDIU T9, T9, 52
1113 // .tmpN
1114 //
1115 // We need the 44 bytes (11 instructions) because at runtime, we'd
1116 // be patching over the full 48 bytes (12 instructions) with the following
1117 // pattern:
1118 //
1119 // ADDIU SP, SP, -8
1120 // NOP
1121 // SW RA, 4(SP)
1122 // SW T9, 0(SP)
1123 // LUI T9, %hi(__xray_FunctionEntry/Exit)
1124 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit)
1125 // LUI T0, %hi(function_id)
1126 // JALR T9
1127 // ORI T0, T0, %lo(function_id)
1128 // LW T9, 0(SP)
1129 // LW RA, 4(SP)
1130 // ADDIU SP, SP, 8
1131 //
1132 // We add 52 bytes to t9 because we want to adjust the function pointer to
1133 // the actual start of function i.e. the address just after the noop sled.
1134 // We do this because gp displacement relocation is emitted at the start of
1135 // of the function i.e after the nop sled and to correctly calculate the
1136 // global offset table address, t9 must hold the address of the instruction
1137 // containing the gp displacement relocation.
1138 // FIXME: Is this correct for the static relocation model?
1139 //
1140 // For mips64 we want to emit the following pattern:
1141 //
1142 // .Lxray_sled_N:
1143 // ALIGN
1144 // B .tmpN
1145 // 15 NOP instructions (60 bytes)
1146 // .tmpN
1147 //
1148 // We need the 60 bytes (15 instructions) because at runtime, we'd
1149 // be patching over the full 64 bytes (16 instructions) with the following
1150 // pattern:
1151 //
1152 // DADDIU SP, SP, -16
1153 // NOP
1154 // SD RA, 8(SP)
1155 // SD T9, 0(SP)
1156 // LUI T9, %highest(__xray_FunctionEntry/Exit)
1157 // ORI T9, T9, %higher(__xray_FunctionEntry/Exit)
1158 // DSLL T9, T9, 16
1159 // ORI T9, T9, %hi(__xray_FunctionEntry/Exit)
1160 // DSLL T9, T9, 16
1161 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit)
1162 // LUI T0, %hi(function_id)
1163 // JALR T9
1164 // ADDIU T0, T0, %lo(function_id)
1165 // LD T9, 0(SP)
1166 // LD RA, 8(SP)
1167 // DADDIU SP, SP, 16
1168 //
1169 OutStreamer->emitCodeAlignment(Alignment: Align(4), STI: getSubtargetInfo());
1170 auto CurSled = OutContext.createTempSymbol(Name: "xray_sled_", AlwaysAddSuffix: true);
1171 OutStreamer->emitLabel(Symbol: CurSled);
1172 auto Target = OutContext.createTempSymbol();
1173
1174 // Emit "B .tmpN" instruction, which jumps over the nop sled to the actual
1175 // start of function
1176 const MCExpr *TargetExpr = MCSymbolRefExpr::create(Symbol: Target, Ctx&: OutContext);
1177 EmitToStreamer(
1178 S&: *OutStreamer,
1179 Inst: MCInstBuilder(Mips::BEQ).addReg(Reg: Mips::R0).addReg(Reg: Mips::R0).addExpr(
1180 Val: TargetExpr));
1181
1182 for (int8_t I = 0; I < NoopsInSledCount; I++)
1183 EmitToStreamer(
1184 S&: *OutStreamer,
1185 Inst: MCInstBuilder(Mips::SLL).addReg(Reg: Mips::R0).addReg(Reg: Mips::R0).addImm(Val: 0));
1186
1187 OutStreamer->emitLabel(Symbol: Target);
1188
1189 if (!Subtarget->isGP64bit()) {
1190 EmitToStreamer(S&: *OutStreamer, Inst: MCInstBuilder(Mips::ADDiu)
1191 .addReg(Reg: Mips::R25)
1192 .addReg(Reg: Mips::R25)
1193 .addImm(Val: 0x34));
1194 }
1195
1196 recordSled(Sled: CurSled, MI, Kind, Version: 2);
1197}
1198
1199void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI) {
1200 EmitSled(MI, Kind: SledKind::FUNCTION_ENTER);
1201}
1202
1203void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI) {
1204 EmitSled(MI, Kind: SledKind::FUNCTION_EXIT);
1205}
1206
1207void MipsAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI) {
1208 EmitSled(MI, Kind: SledKind::TAIL_CALL);
1209}
1210
1211void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1212 raw_ostream &OS) {
1213 // TODO: implement
1214}
1215
1216// Emit .dtprelword or .dtpreldword directive
1217// and value for debug thread local expression.
1218void MipsAsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
1219 if (auto *MipsExpr = dyn_cast<MCSpecifierExpr>(Val: Value)) {
1220 if (MipsExpr && MipsExpr->getSpecifier() == Mips::S_DTPREL) {
1221 switch (Size) {
1222 case 4:
1223 getTargetStreamer().emitDTPRel32Value(MipsExpr->getSubExpr());
1224 break;
1225 case 8:
1226 getTargetStreamer().emitDTPRel64Value(MipsExpr->getSubExpr());
1227 break;
1228 default:
1229 llvm_unreachable("Unexpected size of expression value.");
1230 }
1231 return;
1232 }
1233 }
1234 AsmPrinter::emitDebugValue(Value, Size);
1235}
1236
1237bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1238 return (Opcode == Mips::LONG_BRANCH_LUi
1239 || Opcode == Mips::LONG_BRANCH_LUi2Op
1240 || Opcode == Mips::LONG_BRANCH_LUi2Op_64
1241 || Opcode == Mips::LONG_BRANCH_ADDiu
1242 || Opcode == Mips::LONG_BRANCH_ADDiu2Op
1243 || Opcode == Mips::LONG_BRANCH_DADDiu
1244 || Opcode == Mips::LONG_BRANCH_DADDiu2Op);
1245}
1246
1247char MipsAsmPrinter::ID = 0;
1248
1249INITIALIZE_PASS(MipsAsmPrinter, "mips-asm-printer", "Mips Assembly Printer",
1250 false, false)
1251
1252// Force static initialization.
1253extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
1254LLVMInitializeMipsAsmPrinter() {
1255 RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget());
1256 RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget());
1257 RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target());
1258 RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget());
1259}
1260