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