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