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/IR/Attributes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/InlineAsm.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCInst.h"
48 #include "llvm/MC/MCInstBuilder.h"
49 #include "llvm/MC/MCObjectFileInfo.h"
50 #include "llvm/MC/MCSectionELF.h"
51 #include "llvm/MC/MCSymbol.h"
52 #include "llvm/MC/MCSymbolELF.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetMachine.h"
58 #include "llvm/Target/TargetRegisterInfo.h"
59 #include "llvm/Target/TargetSubtargetInfo.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   } else
365     TS.emitDirectiveSetNoMicroMips();
366 
367   if (Subtarget->inMips16Mode())
368     TS.emitDirectiveSetMips16();
369   else
370     TS.emitDirectiveSetNoMips16();
371 
372   TS.emitDirectiveEnt(*CurrentFnSym);
373   OutStreamer->EmitLabel(CurrentFnSym);
374 }
375 
376 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
377 /// the first basic block in the function.
378 void MipsAsmPrinter::EmitFunctionBodyStart() {
379   MipsTargetStreamer &TS = getTargetStreamer();
380 
381   MCInstLowering.Initialize(&MF->getContext());
382 
383   bool IsNakedFunction = MF->getFunction()->hasFnAttribute(Attribute::Naked);
384   if (!IsNakedFunction)
385     emitFrameDirective();
386 
387   if (!IsNakedFunction)
388     printSavedRegsBitmask();
389 
390   if (!Subtarget->inMips16Mode()) {
391     TS.emitDirectiveSetNoReorder();
392     TS.emitDirectiveSetNoMacro();
393     TS.emitDirectiveSetNoAt();
394   }
395 }
396 
397 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
398 /// the last basic block in the function.
399 void MipsAsmPrinter::EmitFunctionBodyEnd() {
400   MipsTargetStreamer &TS = getTargetStreamer();
401 
402   // There are instruction for this macros, but they must
403   // always be at the function end, and we can't emit and
404   // break with BB logic.
405   if (!Subtarget->inMips16Mode()) {
406     TS.emitDirectiveSetAt();
407     TS.emitDirectiveSetMacro();
408     TS.emitDirectiveSetReorder();
409   }
410   TS.emitDirectiveEnd(CurrentFnSym->getName());
411   // Make sure to terminate any constant pools that were at the end
412   // of the function.
413   if (!InConstantPool)
414     return;
415   InConstantPool = false;
416   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
417 }
418 
419 void MipsAsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
420   MipsTargetStreamer &TS = getTargetStreamer();
421   if (MBB.empty())
422     TS.emitDirectiveInsn();
423 }
424 
425 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
426 /// exactly one predecessor and the control transfer mechanism between
427 /// the predecessor and this block is a fall-through.
428 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
429                                                        MBB) const {
430   // The predecessor has to be immediately before this block.
431   const MachineBasicBlock *Pred = *MBB->pred_begin();
432 
433   // If the predecessor is a switch statement, assume a jump table
434   // implementation, so it is not a fall through.
435   if (const BasicBlock *bb = Pred->getBasicBlock())
436     if (isa<SwitchInst>(bb->getTerminator()))
437       return false;
438 
439   // If this is a landing pad, it isn't a fall through.  If it has no preds,
440   // then nothing falls through to it.
441   if (MBB->isEHPad() || MBB->pred_empty())
442     return false;
443 
444   // If there isn't exactly one predecessor, it can't be a fall through.
445   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
446   ++PI2;
447 
448   if (PI2 != MBB->pred_end())
449     return false;
450 
451   // The predecessor has to be immediately before this block.
452   if (!Pred->isLayoutSuccessor(MBB))
453     return false;
454 
455   // If the block is completely empty, then it definitely does fall through.
456   if (Pred->empty())
457     return true;
458 
459   // Otherwise, check the last instruction.
460   // Check if the last terminator is an unconditional branch.
461   MachineBasicBlock::const_iterator I = Pred->end();
462   while (I != Pred->begin() && !(--I)->isTerminator()) ;
463 
464   return !I->isBarrier();
465 }
466 
467 // Print out an operand for an inline asm expression.
468 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
469                                      unsigned AsmVariant, const char *ExtraCode,
470                                      raw_ostream &O) {
471   // Does this asm operand have a single letter operand modifier?
472   if (ExtraCode && ExtraCode[0]) {
473     if (ExtraCode[1] != 0) return true; // Unknown modifier.
474 
475     const MachineOperand &MO = MI->getOperand(OpNum);
476     switch (ExtraCode[0]) {
477     default:
478       // See if this is a generic print operand
479       return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
480     case 'X': // hex const int
481       if ((MO.getType()) != MachineOperand::MO_Immediate)
482         return true;
483       O << "0x" << Twine::utohexstr(MO.getImm());
484       return false;
485     case 'x': // hex const int (low 16 bits)
486       if ((MO.getType()) != MachineOperand::MO_Immediate)
487         return true;
488       O << "0x" << Twine::utohexstr(MO.getImm() & 0xffff);
489       return false;
490     case 'd': // decimal const int
491       if ((MO.getType()) != MachineOperand::MO_Immediate)
492         return true;
493       O << MO.getImm();
494       return false;
495     case 'm': // decimal const int minus 1
496       if ((MO.getType()) != MachineOperand::MO_Immediate)
497         return true;
498       O << MO.getImm() - 1;
499       return false;
500     case 'z':
501       // $0 if zero, regular printing otherwise
502       if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) {
503         O << "$0";
504         return false;
505       }
506       // If not, call printOperand as normal.
507       break;
508     case 'D': // Second part of a double word register operand
509     case 'L': // Low order register of a double word register operand
510     case 'M': // High order register of a double word register operand
511     {
512       if (OpNum == 0)
513         return true;
514       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
515       if (!FlagsOP.isImm())
516         return true;
517       unsigned Flags = FlagsOP.getImm();
518       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
519       // Number of registers represented by this operand. We are looking
520       // for 2 for 32 bit mode and 1 for 64 bit mode.
521       if (NumVals != 2) {
522         if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
523           unsigned Reg = MO.getReg();
524           O << '$' << MipsInstPrinter::getRegisterName(Reg);
525           return false;
526         }
527         return true;
528       }
529 
530       unsigned RegOp = OpNum;
531       if (!Subtarget->isGP64bit()){
532         // Endianness reverses which register holds the high or low value
533         // between M and L.
534         switch(ExtraCode[0]) {
535         case 'M':
536           RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
537           break;
538         case 'L':
539           RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
540           break;
541         case 'D': // Always the second part
542           RegOp = OpNum + 1;
543         }
544         if (RegOp >= MI->getNumOperands())
545           return true;
546         const MachineOperand &MO = MI->getOperand(RegOp);
547         if (!MO.isReg())
548           return true;
549         unsigned Reg = MO.getReg();
550         O << '$' << MipsInstPrinter::getRegisterName(Reg);
551         return false;
552       }
553     }
554     case 'w':
555       // Print MSA registers for the 'f' constraint
556       // In LLVM, the 'w' modifier doesn't need to do anything.
557       // We can just call printOperand as normal.
558       break;
559     }
560   }
561 
562   printOperand(MI, OpNum, O);
563   return false;
564 }
565 
566 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
567                                            unsigned OpNum, unsigned AsmVariant,
568                                            const char *ExtraCode,
569                                            raw_ostream &O) {
570   assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands");
571   const MachineOperand &BaseMO = MI->getOperand(OpNum);
572   const MachineOperand &OffsetMO = MI->getOperand(OpNum + 1);
573   assert(BaseMO.isReg() && "Unexpected base pointer for inline asm memory operand.");
574   assert(OffsetMO.isImm() && "Unexpected offset for inline asm memory operand.");
575   int Offset = OffsetMO.getImm();
576 
577   // Currently we are expecting either no ExtraCode or 'D'
578   if (ExtraCode) {
579     if (ExtraCode[0] == 'D')
580       Offset += 4;
581     else
582       return true; // Unknown modifier.
583     // FIXME: M = high order bits
584     // FIXME: L = low order bits
585   }
586 
587   O << Offset << "($" << MipsInstPrinter::getRegisterName(BaseMO.getReg()) << ")";
588 
589   return false;
590 }
591 
592 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
593                                   raw_ostream &O) {
594   const MachineOperand &MO = MI->getOperand(opNum);
595   bool closeP = false;
596 
597   if (MO.getTargetFlags())
598     closeP = true;
599 
600   switch(MO.getTargetFlags()) {
601   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
602   case MipsII::MO_GOT_CALL: O << "%call16("; break;
603   case MipsII::MO_GOT:      O << "%got(";    break;
604   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
605   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
606   case MipsII::MO_HIGHER:   O << "%higher("; break;
607   case MipsII::MO_HIGHEST:  O << "%highest(("; break;
608   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
609   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
610   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
611   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
612   case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
613   case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
614   case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
615   case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
616   case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
617   }
618 
619   switch (MO.getType()) {
620     case MachineOperand::MO_Register:
621       O << '$'
622         << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
623       break;
624 
625     case MachineOperand::MO_Immediate:
626       O << MO.getImm();
627       break;
628 
629     case MachineOperand::MO_MachineBasicBlock:
630       MO.getMBB()->getSymbol()->print(O, MAI);
631       return;
632 
633     case MachineOperand::MO_GlobalAddress:
634       getSymbol(MO.getGlobal())->print(O, MAI);
635       break;
636 
637     case MachineOperand::MO_BlockAddress: {
638       MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
639       O << BA->getName();
640       break;
641     }
642 
643     case MachineOperand::MO_ConstantPoolIndex:
644       O << getDataLayout().getPrivateGlobalPrefix() << "CPI"
645         << getFunctionNumber() << "_" << MO.getIndex();
646       if (MO.getOffset())
647         O << "+" << MO.getOffset();
648       break;
649 
650     default:
651       llvm_unreachable("<unknown operand type>");
652   }
653 
654   if (closeP) O << ")";
655 }
656 
657 void MipsAsmPrinter::
658 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
659   // Load/Store memory operands -- imm($reg)
660   // If PIC target the target is loaded as the
661   // pattern lw $25,%call16($28)
662 
663   // opNum can be invalid if instruction has reglist as operand.
664   // MemOperand is always last operand of instruction (base + offset).
665   switch (MI->getOpcode()) {
666   default:
667     break;
668   case Mips::SWM32_MM:
669   case Mips::LWM32_MM:
670     opNum = MI->getNumOperands() - 2;
671     break;
672   }
673 
674   printOperand(MI, opNum+1, O);
675   O << "(";
676   printOperand(MI, opNum, O);
677   O << ")";
678 }
679 
680 void MipsAsmPrinter::
681 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
682   // when using stack locations for not load/store instructions
683   // print the same way as all normal 3 operand instructions.
684   printOperand(MI, opNum, O);
685   O << ", ";
686   printOperand(MI, opNum+1, O);
687 }
688 
689 void MipsAsmPrinter::
690 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
691                 const char *Modifier) {
692   const MachineOperand &MO = MI->getOperand(opNum);
693   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
694 }
695 
696 void MipsAsmPrinter::
697 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) {
698   for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) {
699     if (i != opNum) O << ", ";
700     printOperand(MI, i, O);
701   }
702 }
703 
704 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
705   MipsTargetStreamer &TS = getTargetStreamer();
706 
707   // MipsTargetStreamer has an initialization order problem when emitting an
708   // object file directly (see MipsTargetELFStreamer for full details). Work
709   // around it by re-initializing the PIC state here.
710   TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent());
711 
712   // Compute MIPS architecture attributes based on the default subtarget
713   // that we'd have constructed. Module level directives aren't LTO
714   // clean anyhow.
715   // FIXME: For ifunc related functions we could iterate over and look
716   // for a feature string that doesn't match the default one.
717   const Triple &TT = TM.getTargetTriple();
718   StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU());
719   StringRef FS = TM.getTargetFeatureString();
720   const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM);
721   const MipsSubtarget STI(TT, CPU, FS, MTM.isLittleEndian(), MTM, 0);
722 
723   bool IsABICalls = STI.isABICalls();
724   const MipsABIInfo &ABI = MTM.getABI();
725   if (IsABICalls) {
726     TS.emitDirectiveAbiCalls();
727     // FIXME: This condition should be a lot more complicated that it is here.
728     //        Ideally it should test for properties of the ABI and not the ABI
729     //        itself.
730     //        For the moment, I'm only correcting enough to make MIPS-IV work.
731     if (!isPositionIndependent() && STI.hasSym32())
732       TS.emitDirectiveOptionPic0();
733   }
734 
735   // Tell the assembler which ABI we are using
736   std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
737   OutStreamer->SwitchSection(
738       OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0));
739 
740   // NaN: At the moment we only support:
741   // 1. .nan legacy (default)
742   // 2. .nan 2008
743   STI.isNaN2008() ? TS.emitDirectiveNaN2008()
744                   : TS.emitDirectiveNaNLegacy();
745 
746   // TODO: handle O64 ABI
747 
748   TS.updateABIInfo(STI);
749 
750   // We should always emit a '.module fp=...' but binutils 2.24 does not accept
751   // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or
752   // -mfp64) and omit it otherwise.
753   if (ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit()))
754     TS.emitDirectiveModuleFP();
755 
756   // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
757   // accept it. We therefore emit it when it contradicts the default or an
758   // option has changed the default (i.e. FPXX) and omit it otherwise.
759   if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX()))
760     TS.emitDirectiveModuleOddSPReg();
761 }
762 
763 void MipsAsmPrinter::emitInlineAsmStart() const {
764   MipsTargetStreamer &TS = getTargetStreamer();
765 
766   // GCC's choice of assembler options for inline assembly code ('at', 'macro'
767   // and 'reorder') is different from LLVM's choice for generated code ('noat',
768   // 'nomacro' and 'noreorder').
769   // In order to maintain compatibility with inline assembly code which depends
770   // on GCC's assembler options being used, we have to switch to those options
771   // for the duration of the inline assembly block and then switch back.
772   TS.emitDirectiveSetPush();
773   TS.emitDirectiveSetAt();
774   TS.emitDirectiveSetMacro();
775   TS.emitDirectiveSetReorder();
776   OutStreamer->AddBlankLine();
777 }
778 
779 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
780                                       const MCSubtargetInfo *EndInfo) const {
781   OutStreamer->AddBlankLine();
782   getTargetStreamer().emitDirectiveSetPop();
783 }
784 
785 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) {
786   MCInst I;
787   I.setOpcode(Mips::JAL);
788   I.addOperand(
789       MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext)));
790   OutStreamer->EmitInstruction(I, STI);
791 }
792 
793 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode,
794                                   unsigned Reg) {
795   MCInst I;
796   I.setOpcode(Opcode);
797   I.addOperand(MCOperand::createReg(Reg));
798   OutStreamer->EmitInstruction(I, STI);
799 }
800 
801 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI,
802                                      unsigned Opcode, unsigned Reg1,
803                                      unsigned Reg2) {
804   MCInst I;
805   //
806   // Because of the current td files for Mips32, the operands for MTC1
807   // appear backwards from their normal assembly order. It's not a trivial
808   // change to fix this in the td file so we adjust for it here.
809   //
810   if (Opcode == Mips::MTC1) {
811     unsigned Temp = Reg1;
812     Reg1 = Reg2;
813     Reg2 = Temp;
814   }
815   I.setOpcode(Opcode);
816   I.addOperand(MCOperand::createReg(Reg1));
817   I.addOperand(MCOperand::createReg(Reg2));
818   OutStreamer->EmitInstruction(I, STI);
819 }
820 
821 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI,
822                                         unsigned Opcode, unsigned Reg1,
823                                         unsigned Reg2, unsigned Reg3) {
824   MCInst I;
825   I.setOpcode(Opcode);
826   I.addOperand(MCOperand::createReg(Reg1));
827   I.addOperand(MCOperand::createReg(Reg2));
828   I.addOperand(MCOperand::createReg(Reg3));
829   OutStreamer->EmitInstruction(I, STI);
830 }
831 
832 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI,
833                                       unsigned MovOpc, unsigned Reg1,
834                                       unsigned Reg2, unsigned FPReg1,
835                                       unsigned FPReg2, bool LE) {
836   if (!LE) {
837     unsigned temp = Reg1;
838     Reg1 = Reg2;
839     Reg2 = temp;
840   }
841   EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1);
842   EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2);
843 }
844 
845 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI,
846                                          Mips16HardFloatInfo::FPParamVariant PV,
847                                          bool LE, bool ToFP) {
848   using namespace Mips16HardFloatInfo;
849 
850   unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
851   switch (PV) {
852   case FSig:
853     EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
854     break;
855   case FFSig:
856     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
857     break;
858   case FDSig:
859     EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
860     EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
861     break;
862   case DSig:
863     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
864     break;
865   case DDSig:
866     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
867     EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
868     break;
869   case DFSig:
870     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
871     EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14);
872     break;
873   case NoSig:
874     return;
875   }
876 }
877 
878 void MipsAsmPrinter::EmitSwapFPIntRetval(
879     const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV,
880     bool LE) {
881   using namespace Mips16HardFloatInfo;
882 
883   unsigned MovOpc = Mips::MFC1;
884   switch (RV) {
885   case FRet:
886     EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0);
887     break;
888   case DRet:
889     EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
890     break;
891   case CFRet:
892     EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
893     break;
894   case CDRet:
895     EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
896     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
897     break;
898   case NoFPRet:
899     break;
900   }
901 }
902 
903 void MipsAsmPrinter::EmitFPCallStub(
904     const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
905   using namespace Mips16HardFloatInfo;
906 
907   MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol));
908   bool LE = getDataLayout().isLittleEndian();
909   // Construct a local MCSubtargetInfo here.
910   // This is because the MachineFunction won't exist (but have not yet been
911   // freed) and since we're at the global level we can use the default
912   // constructed subtarget.
913   std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
914       TM.getTargetTriple().str(), TM.getTargetCPU(),
915       TM.getTargetFeatureString()));
916 
917   //
918   // .global xxxx
919   //
920   OutStreamer->EmitSymbolAttribute(MSymbol, MCSA_Global);
921   const char *RetType;
922   //
923   // make the comment field identifying the return and parameter
924   // types of the floating point stub
925   // # Stub function to call rettype xxxx (params)
926   //
927   switch (Signature->RetSig) {
928   case FRet:
929     RetType = "float";
930     break;
931   case DRet:
932     RetType = "double";
933     break;
934   case CFRet:
935     RetType = "complex";
936     break;
937   case CDRet:
938     RetType = "double complex";
939     break;
940   case NoFPRet:
941     RetType = "";
942     break;
943   }
944   const char *Parms;
945   switch (Signature->ParamSig) {
946   case FSig:
947     Parms = "float";
948     break;
949   case FFSig:
950     Parms = "float, float";
951     break;
952   case FDSig:
953     Parms = "float, double";
954     break;
955   case DSig:
956     Parms = "double";
957     break;
958   case DDSig:
959     Parms = "double, double";
960     break;
961   case DFSig:
962     Parms = "double, float";
963     break;
964   case NoSig:
965     Parms = "";
966     break;
967   }
968   OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " +
969                           Twine(Symbol) + " (" + Twine(Parms) + ")");
970   //
971   // probably not necessary but we save and restore the current section state
972   //
973   OutStreamer->PushSection();
974   //
975   // .section mips16.call.fpxxxx,"ax",@progbits
976   //
977   MCSectionELF *M = OutContext.getELFSection(
978       ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
979       ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
980   OutStreamer->SwitchSection(M, nullptr);
981   //
982   // .align 2
983   //
984   OutStreamer->EmitValueToAlignment(4);
985   MipsTargetStreamer &TS = getTargetStreamer();
986   //
987   // .set nomips16
988   // .set nomicromips
989   //
990   TS.emitDirectiveSetNoMips16();
991   TS.emitDirectiveSetNoMicroMips();
992   //
993   // .ent __call_stub_fp_xxxx
994   // .type  __call_stub_fp_xxxx,@function
995   //  __call_stub_fp_xxxx:
996   //
997   std::string x = "__call_stub_fp_" + std::string(Symbol);
998   MCSymbolELF *Stub =
999       cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x)));
1000   TS.emitDirectiveEnt(*Stub);
1001   MCSymbol *MType =
1002       OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
1003   OutStreamer->EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
1004   OutStreamer->EmitLabel(Stub);
1005 
1006   // Only handle non-pic for now.
1007   assert(!isPositionIndependent() &&
1008          "should not be here if we are compiling pic");
1009   TS.emitDirectiveSetReorder();
1010   //
1011   // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
1012   // stubs without raw text but this current patch is for compiler generated
1013   // functions and they all return some value.
1014   // The calling sequence for non pic is different in that case and we need
1015   // to implement %lo and %hi in order to handle the case of no return value
1016   // See the corresponding method in Mips16HardFloat for details.
1017   //
1018   // mov the return address to S2.
1019   // we have no stack space to store it and we are about to make another call.
1020   // We need to make sure that the enclosing function knows to save S2
1021   // This should have already been handled.
1022   //
1023   // Mov $18, $31
1024 
1025   EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO);
1026 
1027   EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true);
1028 
1029   // Jal xxxx
1030   //
1031   EmitJal(*STI, MSymbol);
1032 
1033   // fix return values
1034   EmitSwapFPIntRetval(*STI, Signature->RetSig, LE);
1035   //
1036   // do the return
1037   // if (Signature->RetSig == NoFPRet)
1038   //  llvm_unreachable("should not be any stubs here with no return value");
1039   // else
1040   EmitInstrReg(*STI, Mips::JR, Mips::S2);
1041 
1042   MCSymbol *Tmp = OutContext.createTempSymbol();
1043   OutStreamer->EmitLabel(Tmp);
1044   const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext);
1045   const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext);
1046   const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext);
1047   OutStreamer->emitELFSize(Stub, T_min_E);
1048   TS.emitDirectiveEnd(x);
1049   OutStreamer->PopSection();
1050 }
1051 
1052 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
1053   // Emit needed stubs
1054   //
1055   for (std::map<
1056            const char *,
1057            const Mips16HardFloatInfo::FuncSignature *>::const_iterator
1058            it = StubsNeeded.begin();
1059        it != StubsNeeded.end(); ++it) {
1060     const char *Symbol = it->first;
1061     const Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1062     EmitFPCallStub(Symbol, Signature);
1063   }
1064   // return to the text section
1065   OutStreamer->SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
1066 }
1067 
1068 void MipsAsmPrinter::EmitSled(const MachineInstr &MI, SledKind Kind) {
1069   const uint8_t NoopsInSledCount = Subtarget->isGP64bit() ? 15 : 11;
1070   // For mips32 we want to emit the following pattern:
1071   //
1072   // .Lxray_sled_N:
1073   //   ALIGN
1074   //   B .tmpN
1075   //   11 NOP instructions (44 bytes)
1076   //   ADDIU T9, T9, 52
1077   // .tmpN
1078   //
1079   // We need the 44 bytes (11 instructions) because at runtime, we'd
1080   // be patching over the full 48 bytes (12 instructions) with the following
1081   // pattern:
1082   //
1083   //   ADDIU	SP, SP, -8
1084   //   NOP
1085   //   SW	RA, 4(SP)
1086   //   SW       T9, 0(SP)
1087   //   LUI      T9, %hi(__xray_FunctionEntry/Exit)
1088   //   ORI      T9, T9, %lo(__xray_FunctionEntry/Exit)
1089   //   LUI      T0, %hi(function_id)
1090   //   JALR	T9
1091   //   ORI	T0, T0, %lo(function_id)
1092   //   LW	T9, 0(SP)
1093   //   LW       RA, 4(SP)
1094   //   ADDIU    SP, SP, 8
1095   //
1096   // We add 52 bytes to t9 because we want to adjust the function pointer to
1097   // the actual start of function i.e. the address just after the noop sled.
1098   // We do this because gp displacement relocation is emitted at the start of
1099   // of the function i.e after the nop sled and to correctly calculate the
1100   // global offset table address, t9 must hold the address of the instruction
1101   // containing the gp displacement relocation.
1102   // FIXME: Is this correct for the static relocation model?
1103   //
1104   // For mips64 we want to emit the following pattern:
1105   //
1106   // .Lxray_sled_N:
1107   //   ALIGN
1108   //   B .tmpN
1109   //   15 NOP instructions (60 bytes)
1110   // .tmpN
1111   //
1112   // We need the 60 bytes (15 instructions) because at runtime, we'd
1113   // be patching over the full 64 bytes (16 instructions) with the following
1114   // pattern:
1115   //
1116   //   DADDIU   SP, SP, -16
1117   //   NOP
1118   //   SD       RA, 8(SP)
1119   //   SD       T9, 0(SP)
1120   //   LUI      T9, %highest(__xray_FunctionEntry/Exit)
1121   //   ORI      T9, T9, %higher(__xray_FunctionEntry/Exit)
1122   //   DSLL     T9, T9, 16
1123   //   ORI      T9, T9, %hi(__xray_FunctionEntry/Exit)
1124   //   DSLL     T9, T9, 16
1125   //   ORI      T9, T9, %lo(__xray_FunctionEntry/Exit)
1126   //   LUI      T0, %hi(function_id)
1127   //   JALR     T9
1128   //   ADDIU    T0, T0, %lo(function_id)
1129   //   LD       T9, 0(SP)
1130   //   LD       RA, 8(SP)
1131   //   DADDIU   SP, SP, 16
1132   //
1133   OutStreamer->EmitCodeAlignment(4);
1134   auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1135   OutStreamer->EmitLabel(CurSled);
1136   auto Target = OutContext.createTempSymbol();
1137 
1138   // Emit "B .tmpN" instruction, which jumps over the nop sled to the actual
1139   // start of function
1140   const MCExpr *TargetExpr = MCSymbolRefExpr::create(
1141       Target, MCSymbolRefExpr::VariantKind::VK_None, OutContext);
1142   EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::BEQ)
1143                                    .addReg(Mips::ZERO)
1144                                    .addReg(Mips::ZERO)
1145                                    .addExpr(TargetExpr));
1146 
1147   for (int8_t I = 0; I < NoopsInSledCount; I++)
1148     EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::SLL)
1149                                      .addReg(Mips::ZERO)
1150                                      .addReg(Mips::ZERO)
1151                                      .addImm(0));
1152 
1153   OutStreamer->EmitLabel(Target);
1154 
1155   if (!Subtarget->isGP64bit()) {
1156     EmitToStreamer(*OutStreamer,
1157                    MCInstBuilder(Mips::ADDiu)
1158                        .addReg(Mips::T9)
1159                        .addReg(Mips::T9)
1160                        .addImm(0x34));
1161   }
1162 
1163   recordSled(CurSled, MI, Kind);
1164 }
1165 
1166 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI) {
1167   EmitSled(MI, SledKind::FUNCTION_ENTER);
1168 }
1169 
1170 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI) {
1171   EmitSled(MI, SledKind::FUNCTION_EXIT);
1172 }
1173 
1174 void MipsAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI) {
1175   EmitSled(MI, SledKind::TAIL_CALL);
1176 }
1177 
1178 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1179                                            raw_ostream &OS) {
1180   // TODO: implement
1181 }
1182 
1183 // Emit .dtprelword or .dtpreldword directive
1184 // and value for debug thread local expression.
1185 void MipsAsmPrinter::EmitDebugThreadLocal(const MCExpr *Value,
1186                                           unsigned Size) const {
1187   switch (Size) {
1188   case 4:
1189     OutStreamer->EmitDTPRel32Value(Value);
1190     break;
1191   case 8:
1192     OutStreamer->EmitDTPRel64Value(Value);
1193     break;
1194   default:
1195     llvm_unreachable("Unexpected size of expression value.");
1196   }
1197 }
1198 
1199 // Align all targets of indirect branches on bundle size.  Used only if target
1200 // is NaCl.
1201 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
1202   // Align all blocks that are jumped to through jump table.
1203   if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
1204     const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
1205     for (unsigned I = 0; I < JT.size(); ++I) {
1206       const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
1207 
1208       for (unsigned J = 0; J < MBBs.size(); ++J)
1209         MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1210     }
1211   }
1212 
1213   // If basic block address is taken, block can be target of indirect branch.
1214   for (auto &MBB : MF) {
1215     if (MBB.hasAddressTaken())
1216       MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1217   }
1218 }
1219 
1220 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1221   return (Opcode == Mips::LONG_BRANCH_LUi
1222           || Opcode == Mips::LONG_BRANCH_ADDiu
1223           || Opcode == Mips::LONG_BRANCH_DADDiu);
1224 }
1225 
1226 // Force static initialization.
1227 extern "C" void LLVMInitializeMipsAsmPrinter() {
1228   RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget());
1229   RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget());
1230   RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target());
1231   RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget());
1232 }
1233