LLVM API Documentation

MipsAsmPrinter.cpp

Go to the documentation of this file.
00001 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains a printer that converts from our internal representation
00011 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "mips-asm-printer"
00016 
00017 #include "Mips.h"
00018 #include "MipsSubtarget.h"
00019 #include "MipsInstrInfo.h"
00020 #include "MipsTargetMachine.h"
00021 #include "MipsMachineFunction.h"
00022 #include "llvm/Constants.h"
00023 #include "llvm/DerivedTypes.h"
00024 #include "llvm/Module.h"
00025 #include "llvm/CodeGen/AsmPrinter.h"
00026 #include "llvm/CodeGen/DwarfWriter.h"
00027 #include "llvm/CodeGen/MachineFunctionPass.h"
00028 #include "llvm/CodeGen/MachineConstantPool.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineInstr.h"
00031 #include "llvm/MC/MCStreamer.h"
00032 #include "llvm/Target/TargetAsmInfo.h"
00033 #include "llvm/Target/TargetData.h"
00034 #include "llvm/Target/TargetLoweringObjectFile.h" 
00035 #include "llvm/Target/TargetMachine.h"
00036 #include "llvm/Target/TargetOptions.h"
00037 #include "llvm/Target/TargetRegistry.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/Mangler.h"
00040 #include "llvm/ADT/Statistic.h"
00041 #include "llvm/ADT/StringExtras.h"
00042 #include "llvm/Support/Debug.h"
00043 #include "llvm/Support/CommandLine.h"
00044 #include "llvm/Support/FormattedStream.h"
00045 #include "llvm/Support/MathExtras.h"
00046 #include <cctype>
00047 
00048 using namespace llvm;
00049 
00050 STATISTIC(EmittedInsts, "Number of machine instrs printed");
00051 
00052 namespace {
00053   class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
00054     const MipsSubtarget *Subtarget;
00055   public:
00056     explicit MipsAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM, 
00057                             const TargetAsmInfo *T, bool V)
00058       : AsmPrinter(O, TM, T, V) {
00059       Subtarget = &TM.getSubtarget<MipsSubtarget>();
00060     }
00061 
00062     virtual const char *getPassName() const {
00063       return "Mips Assembly Printer";
00064     }
00065 
00066     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
00067                          unsigned AsmVariant, const char *ExtraCode);
00068     void printOperand(const MachineInstr *MI, int opNum);
00069     void printUnsignedImm(const MachineInstr *MI, int opNum);
00070     void printMemOperand(const MachineInstr *MI, int opNum, 
00071                          const char *Modifier = 0);
00072     void printFCCOperand(const MachineInstr *MI, int opNum, 
00073                          const char *Modifier = 0);
00074     void PrintGlobalVariable(const GlobalVariable *GVar);
00075     void printSavedRegsBitmask(MachineFunction &MF);
00076     void printHex32(unsigned int Value);
00077 
00078     const char *emitCurrentABIString();
00079     void emitFunctionStart(MachineFunction &MF);
00080     void emitFunctionEnd(MachineFunction &MF);
00081     void emitFrameDirective(MachineFunction &MF);
00082 
00083     void printInstruction(const MachineInstr *MI);  // autogenerated.
00084     bool runOnMachineFunction(MachineFunction &F);
00085     bool doInitialization(Module &M);
00086   };
00087 } // end of anonymous namespace
00088 
00089 #include "MipsGenAsmWriter.inc"
00090 
00091 //===----------------------------------------------------------------------===//
00092 //
00093 //  Mips Asm Directives
00094 //
00095 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
00096 //  Describe the stack frame.
00097 //
00098 //  -- Mask directives "(f)mask  bitmask, offset" 
00099 //  Tells the assembler which registers are saved and where.
00100 //  bitmask - contain a little endian bitset indicating which registers are 
00101 //            saved on function prologue (e.g. with a 0x80000000 mask, the 
00102 //            assembler knows the register 31 (RA) is saved at prologue.
00103 //  offset  - the position before stack pointer subtraction indicating where 
00104 //            the first saved register on prologue is located. (e.g. with a
00105 //
00106 //  Consider the following function prologue:
00107 //
00108 //    .frame  $fp,48,$ra
00109 //    .mask   0xc0000000,-8
00110 //       addiu $sp, $sp, -48
00111 //       sw $ra, 40($sp)
00112 //       sw $fp, 36($sp)
00113 //
00114 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and 
00115 //    30 (FP) are saved at prologue. As the save order on prologue is from 
00116 //    left to right, RA is saved first. A -8 offset means that after the 
00117 //    stack pointer subtration, the first register in the mask (RA) will be
00118 //    saved at address 48-8=40.
00119 //
00120 //===----------------------------------------------------------------------===//
00121 
00122 //===----------------------------------------------------------------------===//
00123 // Mask directives
00124 //===----------------------------------------------------------------------===//
00125 
00126 // Create a bitmask with all callee saved registers for CPU or Floating Point 
00127 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
00128 void MipsAsmPrinter::
00129 printSavedRegsBitmask(MachineFunction &MF)
00130 {
00131   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
00132   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
00133              
00134   // CPU and FPU Saved Registers Bitmasks
00135   unsigned int CPUBitmask = 0;
00136   unsigned int FPUBitmask = 0;
00137 
00138   // Set the CPU and FPU Bitmasks
00139   MachineFrameInfo *MFI = MF.getFrameInfo();
00140   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00141   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
00142     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
00143     if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
00144       CPUBitmask |= (1 << RegNum);
00145     else
00146       FPUBitmask |= (1 << RegNum);
00147   }
00148 
00149   // Return Address and Frame registers must also be set in CPUBitmask.
00150   if (RI.hasFP(MF)) 
00151     CPUBitmask |= (1 << MipsRegisterInfo::
00152                 getRegisterNumbering(RI.getFrameRegister(MF)));
00153   
00154   if (MF.getFrameInfo()->hasCalls()) 
00155     CPUBitmask |= (1 << MipsRegisterInfo::
00156                 getRegisterNumbering(RI.getRARegister()));
00157 
00158   // Print CPUBitmask
00159   O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
00160     << MipsFI->getCPUTopSavedRegOff() << '\n';
00161 
00162   // Print FPUBitmask
00163   O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
00164     << MipsFI->getFPUTopSavedRegOff() << '\n';
00165 }
00166 
00167 // Print a 32 bit hex number with all numbers.
00168 void MipsAsmPrinter::
00169 printHex32(unsigned int Value) 
00170 {
00171   O << "0x";
00172   for (int i = 7; i >= 0; i--) 
00173     O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
00174 }
00175 
00176 //===----------------------------------------------------------------------===//
00177 // Frame and Set directives
00178 //===----------------------------------------------------------------------===//
00179 
00180 /// Frame Directive
00181 void MipsAsmPrinter::emitFrameDirective(MachineFunction &MF) {
00182   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
00183 
00184   unsigned stackReg  = RI.getFrameRegister(MF);
00185   unsigned returnReg = RI.getRARegister();
00186   unsigned stackSize = MF.getFrameInfo()->getStackSize();
00187 
00188 
00189   O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
00190                     << ',' << stackSize << ','
00191                     << '$' << LowercaseString(RI.get(returnReg).AsmName)
00192                     << '\n';
00193 }
00194 
00195 /// Emit Set directives.
00196 const char *MipsAsmPrinter::emitCurrentABIString() {  
00197   switch(Subtarget->getTargetABI()) {
00198     case MipsSubtarget::O32:  return "abi32";  
00199     case MipsSubtarget::O64:  return "abiO64";
00200     case MipsSubtarget::N32:  return "abiN32";
00201     case MipsSubtarget::N64:  return "abi64";
00202     case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
00203     default: break;
00204   }
00205 
00206   llvm_unreachable("Unknown Mips ABI");
00207   return NULL;
00208 }  
00209 
00210 /// Emit the directives used by GAS on the start of functions
00211 void MipsAsmPrinter::emitFunctionStart(MachineFunction &MF) {
00212   // Print out the label for the function.
00213   const Function *F = MF.getFunction();
00214   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
00215 
00216   // 2 bits aligned
00217   EmitAlignment(MF.getAlignment(), F);
00218 
00219   O << "\t.globl\t"  << CurrentFnName << '\n';
00220   O << "\t.ent\t"    << CurrentFnName << '\n';
00221 
00222   printVisibility(CurrentFnName, F->getVisibility());
00223 
00224   if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
00225     O << "\t.type\t"   << CurrentFnName << ", @function\n";
00226 
00227   O << CurrentFnName << ":\n";
00228 
00229   emitFrameDirective(MF);
00230   printSavedRegsBitmask(MF);
00231 
00232   O << '\n';
00233 }
00234 
00235 /// Emit the directives used by GAS on the end of functions
00236 void MipsAsmPrinter::emitFunctionEnd(MachineFunction &MF) {
00237   // There are instruction for this macros, but they must
00238   // always be at the function end, and we can't emit and
00239   // break with BB logic. 
00240   O << "\t.set\tmacro\n"; 
00241   O << "\t.set\treorder\n"; 
00242 
00243   O << "\t.end\t" << CurrentFnName << '\n';
00244   if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
00245     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
00246 }
00247 
00248 /// runOnMachineFunction - This uses the printMachineInstruction()
00249 /// method to print assembly for each instruction.
00250 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
00251   this->MF = &MF;
00252 
00253   SetupMachineFunction(MF);
00254 
00255   // Print out constants referenced by the function
00256   EmitConstantPool(MF.getConstantPool());
00257 
00258   // Print out jump tables referenced by the function
00259   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
00260 
00261   O << "\n\n";
00262 
00263   // Emit the function start directives
00264   emitFunctionStart(MF);
00265 
00266   // Print out code for the function.
00267   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
00268        I != E; ++I) {
00269 
00270     // Print a label for the basic block.
00271     if (I != MF.begin()) {
00272       printBasicBlockLabel(I, true, true);
00273       O << '\n';
00274     }
00275 
00276     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
00277          II != E; ++II) {
00278       // Print the assembly for the instruction.
00279       printInstruction(II);
00280       ++EmittedInsts;
00281     }
00282 
00283     // Each Basic Block is separated by a newline
00284     O << '\n';
00285   }
00286 
00287   // Emit function end directives
00288   emitFunctionEnd(MF);
00289 
00290   // We didn't modify anything.
00291   return false;
00292 }
00293 
00294 // Print out an operand for an inline asm expression.
00295 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
00296                                      unsigned AsmVariant,const char *ExtraCode){
00297   // Does this asm operand have a single letter operand modifier?
00298   if (ExtraCode && ExtraCode[0]) 
00299     return true; // Unknown modifier.
00300 
00301   printOperand(MI, OpNo);
00302   return false;
00303 }
00304 
00305 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
00306   const MachineOperand &MO = MI->getOperand(opNum);
00307   const TargetRegisterInfo  &RI = *TM.getRegisterInfo();
00308   bool closeP = false;
00309   bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
00310   bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
00311 
00312   // %hi and %lo used on mips gas to load global addresses on
00313   // static code. %got is used to load global addresses when 
00314   // using PIC_. %call16 is used to load direct call targets
00315   // on PIC_ and small code size. %call_lo and %call_hi load 
00316   // direct call targets on PIC_ and large code size.
00317   if (MI->getOpcode() == Mips::LUi && !MO.isReg() && !MO.isImm()) {
00318     if ((isPIC) && (isCodeLarge))
00319       O << "%call_hi(";
00320     else
00321       O << "%hi(";
00322     closeP = true;
00323   } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isReg() && !MO.isImm()) {
00324     const MachineOperand &firstMO = MI->getOperand(opNum-1);
00325     if (firstMO.getReg() == Mips::GP)
00326       O << "%gp_rel(";
00327     else
00328       O << "%lo(";
00329     closeP = true;
00330   } else if ((isPIC) && (MI->getOpcode() == Mips::LW) &&
00331              (!MO.isReg()) && (!MO.isImm())) {
00332     const MachineOperand &firstMO = MI->getOperand(opNum-1);
00333     const MachineOperand &lastMO  = MI->getOperand(opNum+1);
00334     if ((firstMO.isReg()) && (lastMO.isReg())) {
00335       if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP) 
00336           && (!isCodeLarge))
00337         O << "%call16(";
00338       else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
00339         O << "%got(";
00340       else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP) 
00341                && (isCodeLarge))
00342         O << "%call_lo(";
00343       closeP = true;
00344     }
00345   }
00346  
00347   switch (MO.getType()) 
00348   {
00349     case MachineOperand::MO_Register:
00350       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
00351         O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
00352       else
00353         O << '$' << MO.getReg();
00354       break;
00355 
00356     case MachineOperand::MO_Immediate:
00357       O << (short int)MO.getImm();
00358       break;
00359 
00360     case MachineOperand::MO_MachineBasicBlock:
00361       printBasicBlockLabel(MO.getMBB());
00362       return;
00363 
00364     case MachineOperand::MO_GlobalAddress:
00365       O << Mang->getMangledName(MO.getGlobal());
00366       break;
00367 
00368     case MachineOperand::MO_ExternalSymbol:
00369       O << MO.getSymbolName();
00370       break;
00371 
00372     case MachineOperand::MO_JumpTableIndex:
00373       O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
00374       << '_' << MO.getIndex();
00375       break;
00376 
00377     case MachineOperand::MO_ConstantPoolIndex:
00378       O << TAI->getPrivateGlobalPrefix() << "CPI"
00379         << getFunctionNumber() << "_" << MO.getIndex();
00380       break;
00381   
00382     default:
00383       llvm_unreachable("<unknown operand type>");
00384   }
00385 
00386   if (closeP) O << ")";
00387 }
00388 
00389 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum) {
00390   const MachineOperand &MO = MI->getOperand(opNum);
00391   if (MO.getType() == MachineOperand::MO_Immediate)
00392     O << (unsigned short int)MO.getImm();
00393   else 
00394     printOperand(MI, opNum);
00395 }
00396 
00397 void MipsAsmPrinter::
00398 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
00399   // when using stack locations for not load/store instructions
00400   // print the same way as all normal 3 operand instructions.
00401   if (Modifier && !strcmp(Modifier, "stackloc")) {
00402     printOperand(MI, opNum+1);
00403     O << ", ";
00404     printOperand(MI, opNum);
00405     return;
00406   }
00407 
00408   // Load/Store memory operands -- imm($reg) 
00409   // If PIC target the target is loaded as the 
00410   // pattern lw $25,%call16($28)
00411   printOperand(MI, opNum);
00412   O << "(";
00413   printOperand(MI, opNum+1);
00414   O << ")";
00415 }
00416 
00417 void MipsAsmPrinter::
00418 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
00419   const MachineOperand& MO = MI->getOperand(opNum);
00420   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 
00421 }
00422 
00423 bool MipsAsmPrinter::doInitialization(Module &M) {
00424   // FIXME: Use SwitchSection.
00425   
00426   // Tell the assembler which ABI we are using
00427   O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
00428 
00429   // TODO: handle O64 ABI
00430   if (Subtarget->isABI_EABI())
00431     O << "\t.section .gcc_compiled_long" << 
00432       (Subtarget->isGP32bit() ? "32" : "64") << '\n';
00433 
00434   // return to previous section
00435   O << "\t.previous" << '\n'; 
00436 
00437   return AsmPrinter::doInitialization(M);
00438 }
00439 
00440 void MipsAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
00441   const TargetData *TD = TM.getTargetData();
00442 
00443   if (!GVar->hasInitializer())
00444     return;   // External global require no code
00445 
00446   // Check to see if this is a special global used by LLVM, if so, emit it.
00447   if (EmitSpecialLLVMGlobal(GVar))
00448     return;
00449 
00450   O << "\n\n";
00451   std::string name = Mang->getMangledName(GVar);
00452   Constant *C = GVar->getInitializer();
00453   const Type *CTy = C->getType();
00454   unsigned Size = TD->getTypeAllocSize(CTy);
00455   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
00456   bool printSizeAndType = true;
00457 
00458   // A data structure or array is aligned in memory to the largest
00459   // alignment boundary required by any data type inside it (this matches
00460   // the Preferred Type Alignment). For integral types, the alignment is
00461   // the type size.
00462   unsigned Align;
00463   if (CTy->getTypeID() == Type::IntegerTyID ||
00464       CTy->getTypeID() == Type::VoidTyID) {
00465     assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
00466     Align = Log2_32(Size);
00467   } else
00468     Align = TD->getPreferredTypeAlignmentShift(CTy);
00469 
00470   printVisibility(name, GVar->getVisibility());
00471 
00472   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
00473                                                                   TM));
00474 
00475   if (C->isNullValue() && !GVar->hasSection()) {
00476     if (!GVar->isThreadLocal() &&
00477         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
00478       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
00479 
00480       if (GVar->hasLocalLinkage())
00481         O << "\t.local\t" << name << '\n';
00482 
00483       O << TAI->getCOMMDirective() << name << ',' << Size;
00484       if (TAI->getCOMMDirectiveTakesAlignment())
00485         O << ',' << (1 << Align);
00486 
00487       O << '\n';
00488       return;
00489     }
00490   }
00491   switch (GVar->getLinkage()) {
00492    case GlobalValue::LinkOnceAnyLinkage:
00493    case GlobalValue::LinkOnceODRLinkage:
00494    case GlobalValue::CommonLinkage:
00495    case GlobalValue::WeakAnyLinkage:
00496    case GlobalValue::WeakODRLinkage:
00497     // FIXME: Verify correct for weak.
00498     // Nonnull linkonce -> weak
00499     O << "\t.weak " << name << '\n';
00500     break;
00501    case GlobalValue::AppendingLinkage:
00502     // FIXME: appending linkage variables should go into a section of their name
00503     // or something.  For now, just emit them as external.
00504    case GlobalValue::ExternalLinkage:
00505     // If external or appending, declare as a global symbol
00506     O << TAI->getGlobalDirective() << name << '\n';
00507     // Fall Through
00508    case GlobalValue::PrivateLinkage:
00509    case GlobalValue::LinkerPrivateLinkage:
00510    case GlobalValue::InternalLinkage:
00511     if (CVA && CVA->isCString())
00512       printSizeAndType = false;
00513     break;
00514    case GlobalValue::GhostLinkage:
00515     llvm_unreachable("Should not have any unmaterialized functions!");
00516    case GlobalValue::DLLImportLinkage:
00517     llvm_unreachable("DLLImport linkage is not supported by this target!");
00518    case GlobalValue::DLLExportLinkage:
00519     llvm_unreachable("DLLExport linkage is not supported by this target!");
00520    default:
00521     llvm_unreachable("Unknown linkage type!");
00522   }
00523 
00524   EmitAlignment(Align, GVar);
00525 
00526   if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
00527     O << "\t.type " << name << ",@object\n";
00528     O << "\t.size " << name << ',' << Size << '\n';
00529   }
00530 
00531   O << name << ":\n";
00532   EmitGlobalConstant(C);
00533 }
00534 
00535 
00536 // Force static initialization.
00537 extern "C" void LLVMInitializeMipsAsmPrinter() { 
00538   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
00539   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
00540 }