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