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