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