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
71 using namespace llvm;
72
73 #define DEBUG_TYPE "mips-asm-printer"
74
75 extern cl::opt<bool> EmitJalrReloc;
76
getTargetStreamer() const77 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const {
78 return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer());
79 }
80
runOnMachineFunction(MachineFunction & MF)81 bool 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(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
lowerOperand(const MachineOperand & MO,MCOperand & MCOp)101 bool 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.
emitPseudoIndirectBranch(MCStreamer & OutStreamer,const MachineInstr * MI)110 void 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(MCOperand::createReg(ZeroReg));
141 }
142
143 lowerOperand(MI->getOperand(0), MCOp);
144 TmpInst0.addOperand(MCOp);
145
146 EmitToStreamer(OutStreamer, 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.
emitDirectiveRelocJalr(const MachineInstr & MI,MCContext & OutContext,TargetMachine & TM,MCStreamer & OutStreamer,const MipsSubtarget & Subtarget)156 static 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(MI.operands(), 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(OffsetLabel, OutContext);
169 const MCExpr *CaleeExpr =
170 MCSymbolRefExpr::create(Callee, OutContext);
171 OutStreamer.emitRelocDirective(
172 *OffsetExpr,
173 Subtarget.inMicroMipsMode() ? "R_MICROMIPS_JALR" : "R_MIPS_JALR",
174 CaleeExpr, SMLoc(), *TM.getMCSubtargetInfo());
175 OutStreamer.emitLabel(OffsetLabel);
176 return;
177 }
178 }
179 }
180 }
181
emitInstruction(const MachineInstr * MI)182 void 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(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(0).getImm();
215 unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex();
216
217 // If this is the first entry of the pool, mark it.
218 if (!InConstantPool) {
219 OutStreamer->emitDataRegion(MCDR_DataRegion);
220 InConstantPool = true;
221 }
222
223 OutStreamer->emitLabel(GetCPISymbol(LabelId));
224
225 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
226 if (MCPE.isMachineConstantPoolEntry())
227 emitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
228 else
229 emitGlobalConstant(MF->getDataLayout(), MCPE.Val.ConstVal);
230 return;
231 }
232
233 switch (Opc) {
234 case Mips::PATCHABLE_FUNCTION_ENTER:
235 LowerPATCHABLE_FUNCTION_ENTER(*MI);
236 return;
237 case Mips::PATCHABLE_FUNCTION_EXIT:
238 LowerPATCHABLE_FUNCTION_EXIT(*MI);
239 return;
240 case Mips::PATCHABLE_TAIL_CALL:
241 LowerPATCHABLE_TAIL_CALL(*MI);
242 return;
243 }
244
245 if (EmitJalrReloc &&
246 (MI->isReturn() || MI->isCall() || MI->isIndirectBranch())) {
247 emitDirectiveRelocJalr(*MI, OutContext, TM, *OutStreamer, *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(&*I, OutInst)) {
256 EmitToStreamer(*OutStreamer, 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, &*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(I->getOpcode()))
283 llvm_unreachable("Pseudo opcode found in emitInstruction()");
284
285 MCInst TmpInst0;
286 MCInstLowering.Lower(&*I, TmpInst0);
287 EmitToStreamer(*OutStreamer, 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.
printSavedRegsBitmask()328 void 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(Mips::GPR32RegClass) / 8;
339 unsigned FGR32RegSize = TRI->getRegSizeInBits(Mips::FGR32RegClass) / 8;
340 unsigned AFGR64RegSize = TRI->getRegSizeInBits(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
emitFrameDirective()381 void MipsAsmPrinter::emitFrameDirective() {
382 const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo();
383
384 Register stackReg = RI.getFrameRegister(*MF);
385 MCRegister returnReg = RI.getRARegister();
386 unsigned stackSize = MF->getFrameInfo().getStackSize();
387
388 getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
389 }
390
391 /// Emit Set directives.
getCurrentABIString() const392 const 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
emitFunctionEntryLabel()401 void 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(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
408
409 if (Subtarget->inMicroMipsMode()) {
410 TS.emitDirectiveSetMicroMips();
411 TS.setUsesMicroMips();
412 TS.updateABIInfo(*Subtarget);
413 } else
414 TS.emitDirectiveSetNoMicroMips();
415
416 if (Subtarget->inMips16Mode())
417 TS.emitDirectiveSetMips16();
418 else
419 TS.emitDirectiveSetNoMips16();
420
421 TS.emitDirectiveEnt(*CurrentFnSym);
422 OutStreamer->emitLabel(CurrentFnSym);
423 }
424
425 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
426 /// the first basic block in the function.
emitFunctionBodyStart()427 void MipsAsmPrinter::emitFunctionBodyStart() {
428 MipsTargetStreamer &TS = getTargetStreamer();
429
430 MCInstLowering.Initialize(&MF->getContext());
431
432 bool IsNakedFunction = MF->getFunction().hasFnAttribute(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.
emitFunctionBodyEnd()448 void 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(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(MCDR_DataRegionEnd);
466 }
467
emitBasicBlockEnd(const MachineBasicBlock & MBB)468 void 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.
PrintAsmOperand(const MachineInstr * MI,unsigned OpNum,const char * ExtraCode,raw_ostream & O)476 bool 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(OpNum);
483 switch (ExtraCode[0]) {
484 default:
485 // See if this is a generic print operand
486 return AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O);
487 case 'X': // hex const int
488 if (!MO.isImm())
489 return true;
490 O << "0x" << Twine::utohexstr(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(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(MO.getImm()))
511 return true;
512 O << Log2_64(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(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(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(MO.getReg());
571 if (w != Mips::NoRegister) {
572 O << '$' << MipsInstPrinter::getRegisterName(w);
573 return false;
574 }
575 break;
576 }
577 }
578 }
579
580 printOperand(MI, OpNum, O);
581 return false;
582 }
583
PrintAsmMemoryOperand(const MachineInstr * MI,unsigned OpNum,const char * ExtraCode,raw_ostream & O)584 bool 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(OpNum);
590 const MachineOperand &OffsetMO = MI->getOperand(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(BaseMO.getReg())
617 << ")";
618
619 return false;
620 }
621
printOperand(const MachineInstr * MI,int opNum,raw_ostream & O)622 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
623 raw_ostream &O) {
624 const MachineOperand &MO = MI->getOperand(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(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(O, MAI);
661 return;
662
663 case MachineOperand::MO_GlobalAddress:
664 PrintSymbolOperand(MO, O);
665 break;
666
667 case MachineOperand::MO_BlockAddress: {
668 MCSymbol *BA = GetBlockAddressSymbol(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
687 void MipsAsmPrinter::
printMemOperand(const MachineInstr * MI,int opNum,raw_ostream & O)688 printMemOperand(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+1, O);
705 O << "(";
706 printOperand(MI, opNum, O);
707 O << ")";
708 }
709
710 void MipsAsmPrinter::
printMemOperandEA(const MachineInstr * MI,int opNum,raw_ostream & O)711 printMemOperandEA(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+1, O);
717 }
718
printFCCOperand(const MachineInstr * MI,int opNum,raw_ostream & O)719 void MipsAsmPrinter::printFCCOperand(const MachineInstr *MI, int opNum,
720 raw_ostream &O) {
721 const MachineOperand &MO = MI->getOperand(opNum);
722 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
723 }
724
725 void MipsAsmPrinter::
printRegisterList(const MachineInstr * MI,int opNum,raw_ostream & O)726 printRegisterList(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, i, O);
730 }
731 }
732
emitStartOfAsmFile(Module & M)733 void 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("target-features"))
748 FS = F->getFnAttribute("target-features").getValueAsString();
749
750 std::string strFS = FS.str();
751 if (M.size() && F->getFnAttribute("use-soft-float").getValueAsBool())
752 strFS += strFS.empty() ? "+soft-float" : ",+soft-float";
753
754 // Compute MIPS architecture attributes based on the default subtarget
755 // that we'd have constructed.
756 // FIXME: For ifunc related functions we could iterate over and look
757 // for a feature string that doesn't match the default one.
758 StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU());
759 const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM);
760 const MipsSubtarget STI(TT, CPU, StringRef(strFS), MTM.isLittleEndian(),
761 MTM, std::nullopt);
762
763 bool IsABICalls = STI.isABICalls();
764 const MipsABIInfo &ABI = MTM.getABI();
765 if (IsABICalls) {
766 TS.emitDirectiveAbiCalls();
767 // FIXME: This condition should be a lot more complicated that it is here.
768 // Ideally it should test for properties of the ABI and not the ABI
769 // itself.
770 // For the moment, I'm only correcting enough to make MIPS-IV work.
771 if (!isPositionIndependent() && STI.hasSym32())
772 TS.emitDirectiveOptionPic0();
773 }
774
775 // Tell the assembler which ABI we are using
776 std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
777 OutStreamer->switchSection(
778 OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0));
779
780 // NaN: At the moment we only support:
781 // 1. .nan legacy (default)
782 // 2. .nan 2008
783 STI.isNaN2008() ? TS.emitDirectiveNaN2008() : TS.emitDirectiveNaNLegacy();
784
785 // TODO: handle O64 ABI
786
787 TS.updateABIInfo(STI);
788
789 // We should always emit a '.module fp=...' but binutils 2.24 does not
790 // accept it. We therefore emit it when it contradicts the ABI defaults
791 // (-mfpxx or -mfp64) and omit it otherwise.
792 if ((ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit())) ||
793 STI.useSoftFloat())
794 TS.emitDirectiveModuleFP();
795
796 // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
797 // accept it. We therefore emit it when it contradicts the default or an
798 // option has changed the default (i.e. FPXX) and omit it otherwise.
799 if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX()))
800 TS.emitDirectiveModuleOddSPReg();
801
802 // Switch to the .text section.
803 OutStreamer->switchSection(getObjFileLowering().getTextSection());
804 }
805 }
806
emitInlineAsmStart() const807 void MipsAsmPrinter::emitInlineAsmStart() const {
808 MipsTargetStreamer &TS = getTargetStreamer();
809
810 // GCC's choice of assembler options for inline assembly code ('at', 'macro'
811 // and 'reorder') is different from LLVM's choice for generated code ('noat',
812 // 'nomacro' and 'noreorder').
813 // In order to maintain compatibility with inline assembly code which depends
814 // on GCC's assembler options being used, we have to switch to those options
815 // for the duration of the inline assembly block and then switch back.
816 TS.emitDirectiveSetPush();
817 TS.emitDirectiveSetAt();
818 TS.emitDirectiveSetMacro();
819 TS.emitDirectiveSetReorder();
820 OutStreamer->addBlankLine();
821 }
822
emitInlineAsmEnd(const MCSubtargetInfo & StartInfo,const MCSubtargetInfo * EndInfo) const823 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
824 const MCSubtargetInfo *EndInfo) const {
825 OutStreamer->addBlankLine();
826 getTargetStreamer().emitDirectiveSetPop();
827 }
828
emitJumpTableEntry(const MachineJumpTableInfo & MJTI,const MachineBasicBlock * MBB,unsigned uid) const829 void MipsAsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo &MJTI,
830 const MachineBasicBlock *MBB,
831 unsigned uid) const {
832 MCSymbol *MBBSym = MBB->getSymbol();
833 switch (MJTI.getEntryKind()) {
834 case MachineJumpTableInfo::EK_BlockAddress:
835 OutStreamer->emitValue(MCSymbolRefExpr::create(MBBSym, OutContext),
836 getDataLayout().getPointerSize());
837 break;
838 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
839 // Each entry is a GP-relative value targeting the block symbol.
840 getTargetStreamer().emitGPRel32Value(
841 MCSymbolRefExpr::create(MBBSym, OutContext));
842 break;
843 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
844 getTargetStreamer().emitGPRel64Value(
845 MCSymbolRefExpr::create(MBBSym, OutContext));
846 break;
847 default:
848 llvm_unreachable("");
849 }
850 }
851
EmitJal(const MCSubtargetInfo & STI,MCSymbol * Symbol)852 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) {
853 MCInst I;
854 I.setOpcode(Mips::JAL);
855 I.addOperand(
856 MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext)));
857 OutStreamer->emitInstruction(I, STI);
858 }
859
EmitInstrReg(const MCSubtargetInfo & STI,unsigned Opcode,unsigned Reg)860 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode,
861 unsigned Reg) {
862 MCInst I;
863 I.setOpcode(Opcode);
864 I.addOperand(MCOperand::createReg(Reg));
865 OutStreamer->emitInstruction(I, STI);
866 }
867
EmitInstrRegReg(const MCSubtargetInfo & STI,unsigned Opcode,unsigned Reg1,unsigned Reg2)868 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI,
869 unsigned Opcode, unsigned Reg1,
870 unsigned Reg2) {
871 MCInst I;
872 //
873 // Because of the current td files for Mips32, the operands for MTC1
874 // appear backwards from their normal assembly order. It's not a trivial
875 // change to fix this in the td file so we adjust for it here.
876 //
877 if (Opcode == Mips::MTC1) {
878 unsigned Temp = Reg1;
879 Reg1 = Reg2;
880 Reg2 = Temp;
881 }
882 I.setOpcode(Opcode);
883 I.addOperand(MCOperand::createReg(Reg1));
884 I.addOperand(MCOperand::createReg(Reg2));
885 OutStreamer->emitInstruction(I, STI);
886 }
887
EmitInstrRegRegReg(const MCSubtargetInfo & STI,unsigned Opcode,unsigned Reg1,unsigned Reg2,unsigned Reg3)888 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI,
889 unsigned Opcode, unsigned Reg1,
890 unsigned Reg2, unsigned Reg3) {
891 MCInst I;
892 I.setOpcode(Opcode);
893 I.addOperand(MCOperand::createReg(Reg1));
894 I.addOperand(MCOperand::createReg(Reg2));
895 I.addOperand(MCOperand::createReg(Reg3));
896 OutStreamer->emitInstruction(I, STI);
897 }
898
EmitMovFPIntPair(const MCSubtargetInfo & STI,unsigned MovOpc,unsigned Reg1,unsigned Reg2,unsigned FPReg1,unsigned FPReg2,bool LE)899 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI,
900 unsigned MovOpc, unsigned Reg1,
901 unsigned Reg2, unsigned FPReg1,
902 unsigned FPReg2, bool LE) {
903 if (!LE) {
904 unsigned temp = Reg1;
905 Reg1 = Reg2;
906 Reg2 = temp;
907 }
908 EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1);
909 EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2);
910 }
911
EmitSwapFPIntParams(const MCSubtargetInfo & STI,Mips16HardFloatInfo::FPParamVariant PV,bool LE,bool ToFP)912 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI,
913 Mips16HardFloatInfo::FPParamVariant PV,
914 bool LE, bool ToFP) {
915 using namespace Mips16HardFloatInfo;
916
917 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
918 switch (PV) {
919 case FSig:
920 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
921 break;
922 case FFSig:
923 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
924 break;
925 case FDSig:
926 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
927 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
928 break;
929 case DSig:
930 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
931 break;
932 case DDSig:
933 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
934 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
935 break;
936 case DFSig:
937 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
938 EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14);
939 break;
940 case NoSig:
941 return;
942 }
943 }
944
EmitSwapFPIntRetval(const MCSubtargetInfo & STI,Mips16HardFloatInfo::FPReturnVariant RV,bool LE)945 void MipsAsmPrinter::EmitSwapFPIntRetval(
946 const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV,
947 bool LE) {
948 using namespace Mips16HardFloatInfo;
949
950 unsigned MovOpc = Mips::MFC1;
951 switch (RV) {
952 case FRet:
953 EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0);
954 break;
955 case DRet:
956 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
957 break;
958 case CFRet:
959 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
960 break;
961 case CDRet:
962 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
963 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
964 break;
965 case NoFPRet:
966 break;
967 }
968 }
969
EmitFPCallStub(const char * Symbol,const Mips16HardFloatInfo::FuncSignature * Signature)970 void MipsAsmPrinter::EmitFPCallStub(
971 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
972 using namespace Mips16HardFloatInfo;
973
974 MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol));
975 bool LE = getDataLayout().isLittleEndian();
976 // Construct a local MCSubtargetInfo here.
977 // This is because the MachineFunction won't exist (but have not yet been
978 // freed) and since we're at the global level we can use the default
979 // constructed subtarget.
980 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
981 TM.getTargetTriple().str(), TM.getTargetCPU(),
982 TM.getTargetFeatureString()));
983
984 //
985 // .global xxxx
986 //
987 OutStreamer->emitSymbolAttribute(MSymbol, MCSA_Global);
988 const char *RetType;
989 //
990 // make the comment field identifying the return and parameter
991 // types of the floating point stub
992 // # Stub function to call rettype xxxx (params)
993 //
994 switch (Signature->RetSig) {
995 case FRet:
996 RetType = "float";
997 break;
998 case DRet:
999 RetType = "double";
1000 break;
1001 case CFRet:
1002 RetType = "complex";
1003 break;
1004 case CDRet:
1005 RetType = "double complex";
1006 break;
1007 case NoFPRet:
1008 RetType = "";
1009 break;
1010 }
1011 const char *Parms;
1012 switch (Signature->ParamSig) {
1013 case FSig:
1014 Parms = "float";
1015 break;
1016 case FFSig:
1017 Parms = "float, float";
1018 break;
1019 case FDSig:
1020 Parms = "float, double";
1021 break;
1022 case DSig:
1023 Parms = "double";
1024 break;
1025 case DDSig:
1026 Parms = "double, double";
1027 break;
1028 case DFSig:
1029 Parms = "double, float";
1030 break;
1031 case NoSig:
1032 Parms = "";
1033 break;
1034 }
1035 OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " +
1036 Twine(Symbol) + " (" + Twine(Parms) + ")");
1037 //
1038 // probably not necessary but we save and restore the current section state
1039 //
1040 OutStreamer->pushSection();
1041 //
1042 // .section mips16.call.fpxxxx,"ax",@progbits
1043 //
1044 MCSectionELF *M = OutContext.getELFSection(
1045 ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
1046 ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
1047 OutStreamer->switchSection(M);
1048 //
1049 // .align 2
1050 //
1051 OutStreamer->emitValueToAlignment(Align(4));
1052 MipsTargetStreamer &TS = getTargetStreamer();
1053 //
1054 // .set nomips16
1055 // .set nomicromips
1056 //
1057 TS.emitDirectiveSetNoMips16();
1058 TS.emitDirectiveSetNoMicroMips();
1059 //
1060 // .ent __call_stub_fp_xxxx
1061 // .type __call_stub_fp_xxxx,@function
1062 // __call_stub_fp_xxxx:
1063 //
1064 std::string x = "__call_stub_fp_" + std::string(Symbol);
1065 MCSymbolELF *Stub =
1066 cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x)));
1067 TS.emitDirectiveEnt(*Stub);
1068 MCSymbol *MType =
1069 OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
1070 OutStreamer->emitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
1071 OutStreamer->emitLabel(Stub);
1072
1073 // Only handle non-pic for now.
1074 assert(!isPositionIndependent() &&
1075 "should not be here if we are compiling pic");
1076 TS.emitDirectiveSetReorder();
1077 //
1078 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
1079 // stubs without raw text but this current patch is for compiler generated
1080 // functions and they all return some value.
1081 // The calling sequence for non pic is different in that case and we need
1082 // to implement %lo and %hi in order to handle the case of no return value
1083 // See the corresponding method in Mips16HardFloat for details.
1084 //
1085 // mov the return address to S2.
1086 // we have no stack space to store it and we are about to make another call.
1087 // We need to make sure that the enclosing function knows to save S2
1088 // This should have already been handled.
1089 //
1090 // Mov $18, $31
1091
1092 EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO);
1093
1094 EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true);
1095
1096 // Jal xxxx
1097 //
1098 EmitJal(*STI, MSymbol);
1099
1100 // fix return values
1101 EmitSwapFPIntRetval(*STI, Signature->RetSig, LE);
1102 //
1103 // do the return
1104 // if (Signature->RetSig == NoFPRet)
1105 // llvm_unreachable("should not be any stubs here with no return value");
1106 // else
1107 EmitInstrReg(*STI, Mips::JR, Mips::S2);
1108
1109 MCSymbol *Tmp = OutContext.createTempSymbol();
1110 OutStreamer->emitLabel(Tmp);
1111 const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext);
1112 const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext);
1113 const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext);
1114 OutStreamer->emitELFSize(Stub, T_min_E);
1115 TS.emitDirectiveEnd(x);
1116 OutStreamer->popSection();
1117 }
1118
emitEndOfAsmFile(Module & M)1119 void MipsAsmPrinter::emitEndOfAsmFile(Module &M) {
1120 // Emit needed stubs
1121 //
1122 for (std::map<
1123 const char *,
1124 const Mips16HardFloatInfo::FuncSignature *>::const_iterator
1125 it = StubsNeeded.begin();
1126 it != StubsNeeded.end(); ++it) {
1127 const char *Symbol = it->first;
1128 const Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1129 EmitFPCallStub(Symbol, Signature);
1130 }
1131 // return to the text section
1132 OutStreamer->switchSection(OutContext.getObjectFileInfo()->getTextSection());
1133 }
1134
EmitSled(const MachineInstr & MI,SledKind Kind)1135 void MipsAsmPrinter::EmitSled(const MachineInstr &MI, SledKind Kind) {
1136 const uint8_t NoopsInSledCount = Subtarget->isGP64bit() ? 15 : 11;
1137 // For mips32 we want to emit the following pattern:
1138 //
1139 // .Lxray_sled_N:
1140 // ALIGN
1141 // B .tmpN
1142 // 11 NOP instructions (44 bytes)
1143 // ADDIU T9, T9, 52
1144 // .tmpN
1145 //
1146 // We need the 44 bytes (11 instructions) because at runtime, we'd
1147 // be patching over the full 48 bytes (12 instructions) with the following
1148 // pattern:
1149 //
1150 // ADDIU SP, SP, -8
1151 // NOP
1152 // SW RA, 4(SP)
1153 // SW T9, 0(SP)
1154 // LUI T9, %hi(__xray_FunctionEntry/Exit)
1155 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit)
1156 // LUI T0, %hi(function_id)
1157 // JALR T9
1158 // ORI T0, T0, %lo(function_id)
1159 // LW T9, 0(SP)
1160 // LW RA, 4(SP)
1161 // ADDIU SP, SP, 8
1162 //
1163 // We add 52 bytes to t9 because we want to adjust the function pointer to
1164 // the actual start of function i.e. the address just after the noop sled.
1165 // We do this because gp displacement relocation is emitted at the start of
1166 // of the function i.e after the nop sled and to correctly calculate the
1167 // global offset table address, t9 must hold the address of the instruction
1168 // containing the gp displacement relocation.
1169 // FIXME: Is this correct for the static relocation model?
1170 //
1171 // For mips64 we want to emit the following pattern:
1172 //
1173 // .Lxray_sled_N:
1174 // ALIGN
1175 // B .tmpN
1176 // 15 NOP instructions (60 bytes)
1177 // .tmpN
1178 //
1179 // We need the 60 bytes (15 instructions) because at runtime, we'd
1180 // be patching over the full 64 bytes (16 instructions) with the following
1181 // pattern:
1182 //
1183 // DADDIU SP, SP, -16
1184 // NOP
1185 // SD RA, 8(SP)
1186 // SD T9, 0(SP)
1187 // LUI T9, %highest(__xray_FunctionEntry/Exit)
1188 // ORI T9, T9, %higher(__xray_FunctionEntry/Exit)
1189 // DSLL T9, T9, 16
1190 // ORI T9, T9, %hi(__xray_FunctionEntry/Exit)
1191 // DSLL T9, T9, 16
1192 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit)
1193 // LUI T0, %hi(function_id)
1194 // JALR T9
1195 // ADDIU T0, T0, %lo(function_id)
1196 // LD T9, 0(SP)
1197 // LD RA, 8(SP)
1198 // DADDIU SP, SP, 16
1199 //
1200 OutStreamer->emitCodeAlignment(Align(4), &getSubtargetInfo());
1201 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1202 OutStreamer->emitLabel(CurSled);
1203 auto Target = OutContext.createTempSymbol();
1204
1205 // Emit "B .tmpN" instruction, which jumps over the nop sled to the actual
1206 // start of function
1207 const MCExpr *TargetExpr = MCSymbolRefExpr::create(Target, OutContext);
1208 EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::BEQ)
1209 .addReg(Mips::ZERO)
1210 .addReg(Mips::ZERO)
1211 .addExpr(TargetExpr));
1212
1213 for (int8_t I = 0; I < NoopsInSledCount; I++)
1214 EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::SLL)
1215 .addReg(Mips::ZERO)
1216 .addReg(Mips::ZERO)
1217 .addImm(0));
1218
1219 OutStreamer->emitLabel(Target);
1220
1221 if (!Subtarget->isGP64bit()) {
1222 EmitToStreamer(*OutStreamer,
1223 MCInstBuilder(Mips::ADDiu)
1224 .addReg(Mips::T9)
1225 .addReg(Mips::T9)
1226 .addImm(0x34));
1227 }
1228
1229 recordSled(CurSled, MI, Kind, 2);
1230 }
1231
LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr & MI)1232 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI) {
1233 EmitSled(MI, SledKind::FUNCTION_ENTER);
1234 }
1235
LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr & MI)1236 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI) {
1237 EmitSled(MI, SledKind::FUNCTION_EXIT);
1238 }
1239
LowerPATCHABLE_TAIL_CALL(const MachineInstr & MI)1240 void MipsAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI) {
1241 EmitSled(MI, SledKind::TAIL_CALL);
1242 }
1243
PrintDebugValueComment(const MachineInstr * MI,raw_ostream & OS)1244 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1245 raw_ostream &OS) {
1246 // TODO: implement
1247 }
1248
1249 // Emit .dtprelword or .dtpreldword directive
1250 // and value for debug thread local expression.
emitDebugValue(const MCExpr * Value,unsigned Size) const1251 void MipsAsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const {
1252 if (auto *MipsExpr = dyn_cast<MCSpecifierExpr>(Value)) {
1253 if (MipsExpr && MipsExpr->getSpecifier() == Mips::S_DTPREL) {
1254 switch (Size) {
1255 case 4:
1256 getTargetStreamer().emitDTPRel32Value(MipsExpr->getSubExpr());
1257 break;
1258 case 8:
1259 getTargetStreamer().emitDTPRel64Value(MipsExpr->getSubExpr());
1260 break;
1261 default:
1262 llvm_unreachable("Unexpected size of expression value.");
1263 }
1264 return;
1265 }
1266 }
1267 AsmPrinter::emitDebugValue(Value, Size);
1268 }
1269
1270 // Align all targets of indirect branches on bundle size. Used only if target
1271 // is NaCl.
NaClAlignIndirectJumpTargets(MachineFunction & MF)1272 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
1273 // Align all blocks that are jumped to through jump table.
1274 if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
1275 const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
1276 for (const auto &I : JT) {
1277 const std::vector<MachineBasicBlock *> &MBBs = I.MBBs;
1278
1279 for (MachineBasicBlock *MBB : MBBs)
1280 MBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1281 }
1282 }
1283
1284 // If basic block address is taken, block can be target of indirect branch.
1285 for (auto &MBB : MF) {
1286 if (MBB.hasAddressTaken())
1287 MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1288 }
1289 }
1290
isLongBranchPseudo(int Opcode) const1291 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1292 return (Opcode == Mips::LONG_BRANCH_LUi
1293 || Opcode == Mips::LONG_BRANCH_LUi2Op
1294 || Opcode == Mips::LONG_BRANCH_LUi2Op_64
1295 || Opcode == Mips::LONG_BRANCH_ADDiu
1296 || Opcode == Mips::LONG_BRANCH_ADDiu2Op
1297 || Opcode == Mips::LONG_BRANCH_DADDiu
1298 || Opcode == Mips::LONG_BRANCH_DADDiu2Op);
1299 }
1300
1301 char MipsAsmPrinter::ID = 0;
1302
1303 INITIALIZE_PASS(MipsAsmPrinter, "mips-asm-printer", "Mips Assembly Printer",
1304 false, false)
1305
1306 // Force static initialization.
1307 extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
LLVMInitializeMipsAsmPrinter()1308 LLVMInitializeMipsAsmPrinter() {
1309 RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget());
1310 RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget());
1311 RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target());
1312 RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget());
1313 }
1314