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