1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-asm-printer"
16 #include "MipsAsmPrinter.h"
18 #include "MipsInstrInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsMCInstLower.h"
21 #include "MipsMCSymbolRefExpr.h"
22 #include "InstPrinter/MipsInstPrinter.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Target/Mangler.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Analysis/DebugInfo.h"
48 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
50 raw_svector_ostream OS(Str);
52 if (MI->isDebugValue()) {
53 PrintDebugValueComment(MI, OS);
57 MipsMCInstLower MCInstLowering(Mang, *MF, *this);
58 unsigned Opc = MI->getOpcode();
60 // If target is Mips1, expand double precision load/store to two single
61 // precision loads/stores (and delay slot if MI is a load).
62 if (Subtarget->isMips1() && (Opc == Mips::LDC1 || Opc == Mips::SDC1)) {
63 SmallVector<MCInst, 4> MCInsts;
64 const unsigned* SubReg =
65 TM.getRegisterInfo()->getSubRegisters(MI->getOperand(0).getReg());
66 MCInstLowering.LowerMips1F64LoadStore(MI, Opc, MCInsts,
67 Subtarget->isLittle(), SubReg);
69 for (SmallVector<MCInst, 4>::iterator I = MCInsts.begin();
70 I != MCInsts.end(); ++I)
71 OutStreamer.EmitInstruction(*I);
77 MCInstLowering.Lower(MI, TmpInst0);
79 // Convert aligned loads/stores to their unaligned counterparts.
80 if (!MI->memoperands_empty()) {
81 unsigned NaturalAlignment, UnalignedOpc;
84 case Mips::LW: NaturalAlignment = 4; UnalignedOpc = Mips::ULW; break;
85 case Mips::SW: NaturalAlignment = 4; UnalignedOpc = Mips::USW; break;
86 case Mips::LH: NaturalAlignment = 2; UnalignedOpc = Mips::ULH; break;
87 case Mips::LHu: NaturalAlignment = 2; UnalignedOpc = Mips::ULHu; break;
88 case Mips::SH: NaturalAlignment = 2; UnalignedOpc = Mips::USH; break;
89 default: NaturalAlignment = 0;
92 if ((*MI->memoperands_begin())->getAlignment() < NaturalAlignment) {
94 Directive.setOpcode(Mips::MACRO);
95 OutStreamer.EmitInstruction(Directive);
96 TmpInst0.setOpcode(UnalignedOpc);
97 OutStreamer.EmitInstruction(TmpInst0);
98 Directive.setOpcode(Mips::NOMACRO);
99 OutStreamer.EmitInstruction(Directive);
104 OutStreamer.EmitInstruction(TmpInst0);
107 //===----------------------------------------------------------------------===//
109 // Mips Asm Directives
111 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
112 // Describe the stack frame.
114 // -- Mask directives "(f)mask bitmask, offset"
115 // Tells the assembler which registers are saved and where.
116 // bitmask - contain a little endian bitset indicating which registers are
117 // saved on function prologue (e.g. with a 0x80000000 mask, the
118 // assembler knows the register 31 (RA) is saved at prologue.
119 // offset - the position before stack pointer subtraction indicating where
120 // the first saved register on prologue is located. (e.g. with a
122 // Consider the following function prologue:
125 // .mask 0xc0000000,-8
126 // addiu $sp, $sp, -48
130 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
131 // 30 (FP) are saved at prologue. As the save order on prologue is from
132 // left to right, RA is saved first. A -8 offset means that after the
133 // stack pointer subtration, the first register in the mask (RA) will be
134 // saved at address 48-8=40.
136 //===----------------------------------------------------------------------===//
138 //===----------------------------------------------------------------------===//
140 //===----------------------------------------------------------------------===//
142 // Create a bitmask with all callee saved registers for CPU or Floating Point
143 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
144 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
145 // CPU and FPU Saved Registers Bitmasks
146 unsigned CPUBitmask = 0, FPUBitmask = 0;
147 int CPUTopSavedRegOff, FPUTopSavedRegOff;
149 // Set the CPU and FPU Bitmasks
150 const MachineFrameInfo *MFI = MF->getFrameInfo();
151 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
152 // size of stack area to which FP callee-saved regs are saved.
153 unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
154 unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
155 unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
156 bool HasAFGR64Reg = false;
157 unsigned CSFPRegsSize = 0;
158 unsigned i, e = CSI.size();
161 for (i = 0; i != e; ++i) {
162 unsigned Reg = CSI[i].getReg();
163 if (Mips::CPURegsRegisterClass->contains(Reg))
166 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
167 if (Mips::AFGR64RegisterClass->contains(Reg)) {
168 FPUBitmask |= (3 << RegNum);
169 CSFPRegsSize += AFGR64RegSize;
174 FPUBitmask |= (1 << RegNum);
175 CSFPRegsSize += FGR32RegSize;
179 for (; i != e; ++i) {
180 unsigned Reg = CSI[i].getReg();
181 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
182 CPUBitmask |= (1 << RegNum);
185 // FP Regs are saved right below where the virtual frame pointer points to.
186 FPUTopSavedRegOff = FPUBitmask ?
187 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
189 // CPU Regs are saved below FP Regs.
190 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
193 O << "\t.mask \t"; printHex32(CPUBitmask, O);
194 O << ',' << CPUTopSavedRegOff << '\n';
197 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
198 O << "," << FPUTopSavedRegOff << '\n';
201 // Print a 32 bit hex number with all numbers.
202 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
204 for (int i = 7; i >= 0; i--)
205 O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
208 //===----------------------------------------------------------------------===//
209 // Frame and Set directives
210 //===----------------------------------------------------------------------===//
213 void MipsAsmPrinter::emitFrameDirective() {
214 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
216 unsigned stackReg = RI.getFrameRegister(*MF);
217 unsigned returnReg = RI.getRARegister();
218 unsigned stackSize = MF->getFrameInfo()->getStackSize();
220 OutStreamer.EmitRawText("\t.frame\t$" +
221 Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg))) +
222 "," + Twine(stackSize) + ",$" +
223 Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnReg))));
226 /// Emit Set directives.
227 const char *MipsAsmPrinter::getCurrentABIString() const {
228 switch (Subtarget->getTargetABI()) {
229 case MipsSubtarget::O32: return "abi32";
230 case MipsSubtarget::O64: return "abiO64";
231 case MipsSubtarget::N32: return "abiN32";
232 case MipsSubtarget::N64: return "abi64";
233 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
237 llvm_unreachable("Unknown Mips ABI");
241 void MipsAsmPrinter::EmitFunctionEntryLabel() {
242 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
243 OutStreamer.EmitLabel(CurrentFnSym);
246 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
247 /// the first basic block in the function.
248 void MipsAsmPrinter::EmitFunctionBodyStart() {
249 emitFrameDirective();
251 SmallString<128> Str;
252 raw_svector_ostream OS(Str);
253 printSavedRegsBitmask(OS);
254 OutStreamer.EmitRawText(OS.str());
257 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
258 /// the last basic block in the function.
259 void MipsAsmPrinter::EmitFunctionBodyEnd() {
260 // There are instruction for this macros, but they must
261 // always be at the function end, and we can't emit and
262 // break with BB logic.
263 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
264 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
265 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
269 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
270 /// exactly one predecessor and the control transfer mechanism between
271 /// the predecessor and this block is a fall-through.
272 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
274 // The predecessor has to be immediately before this block.
275 const MachineBasicBlock *Pred = *MBB->pred_begin();
277 // If the predecessor is a switch statement, assume a jump table
278 // implementation, so it is not a fall through.
279 if (const BasicBlock *bb = Pred->getBasicBlock())
280 if (isa<SwitchInst>(bb->getTerminator()))
283 // If this is a landing pad, it isn't a fall through. If it has no preds,
284 // then nothing falls through to it.
285 if (MBB->isLandingPad() || MBB->pred_empty())
288 // If there isn't exactly one predecessor, it can't be a fall through.
289 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
292 if (PI2 != MBB->pred_end())
295 // The predecessor has to be immediately before this block.
296 if (!Pred->isLayoutSuccessor(MBB))
299 // If the block is completely empty, then it definitely does fall through.
303 // Otherwise, check the last instruction.
304 // Check if the last terminator is an unconditional branch.
305 MachineBasicBlock::const_iterator I = Pred->end();
306 while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
308 return !I->getDesc().isBarrier();
311 // Print out an operand for an inline asm expression.
312 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
313 unsigned AsmVariant,const char *ExtraCode,
315 // Does this asm operand have a single letter operand modifier?
316 if (ExtraCode && ExtraCode[0])
317 return true; // Unknown modifier.
319 printOperand(MI, OpNo, O);
323 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
324 unsigned OpNum, unsigned AsmVariant,
325 const char *ExtraCode,
327 if (ExtraCode && ExtraCode[0])
328 return true; // Unknown modifier.
330 const MachineOperand &MO = MI->getOperand(OpNum);
331 assert(MO.isReg() && "unexpected inline asm memory operand");
332 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
336 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
338 const MachineOperand &MO = MI->getOperand(opNum);
341 if (MO.getTargetFlags())
344 switch(MO.getTargetFlags()) {
345 case MipsII::MO_GPREL: O << "%gp_rel("; break;
346 case MipsII::MO_GOT_CALL: O << "%call16("; break;
347 case MipsII::MO_GOT: O << "%got("; break;
348 case MipsII::MO_ABS_HI: O << "%hi("; break;
349 case MipsII::MO_ABS_LO: O << "%lo("; break;
350 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
351 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
352 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
353 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
356 switch (MO.getType()) {
357 case MachineOperand::MO_Register:
359 << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
362 case MachineOperand::MO_Immediate:
366 case MachineOperand::MO_MachineBasicBlock:
367 O << *MO.getMBB()->getSymbol();
370 case MachineOperand::MO_GlobalAddress:
371 O << *Mang->getSymbol(MO.getGlobal());
374 case MachineOperand::MO_BlockAddress: {
375 MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
380 case MachineOperand::MO_ExternalSymbol:
381 O << *GetExternalSymbolSymbol(MO.getSymbolName());
384 case MachineOperand::MO_JumpTableIndex:
385 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
386 << '_' << MO.getIndex();
389 case MachineOperand::MO_ConstantPoolIndex:
390 O << MAI->getPrivateGlobalPrefix() << "CPI"
391 << getFunctionNumber() << "_" << MO.getIndex();
393 O << "+" << MO.getOffset();
397 llvm_unreachable("<unknown operand type>");
400 if (closeP) O << ")";
403 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
405 const MachineOperand &MO = MI->getOperand(opNum);
407 O << (unsigned short int)MO.getImm();
409 printOperand(MI, opNum, O);
412 void MipsAsmPrinter::
413 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
414 // Load/Store memory operands -- imm($reg)
415 // If PIC target the target is loaded as the
416 // pattern lw $25,%call16($28)
417 printOperand(MI, opNum+1, O);
419 printOperand(MI, opNum, O);
423 void MipsAsmPrinter::
424 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
425 // when using stack locations for not load/store instructions
426 // print the same way as all normal 3 operand instructions.
427 printOperand(MI, opNum, O);
429 printOperand(MI, opNum+1, O);
433 void MipsAsmPrinter::
434 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
435 const char *Modifier) {
436 const MachineOperand& MO = MI->getOperand(opNum);
437 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
440 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
441 // FIXME: Use SwitchSection.
443 // Tell the assembler which ABI we are using
444 OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
446 // TODO: handle O64 ABI
447 if (Subtarget->isABI_EABI()) {
448 if (Subtarget->isGP32bit())
449 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
451 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
454 // return to previous section
455 OutStreamer.EmitRawText(StringRef("\t.previous"));
459 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
460 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
461 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
462 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
463 "Unexpected MachineOperand types");
464 return MachineLocation(MI->getOperand(0).getReg(),
465 MI->getOperand(1).getImm());
468 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
473 // Force static initialization.
474 extern "C" void LLVMInitializeMipsAsmPrinter() {
475 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
476 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);