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/StringExtras.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Analysis/DebugInfo.h"
47 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
49 raw_svector_ostream OS(Str);
51 if (MI->isDebugValue()) {
52 PrintDebugValueComment(MI, OS);
56 MipsMCInstLower MCInstLowering(Mang, *MF, *this);
57 unsigned Opc = MI->getOpcode();
59 MCInstLowering.Lower(MI, TmpInst0);
61 // Convert aligned loads/stores to their unaligned counterparts.
62 if (!MI->memoperands_empty()) {
63 unsigned NaturalAlignment, UnalignedOpc;
66 case Mips::LW: NaturalAlignment = 4; UnalignedOpc = Mips::ULW; break;
67 case Mips::SW: NaturalAlignment = 4; UnalignedOpc = Mips::USW; break;
68 case Mips::LH: NaturalAlignment = 2; UnalignedOpc = Mips::ULH; break;
69 case Mips::LHu: NaturalAlignment = 2; UnalignedOpc = Mips::ULHu; break;
70 case Mips::SH: NaturalAlignment = 2; UnalignedOpc = Mips::USH; break;
71 default: NaturalAlignment = 0;
74 if ((*MI->memoperands_begin())->getAlignment() < NaturalAlignment) {
76 Directive.setOpcode(Mips::MACRO);
77 OutStreamer.EmitInstruction(Directive);
78 TmpInst0.setOpcode(UnalignedOpc);
79 OutStreamer.EmitInstruction(TmpInst0);
80 Directive.setOpcode(Mips::NOMACRO);
81 OutStreamer.EmitInstruction(Directive);
86 OutStreamer.EmitInstruction(TmpInst0);
89 //===----------------------------------------------------------------------===//
91 // Mips Asm Directives
93 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
94 // Describe the stack frame.
96 // -- Mask directives "(f)mask bitmask, offset"
97 // Tells the assembler which registers are saved and where.
98 // bitmask - contain a little endian bitset indicating which registers are
99 // saved on function prologue (e.g. with a 0x80000000 mask, the
100 // assembler knows the register 31 (RA) is saved at prologue.
101 // offset - the position before stack pointer subtraction indicating where
102 // the first saved register on prologue is located. (e.g. with a
104 // Consider the following function prologue:
107 // .mask 0xc0000000,-8
108 // addiu $sp, $sp, -48
112 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
113 // 30 (FP) are saved at prologue. As the save order on prologue is from
114 // left to right, RA is saved first. A -8 offset means that after the
115 // stack pointer subtration, the first register in the mask (RA) will be
116 // saved at address 48-8=40.
118 //===----------------------------------------------------------------------===//
120 //===----------------------------------------------------------------------===//
122 //===----------------------------------------------------------------------===//
124 // Create a bitmask with all callee saved registers for CPU or Floating Point
125 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
126 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
127 // CPU and FPU Saved Registers Bitmasks
128 unsigned CPUBitmask = 0, FPUBitmask = 0;
129 int CPUTopSavedRegOff, FPUTopSavedRegOff;
131 // Set the CPU and FPU Bitmasks
132 const MachineFrameInfo *MFI = MF->getFrameInfo();
133 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
134 // size of stack area to which FP callee-saved regs are saved.
135 unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
136 unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
137 unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
138 bool HasAFGR64Reg = false;
139 unsigned CSFPRegsSize = 0;
140 unsigned i, e = CSI.size();
143 for (i = 0; i != e; ++i) {
144 unsigned Reg = CSI[i].getReg();
145 if (Mips::CPURegsRegisterClass->contains(Reg))
148 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
149 if (Mips::AFGR64RegisterClass->contains(Reg)) {
150 FPUBitmask |= (3 << RegNum);
151 CSFPRegsSize += AFGR64RegSize;
156 FPUBitmask |= (1 << RegNum);
157 CSFPRegsSize += FGR32RegSize;
161 for (; i != e; ++i) {
162 unsigned Reg = CSI[i].getReg();
163 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
164 CPUBitmask |= (1 << RegNum);
167 // FP Regs are saved right below where the virtual frame pointer points to.
168 FPUTopSavedRegOff = FPUBitmask ?
169 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
171 // CPU Regs are saved below FP Regs.
172 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
175 O << "\t.mask \t"; printHex32(CPUBitmask, O);
176 O << ',' << CPUTopSavedRegOff << '\n';
179 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
180 O << "," << FPUTopSavedRegOff << '\n';
183 // Print a 32 bit hex number with all numbers.
184 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
186 for (int i = 7; i >= 0; i--)
187 O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
190 //===----------------------------------------------------------------------===//
191 // Frame and Set directives
192 //===----------------------------------------------------------------------===//
195 void MipsAsmPrinter::emitFrameDirective() {
196 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
198 unsigned stackReg = RI.getFrameRegister(*MF);
199 unsigned returnReg = RI.getRARegister();
200 unsigned stackSize = MF->getFrameInfo()->getStackSize();
202 OutStreamer.EmitRawText("\t.frame\t$" +
203 Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg))) +
204 "," + Twine(stackSize) + ",$" +
205 Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnReg))));
208 /// Emit Set directives.
209 const char *MipsAsmPrinter::getCurrentABIString() const {
210 switch (Subtarget->getTargetABI()) {
211 case MipsSubtarget::O32: return "abi32";
212 case MipsSubtarget::N32: return "abiN32";
213 case MipsSubtarget::N64: return "abi64";
214 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
218 llvm_unreachable("Unknown Mips ABI");
222 void MipsAsmPrinter::EmitFunctionEntryLabel() {
223 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
224 OutStreamer.EmitLabel(CurrentFnSym);
227 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
228 /// the first basic block in the function.
229 void MipsAsmPrinter::EmitFunctionBodyStart() {
230 emitFrameDirective();
232 SmallString<128> Str;
233 raw_svector_ostream OS(Str);
234 printSavedRegsBitmask(OS);
235 OutStreamer.EmitRawText(OS.str());
238 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
239 /// the last basic block in the function.
240 void MipsAsmPrinter::EmitFunctionBodyEnd() {
241 // There are instruction for this macros, but they must
242 // always be at the function end, and we can't emit and
243 // break with BB logic.
244 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
245 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
246 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
250 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
251 /// exactly one predecessor and the control transfer mechanism between
252 /// the predecessor and this block is a fall-through.
253 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
255 // The predecessor has to be immediately before this block.
256 const MachineBasicBlock *Pred = *MBB->pred_begin();
258 // If the predecessor is a switch statement, assume a jump table
259 // implementation, so it is not a fall through.
260 if (const BasicBlock *bb = Pred->getBasicBlock())
261 if (isa<SwitchInst>(bb->getTerminator()))
264 // If this is a landing pad, it isn't a fall through. If it has no preds,
265 // then nothing falls through to it.
266 if (MBB->isLandingPad() || MBB->pred_empty())
269 // If there isn't exactly one predecessor, it can't be a fall through.
270 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
273 if (PI2 != MBB->pred_end())
276 // The predecessor has to be immediately before this block.
277 if (!Pred->isLayoutSuccessor(MBB))
280 // If the block is completely empty, then it definitely does fall through.
284 // Otherwise, check the last instruction.
285 // Check if the last terminator is an unconditional branch.
286 MachineBasicBlock::const_iterator I = Pred->end();
287 while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
289 return !I->getDesc().isBarrier();
292 // Print out an operand for an inline asm expression.
293 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
294 unsigned AsmVariant,const char *ExtraCode,
296 // Does this asm operand have a single letter operand modifier?
297 if (ExtraCode && ExtraCode[0])
298 return true; // Unknown modifier.
300 printOperand(MI, OpNo, O);
304 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
305 unsigned OpNum, unsigned AsmVariant,
306 const char *ExtraCode,
308 if (ExtraCode && ExtraCode[0])
309 return true; // Unknown modifier.
311 const MachineOperand &MO = MI->getOperand(OpNum);
312 assert(MO.isReg() && "unexpected inline asm memory operand");
313 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
317 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
319 const MachineOperand &MO = MI->getOperand(opNum);
322 if (MO.getTargetFlags())
325 switch(MO.getTargetFlags()) {
326 case MipsII::MO_GPREL: O << "%gp_rel("; break;
327 case MipsII::MO_GOT_CALL: O << "%call16("; break;
328 case MipsII::MO_GOT: O << "%got("; break;
329 case MipsII::MO_ABS_HI: O << "%hi("; break;
330 case MipsII::MO_ABS_LO: O << "%lo("; break;
331 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
332 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
333 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
334 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
337 switch (MO.getType()) {
338 case MachineOperand::MO_Register:
340 << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
343 case MachineOperand::MO_Immediate:
347 case MachineOperand::MO_MachineBasicBlock:
348 O << *MO.getMBB()->getSymbol();
351 case MachineOperand::MO_GlobalAddress:
352 O << *Mang->getSymbol(MO.getGlobal());
355 case MachineOperand::MO_BlockAddress: {
356 MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
361 case MachineOperand::MO_ExternalSymbol:
362 O << *GetExternalSymbolSymbol(MO.getSymbolName());
365 case MachineOperand::MO_JumpTableIndex:
366 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
367 << '_' << MO.getIndex();
370 case MachineOperand::MO_ConstantPoolIndex:
371 O << MAI->getPrivateGlobalPrefix() << "CPI"
372 << getFunctionNumber() << "_" << MO.getIndex();
374 O << "+" << MO.getOffset();
378 llvm_unreachable("<unknown operand type>");
381 if (closeP) O << ")";
384 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
386 const MachineOperand &MO = MI->getOperand(opNum);
388 O << (unsigned short int)MO.getImm();
390 printOperand(MI, opNum, O);
393 void MipsAsmPrinter::
394 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
395 // Load/Store memory operands -- imm($reg)
396 // If PIC target the target is loaded as the
397 // pattern lw $25,%call16($28)
398 printOperand(MI, opNum+1, O);
400 printOperand(MI, opNum, O);
404 void MipsAsmPrinter::
405 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
406 // when using stack locations for not load/store instructions
407 // print the same way as all normal 3 operand instructions.
408 printOperand(MI, opNum, O);
410 printOperand(MI, opNum+1, O);
414 void MipsAsmPrinter::
415 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
416 const char *Modifier) {
417 const MachineOperand& MO = MI->getOperand(opNum);
418 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
421 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
422 // FIXME: Use SwitchSection.
424 // Tell the assembler which ABI we are using
425 OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
427 // TODO: handle O64 ABI
428 if (Subtarget->isABI_EABI()) {
429 if (Subtarget->isGP32bit())
430 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
432 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
435 // return to previous section
436 OutStreamer.EmitRawText(StringRef("\t.previous"));
440 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
441 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
442 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
443 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
444 "Unexpected MachineOperand types");
445 return MachineLocation(MI->getOperand(0).getReg(),
446 MI->getOperand(1).getImm());
449 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
454 // Force static initialization.
455 extern "C" void LLVMInitializeMipsAsmPrinter() {
456 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
457 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);