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"
18 #include "MipsSubtarget.h"
19 #include "MipsInstrInfo.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsMachineFunction.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
45 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48 struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
50 const MipsSubtarget *Subtarget;
52 MipsAsmPrinter(raw_ostream &O, MipsTargetMachine &TM,
53 const TargetAsmInfo *T):
54 AsmPrinter(O, TM, T) {
55 Subtarget = &TM.getSubtarget<MipsSubtarget>();
58 virtual const char *getPassName() const {
59 return "Mips Assembly Printer";
62 virtual std::string getSectionForFunction(const Function &F) const;
63 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
64 unsigned AsmVariant, const char *ExtraCode);
65 void printOperand(const MachineInstr *MI, int opNum);
66 void printUnsignedImm(const MachineInstr *MI, int opNum);
67 void printMemOperand(const MachineInstr *MI, int opNum,
68 const char *Modifier = 0);
69 void printFCCOperand(const MachineInstr *MI, int opNum,
70 const char *Modifier = 0);
71 void printModuleLevelGV(const GlobalVariable* GVar);
72 void printSavedRegsBitmask(MachineFunction &MF);
73 void printHex32(unsigned int Value);
75 const char *emitCurrentABIString(void);
76 void emitFunctionStart(MachineFunction &MF);
77 void emitFunctionEnd(MachineFunction &MF);
78 void emitFrameDirective(MachineFunction &MF);
80 bool printInstruction(const MachineInstr *MI); // autogenerated.
81 bool runOnMachineFunction(MachineFunction &F);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
85 } // end of anonymous namespace
87 #include "MipsGenAsmWriter.inc"
89 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description. This should work
92 /// regardless of whether the function is in SSA form.
93 FunctionPass *llvm::createMipsCodePrinterPass(raw_ostream &o,
94 MipsTargetMachine &tm)
96 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
99 //===----------------------------------------------------------------------===//
101 // Mips Asm Directives
103 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
104 // Describe the stack frame.
106 // -- Mask directives "(f)mask bitmask, offset"
107 // Tells the assembler which registers are saved and where.
108 // bitmask - contain a little endian bitset indicating which registers are
109 // saved on function prologue (e.g. with a 0x80000000 mask, the
110 // assembler knows the register 31 (RA) is saved at prologue.
111 // offset - the position before stack pointer subtraction indicating where
112 // the first saved register on prologue is located. (e.g. with a
114 // Consider the following function prologue:
117 // .mask 0xc0000000,-8
118 // addiu $sp, $sp, -48
122 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
123 // 30 (FP) are saved at prologue. As the save order on prologue is from
124 // left to right, RA is saved first. A -8 offset means that after the
125 // stack pointer subtration, the first register in the mask (RA) will be
126 // saved at address 48-8=40.
128 //===----------------------------------------------------------------------===//
130 //===----------------------------------------------------------------------===//
132 //===----------------------------------------------------------------------===//
134 // Create a bitmask with all callee saved registers for CPU or Floating Point
135 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
136 void MipsAsmPrinter::
137 printSavedRegsBitmask(MachineFunction &MF)
139 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
140 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
142 // CPU and FPU Saved Registers Bitmasks
143 unsigned int CPUBitmask = 0;
144 unsigned int FPUBitmask = 0;
146 // Set the CPU and FPU Bitmasks
147 MachineFrameInfo *MFI = MF.getFrameInfo();
148 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
149 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
150 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
151 if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
152 CPUBitmask |= (1 << RegNum);
154 FPUBitmask |= (1 << RegNum);
157 // Return Address and Frame registers must also be set in CPUBitmask.
159 CPUBitmask |= (1 << MipsRegisterInfo::
160 getRegisterNumbering(RI.getFrameRegister(MF)));
162 if (MF.getFrameInfo()->hasCalls())
163 CPUBitmask |= (1 << MipsRegisterInfo::
164 getRegisterNumbering(RI.getRARegister()));
167 O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
168 << MipsFI->getCPUTopSavedRegOff() << '\n';
171 O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
172 << MipsFI->getFPUTopSavedRegOff() << '\n';
175 // Print a 32 bit hex number with all numbers.
176 void MipsAsmPrinter::
177 printHex32(unsigned int Value)
180 for (int i = 7; i >= 0; i--)
181 O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
184 //===----------------------------------------------------------------------===//
185 // Frame and Set directives
186 //===----------------------------------------------------------------------===//
189 void MipsAsmPrinter::
190 emitFrameDirective(MachineFunction &MF)
192 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
194 unsigned stackReg = RI.getFrameRegister(MF);
195 unsigned returnReg = RI.getRARegister();
196 unsigned stackSize = MF.getFrameInfo()->getStackSize();
199 O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
200 << ',' << stackSize << ','
201 << '$' << LowercaseString(RI.get(returnReg).AsmName)
205 /// Emit Set directives.
206 const char * MipsAsmPrinter::
207 emitCurrentABIString(void)
209 switch(Subtarget->getTargetABI()) {
210 case MipsSubtarget::O32: return "abi32";
211 case MipsSubtarget::O64: return "abiO64";
212 case MipsSubtarget::N32: return "abiN32";
213 case MipsSubtarget::N64: return "abi64";
214 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
218 assert(0 && "Unknown Mips ABI");
222 // Substitute old hook with new one temporary
223 std::string MipsAsmPrinter::getSectionForFunction(const Function &F) const {
224 return TAI->SectionForGlobal(&F);
227 /// Emit the directives used by GAS on the start of functions
228 void MipsAsmPrinter::
229 emitFunctionStart(MachineFunction &MF)
231 // Print out the label for the function.
232 const Function *F = MF.getFunction();
233 SwitchToTextSection(TAI->SectionForGlobal(F).c_str());
238 O << "\t.globl\t" << CurrentFnName << '\n';
239 O << "\t.ent\t" << CurrentFnName << '\n';
241 printVisibility(CurrentFnName, F->getVisibility());
243 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
244 O << "\t.type\t" << CurrentFnName << ", @function\n";
246 O << CurrentFnName << ":\n";
248 emitFrameDirective(MF);
249 printSavedRegsBitmask(MF);
254 /// Emit the directives used by GAS on the end of functions
255 void MipsAsmPrinter::
256 emitFunctionEnd(MachineFunction &MF)
258 // There are instruction for this macros, but they must
259 // always be at the function end, and we can't emit and
260 // break with BB logic.
261 O << "\t.set\tmacro\n";
262 O << "\t.set\treorder\n";
264 O << "\t.end\t" << CurrentFnName << '\n';
265 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
266 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
269 /// runOnMachineFunction - This uses the printMachineInstruction()
270 /// method to print assembly for each instruction.
271 bool MipsAsmPrinter::
272 runOnMachineFunction(MachineFunction &MF)
274 SetupMachineFunction(MF);
276 // Print out constants referenced by the function
277 EmitConstantPool(MF.getConstantPool());
279 // Print out jump tables referenced by the function
280 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
284 // What's my mangled name?
285 CurrentFnName = Mang->getValueName(MF.getFunction());
287 // Emit the function start directives
288 emitFunctionStart(MF);
290 // Print out code for the function.
291 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
294 // Print a label for the basic block.
295 if (I != MF.begin()) {
296 printBasicBlockLabel(I, true, true);
300 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
302 // Print the assembly for the instruction.
303 printInstruction(II);
307 // Each Basic Block is separated by a newline
311 // Emit function end directives
314 // We didn't modify anything.
318 // Print out an operand for an inline asm expression.
319 bool MipsAsmPrinter::
320 PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
321 unsigned AsmVariant, const char *ExtraCode)
323 // Does this asm operand have a single letter operand modifier?
324 if (ExtraCode && ExtraCode[0])
325 return true; // Unknown modifier.
327 printOperand(MI, OpNo);
331 void MipsAsmPrinter::
332 printOperand(const MachineInstr *MI, int opNum)
334 const MachineOperand &MO = MI->getOperand(opNum);
335 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
337 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
338 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
340 // %hi and %lo used on mips gas to load global addresses on
341 // static code. %got is used to load global addresses when
342 // using PIC_. %call16 is used to load direct call targets
343 // on PIC_ and small code size. %call_lo and %call_hi load
344 // direct call targets on PIC_ and large code size.
345 if (MI->getOpcode() == Mips::LUi && !MO.isRegister()
346 && !MO.isImmediate()) {
347 if ((isPIC) && (isCodeLarge))
352 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isRegister()
353 && !MO.isImmediate()) {
354 const MachineOperand &firstMO = MI->getOperand(opNum-1);
355 if (firstMO.getReg() == Mips::GP)
360 } else if ((isPIC) && (MI->getOpcode() == Mips::LW)
361 && (!MO.isRegister()) && (!MO.isImmediate())) {
362 const MachineOperand &firstMO = MI->getOperand(opNum-1);
363 const MachineOperand &lastMO = MI->getOperand(opNum+1);
364 if ((firstMO.isRegister()) && (lastMO.isRegister())) {
365 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
368 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
370 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
377 switch (MO.getType())
379 case MachineOperand::MO_Register:
380 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
381 O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
383 O << '$' << MO.getReg();
386 case MachineOperand::MO_Immediate:
387 O << (short int)MO.getImm();
390 case MachineOperand::MO_MachineBasicBlock:
391 printBasicBlockLabel(MO.getMBB());
394 case MachineOperand::MO_GlobalAddress:
395 O << Mang->getValueName(MO.getGlobal());
398 case MachineOperand::MO_ExternalSymbol:
399 O << MO.getSymbolName();
402 case MachineOperand::MO_JumpTableIndex:
403 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
404 << '_' << MO.getIndex();
407 case MachineOperand::MO_ConstantPoolIndex:
408 O << TAI->getPrivateGlobalPrefix() << "CPI"
409 << getFunctionNumber() << "_" << MO.getIndex();
413 O << "<unknown operand type>"; abort (); break;
416 if (closeP) O << ")";
419 void MipsAsmPrinter::
420 printUnsignedImm(const MachineInstr *MI, int opNum)
422 const MachineOperand &MO = MI->getOperand(opNum);
423 if (MO.getType() == MachineOperand::MO_Immediate)
424 O << (unsigned short int)MO.getImm();
426 printOperand(MI, opNum);
429 void MipsAsmPrinter::
430 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
432 // when using stack locations for not load/store instructions
433 // print the same way as all normal 3 operand instructions.
434 if (Modifier && !strcmp(Modifier, "stackloc")) {
435 printOperand(MI, opNum+1);
437 printOperand(MI, opNum);
441 // Load/Store memory operands -- imm($reg)
442 // If PIC target the target is loaded as the
443 // pattern lw $25,%call16($28)
444 printOperand(MI, opNum);
446 printOperand(MI, opNum+1);
450 void MipsAsmPrinter::
451 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier)
453 const MachineOperand& MO = MI->getOperand(opNum);
454 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
457 bool MipsAsmPrinter::
458 doInitialization(Module &M)
460 Mang = new Mangler(M);
462 // Tell the assembler which ABI we are using
463 O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
465 // TODO: handle O64 ABI
466 if (Subtarget->isABI_EABI())
467 O << "\t.section .gcc_compiled_long" <<
468 (Subtarget->isGP32bit() ? "32" : "64") << '\n';
470 // return to previous section
471 O << "\t.previous" << '\n';
473 return false; // success
476 void MipsAsmPrinter::
477 printModuleLevelGV(const GlobalVariable* GVar) {
478 const TargetData *TD = TM.getTargetData();
480 if (!GVar->hasInitializer())
481 return; // External global require no code
483 // Check to see if this is a special global used by LLVM, if so, emit it.
484 if (EmitSpecialLLVMGlobal(GVar))
488 std::string SectionName = TAI->SectionForGlobal(GVar);
489 std::string name = Mang->getValueName(GVar);
490 Constant *C = GVar->getInitializer();
491 const Type *CTy = C->getType();
492 unsigned Size = TD->getABITypeSize(CTy);
493 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
494 bool printSizeAndType = true;
496 // A data structure or array is aligned in memory to the largest
497 // alignment boundary required by any data type inside it (this matches
498 // the Preferred Type Alignment). For integral types, the alignment is
501 if (CTy->getTypeID() == Type::IntegerTyID ||
502 CTy->getTypeID() == Type::VoidTyID) {
503 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
504 Align = Log2_32(Size);
506 Align = TD->getPreferredTypeAlignmentShift(CTy);
508 printVisibility(name, GVar->getVisibility());
510 SwitchToDataSection(SectionName.c_str());
512 if (C->isNullValue() && !GVar->hasSection()) {
513 if (!GVar->isThreadLocal() &&
514 (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
515 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
517 if (GVar->hasInternalLinkage())
518 O << "\t.local\t" << name << '\n';
520 O << TAI->getCOMMDirective() << name << ',' << Size;
521 if (TAI->getCOMMDirectiveTakesAlignment())
522 O << ',' << (1 << Align);
528 switch (GVar->getLinkage()) {
529 case GlobalValue::LinkOnceLinkage:
530 case GlobalValue::CommonLinkage:
531 case GlobalValue::WeakLinkage:
532 // FIXME: Verify correct for weak.
533 // Nonnull linkonce -> weak
534 O << "\t.weak " << name << '\n';
536 case GlobalValue::AppendingLinkage:
537 // FIXME: appending linkage variables should go into a section of their name
538 // or something. For now, just emit them as external.
539 case GlobalValue::ExternalLinkage:
540 // If external or appending, declare as a global symbol
541 O << TAI->getGlobalDirective() << name << '\n';
543 case GlobalValue::InternalLinkage:
544 if (CVA && CVA->isCString())
545 printSizeAndType = false;
547 case GlobalValue::GhostLinkage:
548 cerr << "Should not have any unmaterialized functions!\n";
550 case GlobalValue::DLLImportLinkage:
551 cerr << "DLLImport linkage is not supported by this target!\n";
553 case GlobalValue::DLLExportLinkage:
554 cerr << "DLLExport linkage is not supported by this target!\n";
557 assert(0 && "Unknown linkage type!");
560 EmitAlignment(Align, GVar);
562 if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
563 O << "\t.type " << name << ",@object\n";
564 O << "\t.size " << name << ',' << Size << '\n';
568 EmitGlobalConstant(C);
571 bool MipsAsmPrinter::
572 doFinalization(Module &M)
574 // Print out module-level global variables here.
575 for (Module::const_global_iterator I = M.global_begin(),
576 E = M.global_end(); I != E; ++I)
577 printModuleLevelGV(I);
581 return AsmPrinter::doFinalization(M);