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