Home | History | Annotate | Download | only in Mips
      1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
      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 #define DEBUG_TYPE "mips-asm-printer"
     16 #include "MipsAsmPrinter.h"
     17 #include "Mips.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"
     44 
     45 using namespace llvm;
     46 
     47 static bool isUnalignedLoadStore(unsigned Opc) {
     48   return Opc == Mips::ULW    || Opc == Mips::ULH    || Opc == Mips::ULHu ||
     49          Opc == Mips::USW    || Opc == Mips::USH    ||
     50          Opc == Mips::ULW_P8 || Opc == Mips::ULH_P8 || Opc == Mips::ULHu_P8 ||
     51          Opc == Mips::USW_P8 || Opc == Mips::USH_P8;
     52 }
     53 
     54 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
     55   SmallString<128> Str;
     56   raw_svector_ostream OS(Str);
     57 
     58   if (MI->isDebugValue()) {
     59     PrintDebugValueComment(MI, OS);
     60     return;
     61   }
     62 
     63   MipsMCInstLower MCInstLowering(Mang, *MF, *this);
     64   unsigned Opc = MI->getOpcode();
     65   MCInst TmpInst0;
     66   MCInstLowering.Lower(MI, TmpInst0);
     67 
     68   // Enclose unaligned load or store with .macro & .nomacro directives.
     69   if (isUnalignedLoadStore(Opc)) {
     70     MCInst Directive;
     71     Directive.setOpcode(Mips::MACRO);
     72     OutStreamer.EmitInstruction(Directive);
     73     OutStreamer.EmitInstruction(TmpInst0);
     74     Directive.setOpcode(Mips::NOMACRO);
     75     OutStreamer.EmitInstruction(Directive);
     76     return;
     77   }
     78 
     79   OutStreamer.EmitInstruction(TmpInst0);
     80 }
     81 
     82 //===----------------------------------------------------------------------===//
     83 //
     84 //  Mips Asm Directives
     85 //
     86 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
     87 //  Describe the stack frame.
     88 //
     89 //  -- Mask directives "(f)mask  bitmask, offset"
     90 //  Tells the assembler which registers are saved and where.
     91 //  bitmask - contain a little endian bitset indicating which registers are
     92 //            saved on function prologue (e.g. with a 0x80000000 mask, the
     93 //            assembler knows the register 31 (RA) is saved at prologue.
     94 //  offset  - the position before stack pointer subtraction indicating where
     95 //            the first saved register on prologue is located. (e.g. with a
     96 //
     97 //  Consider the following function prologue:
     98 //
     99 //    .frame  $fp,48,$ra
    100 //    .mask   0xc0000000,-8
    101 //       addiu $sp, $sp, -48
    102 //       sw $ra, 40($sp)
    103 //       sw $fp, 36($sp)
    104 //
    105 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
    106 //    30 (FP) are saved at prologue. As the save order on prologue is from
    107 //    left to right, RA is saved first. A -8 offset means that after the
    108 //    stack pointer subtration, the first register in the mask (RA) will be
    109 //    saved at address 48-8=40.
    110 //
    111 //===----------------------------------------------------------------------===//
    112 
    113 //===----------------------------------------------------------------------===//
    114 // Mask directives
    115 //===----------------------------------------------------------------------===//
    116 
    117 // Create a bitmask with all callee saved registers for CPU or Floating Point
    118 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
    119 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
    120   // CPU and FPU Saved Registers Bitmasks
    121   unsigned CPUBitmask = 0, FPUBitmask = 0;
    122   int CPUTopSavedRegOff, FPUTopSavedRegOff;
    123 
    124   // Set the CPU and FPU Bitmasks
    125   const MachineFrameInfo *MFI = MF->getFrameInfo();
    126   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
    127   // size of stack area to which FP callee-saved regs are saved.
    128   unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
    129   unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
    130   unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
    131   bool HasAFGR64Reg = false;
    132   unsigned CSFPRegsSize = 0;
    133   unsigned i, e = CSI.size();
    134 
    135   // Set FPU Bitmask.
    136   for (i = 0; i != e; ++i) {
    137     unsigned Reg = CSI[i].getReg();
    138     if (Mips::CPURegsRegisterClass->contains(Reg))
    139       break;
    140 
    141     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
    142     if (Mips::AFGR64RegisterClass->contains(Reg)) {
    143       FPUBitmask |= (3 << RegNum);
    144       CSFPRegsSize += AFGR64RegSize;
    145       HasAFGR64Reg = true;
    146       continue;
    147     }
    148 
    149     FPUBitmask |= (1 << RegNum);
    150     CSFPRegsSize += FGR32RegSize;
    151   }
    152 
    153   // Set CPU Bitmask.
    154   for (; i != e; ++i) {
    155     unsigned Reg = CSI[i].getReg();
    156     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
    157     CPUBitmask |= (1 << RegNum);
    158   }
    159 
    160   // FP Regs are saved right below where the virtual frame pointer points to.
    161   FPUTopSavedRegOff = FPUBitmask ?
    162     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
    163 
    164   // CPU Regs are saved below FP Regs.
    165   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
    166 
    167   // Print CPUBitmask
    168   O << "\t.mask \t"; printHex32(CPUBitmask, O);
    169   O << ',' << CPUTopSavedRegOff << '\n';
    170 
    171   // Print FPUBitmask
    172   O << "\t.fmask\t"; printHex32(FPUBitmask, O);
    173   O << "," << FPUTopSavedRegOff << '\n';
    174 }
    175 
    176 // Print a 32 bit hex number with all numbers.
    177 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
    178   O << "0x";
    179   for (int i = 7; i >= 0; i--)
    180     O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
    181 }
    182 
    183 //===----------------------------------------------------------------------===//
    184 // Frame and Set directives
    185 //===----------------------------------------------------------------------===//
    186 
    187 /// Frame Directive
    188 void MipsAsmPrinter::emitFrameDirective() {
    189   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
    190 
    191   unsigned stackReg  = RI.getFrameRegister(*MF);
    192   unsigned returnReg = RI.getRARegister();
    193   unsigned stackSize = MF->getFrameInfo()->getStackSize();
    194 
    195   OutStreamer.EmitRawText("\t.frame\t$" +
    196            Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg))) +
    197            "," + Twine(stackSize) + ",$" +
    198            Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnReg))));
    199 }
    200 
    201 /// Emit Set directives.
    202 const char *MipsAsmPrinter::getCurrentABIString() const {
    203   switch (Subtarget->getTargetABI()) {
    204   case MipsSubtarget::O32:  return "abi32";
    205   case MipsSubtarget::N32:  return "abiN32";
    206   case MipsSubtarget::N64:  return "abi64";
    207   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
    208   default: break;
    209   }
    210 
    211   llvm_unreachable("Unknown Mips ABI");
    212   return NULL;
    213 }
    214 
    215 void MipsAsmPrinter::EmitFunctionEntryLabel() {
    216   OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
    217   OutStreamer.EmitLabel(CurrentFnSym);
    218 }
    219 
    220 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
    221 /// the first basic block in the function.
    222 void MipsAsmPrinter::EmitFunctionBodyStart() {
    223   emitFrameDirective();
    224 
    225   SmallString<128> Str;
    226   raw_svector_ostream OS(Str);
    227   printSavedRegsBitmask(OS);
    228   OutStreamer.EmitRawText(OS.str());
    229 }
    230 
    231 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
    232 /// the last basic block in the function.
    233 void MipsAsmPrinter::EmitFunctionBodyEnd() {
    234   // There are instruction for this macros, but they must
    235   // always be at the function end, and we can't emit and
    236   // break with BB logic.
    237   OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
    238   OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
    239   OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
    240 }
    241 
    242 
    243 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
    244 /// exactly one predecessor and the control transfer mechanism between
    245 /// the predecessor and this block is a fall-through.
    246 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
    247                                                        MBB) const {
    248   // The predecessor has to be immediately before this block.
    249   const MachineBasicBlock *Pred = *MBB->pred_begin();
    250 
    251   // If the predecessor is a switch statement, assume a jump table
    252   // implementation, so it is not a fall through.
    253   if (const BasicBlock *bb = Pred->getBasicBlock())
    254     if (isa<SwitchInst>(bb->getTerminator()))
    255       return false;
    256 
    257   // If this is a landing pad, it isn't a fall through.  If it has no preds,
    258   // then nothing falls through to it.
    259   if (MBB->isLandingPad() || MBB->pred_empty())
    260     return false;
    261 
    262   // If there isn't exactly one predecessor, it can't be a fall through.
    263   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
    264   ++PI2;
    265 
    266   if (PI2 != MBB->pred_end())
    267     return false;
    268 
    269   // The predecessor has to be immediately before this block.
    270   if (!Pred->isLayoutSuccessor(MBB))
    271     return false;
    272 
    273   // If the block is completely empty, then it definitely does fall through.
    274   if (Pred->empty())
    275     return true;
    276 
    277   // Otherwise, check the last instruction.
    278   // Check if the last terminator is an unconditional branch.
    279   MachineBasicBlock::const_iterator I = Pred->end();
    280   while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
    281 
    282   return !I->getDesc().isBarrier();
    283 }
    284 
    285 // Print out an operand for an inline asm expression.
    286 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
    287                                      unsigned AsmVariant,const char *ExtraCode,
    288                                      raw_ostream &O) {
    289   // Does this asm operand have a single letter operand modifier?
    290   if (ExtraCode && ExtraCode[0])
    291     return true; // Unknown modifier.
    292 
    293   printOperand(MI, OpNo, O);
    294   return false;
    295 }
    296 
    297 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
    298                                            unsigned OpNum, unsigned AsmVariant,
    299                                            const char *ExtraCode,
    300                                            raw_ostream &O) {
    301   if (ExtraCode && ExtraCode[0])
    302      return true; // Unknown modifier.
    303 
    304   const MachineOperand &MO = MI->getOperand(OpNum);
    305   assert(MO.isReg() && "unexpected inline asm memory operand");
    306   O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
    307   return false;
    308 }
    309 
    310 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
    311                                   raw_ostream &O) {
    312   const MachineOperand &MO = MI->getOperand(opNum);
    313   bool closeP = false;
    314 
    315   if (MO.getTargetFlags())
    316     closeP = true;
    317 
    318   switch(MO.getTargetFlags()) {
    319   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
    320   case MipsII::MO_GOT_CALL: O << "%call16("; break;
    321   case MipsII::MO_GOT:      O << "%got(";    break;
    322   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
    323   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
    324   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
    325   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
    326   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
    327   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
    328   case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
    329   case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
    330   case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
    331   case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
    332   case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
    333   }
    334 
    335   switch (MO.getType()) {
    336     case MachineOperand::MO_Register:
    337       O << '$'
    338         << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
    339       break;
    340 
    341     case MachineOperand::MO_Immediate:
    342       O << MO.getImm();
    343       break;
    344 
    345     case MachineOperand::MO_MachineBasicBlock:
    346       O << *MO.getMBB()->getSymbol();
    347       return;
    348 
    349     case MachineOperand::MO_GlobalAddress:
    350       O << *Mang->getSymbol(MO.getGlobal());
    351       break;
    352 
    353     case MachineOperand::MO_BlockAddress: {
    354       MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
    355       O << BA->getName();
    356       break;
    357     }
    358 
    359     case MachineOperand::MO_ExternalSymbol:
    360       O << *GetExternalSymbolSymbol(MO.getSymbolName());
    361       break;
    362 
    363     case MachineOperand::MO_JumpTableIndex:
    364       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
    365         << '_' << MO.getIndex();
    366       break;
    367 
    368     case MachineOperand::MO_ConstantPoolIndex:
    369       O << MAI->getPrivateGlobalPrefix() << "CPI"
    370         << getFunctionNumber() << "_" << MO.getIndex();
    371       if (MO.getOffset())
    372         O << "+" << MO.getOffset();
    373       break;
    374 
    375     default:
    376       llvm_unreachable("<unknown operand type>");
    377   }
    378 
    379   if (closeP) O << ")";
    380 }
    381 
    382 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
    383                                       raw_ostream &O) {
    384   const MachineOperand &MO = MI->getOperand(opNum);
    385   if (MO.isImm())
    386     O << (unsigned short int)MO.getImm();
    387   else
    388     printOperand(MI, opNum, O);
    389 }
    390 
    391 void MipsAsmPrinter::
    392 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
    393   // Load/Store memory operands -- imm($reg)
    394   // If PIC target the target is loaded as the
    395   // pattern lw $25,%call16($28)
    396   printOperand(MI, opNum+1, O);
    397   O << "(";
    398   printOperand(MI, opNum, O);
    399   O << ")";
    400 }
    401 
    402 void MipsAsmPrinter::
    403 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
    404   // when using stack locations for not load/store instructions
    405   // print the same way as all normal 3 operand instructions.
    406   printOperand(MI, opNum, O);
    407   O << ", ";
    408   printOperand(MI, opNum+1, O);
    409   return;
    410 }
    411 
    412 void MipsAsmPrinter::
    413 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
    414                 const char *Modifier) {
    415   const MachineOperand& MO = MI->getOperand(opNum);
    416   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
    417 }
    418 
    419 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
    420   // FIXME: Use SwitchSection.
    421 
    422   // Tell the assembler which ABI we are using
    423   OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
    424 
    425   // TODO: handle O64 ABI
    426   if (Subtarget->isABI_EABI()) {
    427     if (Subtarget->isGP32bit())
    428       OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
    429     else
    430       OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
    431   }
    432 
    433   // return to previous section
    434   OutStreamer.EmitRawText(StringRef("\t.previous"));
    435 }
    436 
    437 MachineLocation
    438 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
    439   // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
    440   assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
    441   assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
    442          "Unexpected MachineOperand types");
    443   return MachineLocation(MI->getOperand(0).getReg(),
    444                          MI->getOperand(1).getImm());
    445 }
    446 
    447 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
    448                                            raw_ostream &OS) {
    449   // TODO: implement
    450 }
    451 
    452 // Force static initialization.
    453 extern "C" void LLVMInitializeMipsAsmPrinter() {
    454   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
    455   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
    456   RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
    457   RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);
    458 }
    459