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/DwarfWriter.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegistry.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/Mangler.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/MathExtras.h"
51 STATISTIC(EmittedInsts, "Number of machine instrs printed");
54 class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
55 const MipsSubtarget *Subtarget;
57 explicit MipsAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
58 const MCAsmInfo *T, bool V)
59 : AsmPrinter(O, TM, T, V) {
60 Subtarget = &TM.getSubtarget<MipsSubtarget>();
63 virtual const char *getPassName() const {
64 return "Mips Assembly Printer";
67 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
68 unsigned AsmVariant, const char *ExtraCode);
69 void printOperand(const MachineInstr *MI, int opNum);
70 void printUnsignedImm(const MachineInstr *MI, int opNum);
71 void printMemOperand(const MachineInstr *MI, int opNum,
72 const char *Modifier = 0);
73 void printFCCOperand(const MachineInstr *MI, int opNum,
74 const char *Modifier = 0);
75 void PrintGlobalVariable(const GlobalVariable *GVar);
76 void printSavedRegsBitmask(MachineFunction &MF);
77 void printHex32(unsigned int Value);
79 const char *emitCurrentABIString();
80 void emitFunctionStart(MachineFunction &MF);
81 void emitFunctionEnd(MachineFunction &MF);
82 void emitFrameDirective(MachineFunction &MF);
84 void printInstruction(const MachineInstr *MI); // autogenerated.
85 bool runOnMachineFunction(MachineFunction &F);
86 bool doInitialization(Module &M);
88 } // end of anonymous namespace
90 #include "MipsGenAsmWriter.inc"
92 //===----------------------------------------------------------------------===//
94 // Mips Asm Directives
96 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
97 // Describe the stack frame.
99 // -- Mask directives "(f)mask bitmask, offset"
100 // Tells the assembler which registers are saved and where.
101 // bitmask - contain a little endian bitset indicating which registers are
102 // saved on function prologue (e.g. with a 0x80000000 mask, the
103 // assembler knows the register 31 (RA) is saved at prologue.
104 // offset - the position before stack pointer subtraction indicating where
105 // the first saved register on prologue is located. (e.g. with a
107 // Consider the following function prologue:
110 // .mask 0xc0000000,-8
111 // addiu $sp, $sp, -48
115 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
116 // 30 (FP) are saved at prologue. As the save order on prologue is from
117 // left to right, RA is saved first. A -8 offset means that after the
118 // stack pointer subtration, the first register in the mask (RA) will be
119 // saved at address 48-8=40.
121 //===----------------------------------------------------------------------===//
123 //===----------------------------------------------------------------------===//
125 //===----------------------------------------------------------------------===//
127 // Create a bitmask with all callee saved registers for CPU or Floating Point
128 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
129 void MipsAsmPrinter::
130 printSavedRegsBitmask(MachineFunction &MF)
132 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
133 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
135 // CPU and FPU Saved Registers Bitmasks
136 unsigned int CPUBitmask = 0;
137 unsigned int FPUBitmask = 0;
139 // Set the CPU and FPU Bitmasks
140 MachineFrameInfo *MFI = MF.getFrameInfo();
141 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
142 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
143 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
144 if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
145 CPUBitmask |= (1 << RegNum);
147 FPUBitmask |= (1 << RegNum);
150 // Return Address and Frame registers must also be set in CPUBitmask.
152 CPUBitmask |= (1 << MipsRegisterInfo::
153 getRegisterNumbering(RI.getFrameRegister(MF)));
155 if (MF.getFrameInfo()->hasCalls())
156 CPUBitmask |= (1 << MipsRegisterInfo::
157 getRegisterNumbering(RI.getRARegister()));
160 O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
161 << MipsFI->getCPUTopSavedRegOff() << '\n';
164 O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
165 << MipsFI->getFPUTopSavedRegOff() << '\n';
168 // Print a 32 bit hex number with all numbers.
169 void MipsAsmPrinter::
170 printHex32(unsigned int Value)
173 for (int i = 7; i >= 0; i--)
174 O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
177 //===----------------------------------------------------------------------===//
178 // Frame and Set directives
179 //===----------------------------------------------------------------------===//
182 void MipsAsmPrinter::emitFrameDirective(MachineFunction &MF) {
183 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
185 unsigned stackReg = RI.getFrameRegister(MF);
186 unsigned returnReg = RI.getRARegister();
187 unsigned stackSize = MF.getFrameInfo()->getStackSize();
190 O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
191 << ',' << stackSize << ','
192 << '$' << LowercaseString(RI.get(returnReg).AsmName)
196 /// Emit Set directives.
197 const char *MipsAsmPrinter::emitCurrentABIString() {
198 switch(Subtarget->getTargetABI()) {
199 case MipsSubtarget::O32: return "abi32";
200 case MipsSubtarget::O64: return "abiO64";
201 case MipsSubtarget::N32: return "abiN32";
202 case MipsSubtarget::N64: return "abi64";
203 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
207 llvm_unreachable("Unknown Mips ABI");
211 /// Emit the directives used by GAS on the start of functions
212 void MipsAsmPrinter::emitFunctionStart(MachineFunction &MF) {
213 // Print out the label for the function.
214 const Function *F = MF.getFunction();
215 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
218 EmitAlignment(MF.getAlignment(), F);
220 O << "\t.globl\t" << CurrentFnName << '\n';
221 O << "\t.ent\t" << CurrentFnName << '\n';
223 printVisibility(CurrentFnName, F->getVisibility());
225 if ((MAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
226 O << "\t.type\t" << CurrentFnName << ", @function\n";
228 O << CurrentFnName << ":\n";
230 emitFrameDirective(MF);
231 printSavedRegsBitmask(MF);
236 /// Emit the directives used by GAS on the end of functions
237 void MipsAsmPrinter::emitFunctionEnd(MachineFunction &MF) {
238 // There are instruction for this macros, but they must
239 // always be at the function end, and we can't emit and
240 // break with BB logic.
241 O << "\t.set\tmacro\n";
242 O << "\t.set\treorder\n";
244 O << "\t.end\t" << CurrentFnName << '\n';
245 if (MAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
246 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
249 /// runOnMachineFunction - This uses the printMachineInstruction()
250 /// method to print assembly for each instruction.
251 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
254 SetupMachineFunction(MF);
256 // Print out constants referenced by the function
257 EmitConstantPool(MF.getConstantPool());
259 // Print out jump tables referenced by the function
260 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
264 // Emit the function start directives
265 emitFunctionStart(MF);
267 // Print out code for the function.
268 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
271 // Print a label for the basic block.
272 if (I != MF.begin()) {
273 printBasicBlockLabel(I, true, true);
277 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
279 processDebugLoc(II->getDebugLoc());
281 // Print the assembly for the instruction.
282 printInstruction(II);
284 if (VerboseAsm && !II->getDebugLoc().isUnknown())
291 // Each Basic Block is separated by a newline
295 // Emit function end directives
298 // We didn't modify anything.
302 // Print out an operand for an inline asm expression.
303 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
304 unsigned AsmVariant,const char *ExtraCode){
305 // Does this asm operand have a single letter operand modifier?
306 if (ExtraCode && ExtraCode[0])
307 return true; // Unknown modifier.
309 printOperand(MI, OpNo);
313 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
314 const MachineOperand &MO = MI->getOperand(opNum);
315 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
318 if (MO.getTargetFlags())
321 switch(MO.getTargetFlags()) {
322 case MipsII::MO_GPREL: O << "%gp_rel("; break;
323 case MipsII::MO_GOT_CALL: O << "%call16("; break;
325 if (MI->getOpcode() == Mips::LW)
330 case MipsII::MO_ABS_HILO:
331 if (MI->getOpcode() == Mips::LUi)
338 switch (MO.getType())
340 case MachineOperand::MO_Register:
341 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
342 O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
344 O << '$' << MO.getReg();
347 case MachineOperand::MO_Immediate:
348 O << (short int)MO.getImm();
351 case MachineOperand::MO_MachineBasicBlock:
352 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
355 case MachineOperand::MO_GlobalAddress:
356 O << Mang->getMangledName(MO.getGlobal());
359 case MachineOperand::MO_ExternalSymbol:
360 O << MO.getSymbolName();
363 case MachineOperand::MO_JumpTableIndex:
364 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
365 << '_' << MO.getIndex();
368 case MachineOperand::MO_ConstantPoolIndex:
369 O << MAI->getPrivateGlobalPrefix() << "CPI"
370 << getFunctionNumber() << "_" << MO.getIndex();
374 llvm_unreachable("<unknown operand type>");
377 if (closeP) O << ")";
380 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum) {
381 const MachineOperand &MO = MI->getOperand(opNum);
382 if (MO.getType() == MachineOperand::MO_Immediate)
383 O << (unsigned short int)MO.getImm();
385 printOperand(MI, opNum);
388 void MipsAsmPrinter::
389 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
390 // when using stack locations for not load/store instructions
391 // print the same way as all normal 3 operand instructions.
392 if (Modifier && !strcmp(Modifier, "stackloc")) {
393 printOperand(MI, opNum+1);
395 printOperand(MI, opNum);
399 // Load/Store memory operands -- imm($reg)
400 // If PIC target the target is loaded as the
401 // pattern lw $25,%call16($28)
402 printOperand(MI, opNum);
404 printOperand(MI, opNum+1);
408 void MipsAsmPrinter::
409 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
410 const MachineOperand& MO = MI->getOperand(opNum);
411 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
414 bool MipsAsmPrinter::doInitialization(Module &M) {
415 // FIXME: Use SwitchSection.
417 // Tell the assembler which ABI we are using
418 O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
420 // TODO: handle O64 ABI
421 if (Subtarget->isABI_EABI())
422 O << "\t.section .gcc_compiled_long" <<
423 (Subtarget->isGP32bit() ? "32" : "64") << '\n';
425 // return to previous section
426 O << "\t.previous" << '\n';
428 return AsmPrinter::doInitialization(M);
431 void MipsAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
432 const TargetData *TD = TM.getTargetData();
434 if (!GVar->hasInitializer())
435 return; // External global require no code
437 // Check to see if this is a special global used by LLVM, if so, emit it.
438 if (EmitSpecialLLVMGlobal(GVar))
442 std::string name = Mang->getMangledName(GVar);
443 Constant *C = GVar->getInitializer();
444 const Type *CTy = C->getType();
445 unsigned Size = TD->getTypeAllocSize(CTy);
446 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
447 bool printSizeAndType = true;
449 // A data structure or array is aligned in memory to the largest
450 // alignment boundary required by any data type inside it (this matches
451 // the Preferred Type Alignment). For integral types, the alignment is
454 if (CTy->getTypeID() == Type::IntegerTyID ||
455 CTy->getTypeID() == Type::VoidTyID) {
456 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
457 Align = Log2_32(Size);
459 Align = TD->getPreferredTypeAlignmentShift(CTy);
461 printVisibility(name, GVar->getVisibility());
463 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
466 if (C->isNullValue() && !GVar->hasSection()) {
467 if (!GVar->isThreadLocal() &&
468 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
469 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
471 if (GVar->hasLocalLinkage())
472 O << "\t.local\t" << name << '\n';
474 O << MAI->getCOMMDirective() << name << ',' << Size;
475 if (MAI->getCOMMDirectiveTakesAlignment())
476 O << ',' << (1 << Align);
482 switch (GVar->getLinkage()) {
483 case GlobalValue::LinkOnceAnyLinkage:
484 case GlobalValue::LinkOnceODRLinkage:
485 case GlobalValue::CommonLinkage:
486 case GlobalValue::WeakAnyLinkage:
487 case GlobalValue::WeakODRLinkage:
488 // FIXME: Verify correct for weak.
489 // Nonnull linkonce -> weak
490 O << "\t.weak " << name << '\n';
492 case GlobalValue::AppendingLinkage:
493 // FIXME: appending linkage variables should go into a section of their name
494 // or something. For now, just emit them as external.
495 case GlobalValue::ExternalLinkage:
496 // If external or appending, declare as a global symbol
497 O << MAI->getGlobalDirective() << name << '\n';
499 case GlobalValue::PrivateLinkage:
500 case GlobalValue::LinkerPrivateLinkage:
501 case GlobalValue::InternalLinkage:
502 if (CVA && CVA->isCString())
503 printSizeAndType = false;
505 case GlobalValue::GhostLinkage:
506 llvm_unreachable("Should not have any unmaterialized functions!");
507 case GlobalValue::DLLImportLinkage:
508 llvm_unreachable("DLLImport linkage is not supported by this target!");
509 case GlobalValue::DLLExportLinkage:
510 llvm_unreachable("DLLExport linkage is not supported by this target!");
512 llvm_unreachable("Unknown linkage type!");
515 EmitAlignment(Align, GVar);
517 if (MAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
518 O << "\t.type " << name << ",@object\n";
519 O << "\t.size " << name << ',' << Size << '\n';
523 EmitGlobalConstant(C);
527 // Force static initialization.
528 extern "C" void LLVMInitializeMipsAsmPrinter() {
529 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
530 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);