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"
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
47 struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
49 const MipsSubtarget *Subtarget;
51 MipsAsmPrinter(std::ostream &O, MipsTargetMachine &TM,
52 const TargetAsmInfo *T):
53 AsmPrinter(O, TM, T) {
54 Subtarget = &TM.getSubtarget<MipsSubtarget>();
57 virtual const char *getPassName() const {
58 return "Mips Assembly Printer";
61 virtual std::string getSectionForFunction(const Function &F) const;
62 void printOperand(const MachineInstr *MI, int opNum);
63 void printMemOperand(const MachineInstr *MI, int opNum,
64 const char *Modifier = 0);
65 void printFCCOperand(const MachineInstr *MI, int opNum,
66 const char *Modifier = 0);
67 void printModuleLevelGV(const GlobalVariable* GVar);
68 unsigned int getSavedRegsBitmask(bool isFloat, MachineFunction &MF);
69 void printHex32(unsigned int Value);
71 const char *emitCurrentABIString(void);
72 void emitFunctionStart(MachineFunction &MF);
73 void emitFunctionEnd(MachineFunction &MF);
74 void emitFrameDirective(MachineFunction &MF);
75 void emitMaskDirective(MachineFunction &MF);
76 void emitFMaskDirective(MachineFunction &MF);
78 bool printInstruction(const MachineInstr *MI); // autogenerated.
79 bool runOnMachineFunction(MachineFunction &F);
80 bool doInitialization(Module &M);
81 bool doFinalization(Module &M);
83 } // end of anonymous namespace
85 #include "MipsGenAsmWriter.inc"
87 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
88 /// assembly code for a MachineFunction to the given output stream,
89 /// using the given target machine description. This should work
90 /// regardless of whether the function is in SSA form.
91 FunctionPass *llvm::createMipsCodePrinterPass(std::ostream &o,
92 MipsTargetMachine &tm)
94 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
97 //===----------------------------------------------------------------------===//
99 // Mips Asm Directives
101 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
102 // Describe the stack frame.
104 // -- Mask directives "(f)mask bitmask, offset"
105 // Tells the assembler which registers are saved and where.
106 // bitmask - contain a little endian bitset indicating which registers are
107 // saved on function prologue (e.g. with a 0x80000000 mask, the
108 // assembler knows the register 31 (RA) is saved at prologue.
109 // offset - the position before stack pointer subtraction indicating where
110 // the first saved register on prologue is located. (e.g. with a
112 // Consider the following function prologue:
115 // .mask 0xc0000000,-8
116 // addiu $sp, $sp, -48
120 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
121 // 30 (FP) are saved at prologue. As the save order on prologue is from
122 // left to right, RA is saved first. A -8 offset means that after the
123 // stack pointer subtration, the first register in the mask (RA) will be
124 // saved at address 48-8=40.
126 //===----------------------------------------------------------------------===//
128 //===----------------------------------------------------------------------===//
130 //===----------------------------------------------------------------------===//
132 /// Mask directive for GPR
133 void MipsAsmPrinter::
134 emitMaskDirective(MachineFunction &MF)
136 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
138 int StackSize = MF.getFrameInfo()->getStackSize();
139 int Offset = (!MipsFI->getTopSavedRegOffset()) ? 0 :
140 (-(StackSize-MipsFI->getTopSavedRegOffset()));
143 DOUT << "--> emitMaskDirective" << "\n";
144 DOUT << "StackSize : " << StackSize << "\n";
145 DOUT << "getTopSavedReg : " << MipsFI->getTopSavedRegOffset() << "\n";
146 DOUT << "Offset : " << Offset << "\n\n";
149 unsigned int Bitmask = getSavedRegsBitmask(false, MF);
152 O << "," << Offset << "\n";
155 /// TODO: Mask Directive for Floating Point
156 void MipsAsmPrinter::
157 emitFMaskDirective(MachineFunction &MF)
159 unsigned int Bitmask = getSavedRegsBitmask(true, MF);
166 // Create a bitmask with all callee saved registers for CPU
167 // or Floating Point registers. For CPU registers consider RA,
168 // GP and FP for saving if necessary.
169 unsigned int MipsAsmPrinter::
170 getSavedRegsBitmask(bool isFloat, MachineFunction &MF)
172 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
174 // Floating Point Registers, TODO
179 unsigned int Bitmask = 0;
181 MachineFrameInfo *MFI = MF.getFrameInfo();
182 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
183 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
184 Bitmask |= (1 << MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg()));
187 Bitmask |= (1 << MipsRegisterInfo::
188 getRegisterNumbering(RI.getFrameRegister(MF)));
190 if (MF.getFrameInfo()->hasCalls())
191 Bitmask |= (1 << MipsRegisterInfo::
192 getRegisterNumbering(RI.getRARegister()));
197 // Print a 32 bit hex number with all numbers.
198 void MipsAsmPrinter::
199 printHex32(unsigned int Value)
201 O << "0x" << std::hex;
202 for (int i = 7; i >= 0; i--)
203 O << std::hex << ( (Value & (0xF << (i*4))) >> (i*4) );
207 //===----------------------------------------------------------------------===//
208 // Frame and Set directives
209 //===----------------------------------------------------------------------===//
212 void MipsAsmPrinter::
213 emitFrameDirective(MachineFunction &MF)
215 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
217 unsigned stackReg = RI.getFrameRegister(MF);
218 unsigned returnReg = RI.getRARegister();
219 unsigned stackSize = MF.getFrameInfo()->getStackSize();
222 O << "\t.frame\t" << "$" << LowercaseString(RI.get(stackReg).AsmName)
223 << "," << stackSize << ","
224 << "$" << LowercaseString(RI.get(returnReg).AsmName)
228 /// Emit Set directives.
229 const char * MipsAsmPrinter::
230 emitCurrentABIString(void)
232 switch(Subtarget->getTargetABI()) {
233 case MipsSubtarget::O32: return "abi32";
234 case MipsSubtarget::O64: return "abiO64";
235 case MipsSubtarget::N32: return "abiN32";
236 case MipsSubtarget::N64: return "abi64";
237 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
241 assert(0 && "Unknown Mips ABI");
245 // Substitute old hook with new one temporary
246 std::string MipsAsmPrinter::getSectionForFunction(const Function &F) const {
247 return TAI->SectionForGlobal(&F);
250 /// Emit the directives used by GAS on the start of functions
251 void MipsAsmPrinter::
252 emitFunctionStart(MachineFunction &MF)
254 // Print out the label for the function.
255 const Function *F = MF.getFunction();
256 SwitchToTextSection(TAI->SectionForGlobal(F).c_str());
261 O << "\t.globl\t" << CurrentFnName << "\n";
262 O << "\t.ent\t" << CurrentFnName << "\n";
264 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
265 O << "\t.type\t" << CurrentFnName << ", @function\n";
267 O << CurrentFnName << ":\n";
269 emitFrameDirective(MF);
270 emitMaskDirective(MF);
271 emitFMaskDirective(MF);
276 /// Emit the directives used by GAS on the end of functions
277 void MipsAsmPrinter::
278 emitFunctionEnd(MachineFunction &MF)
280 // There are instruction for this macros, but they must
281 // always be at the function end, and we can't emit and
282 // break with BB logic.
283 O << "\t.set\tmacro\n";
284 O << "\t.set\treorder\n";
286 O << "\t.end\t" << CurrentFnName << "\n";
287 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
288 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << "\n";
291 /// runOnMachineFunction - This uses the printMachineInstruction()
292 /// method to print assembly for each instruction.
293 bool MipsAsmPrinter::
294 runOnMachineFunction(MachineFunction &MF)
296 SetupMachineFunction(MF);
298 // Print out constants referenced by the function
299 EmitConstantPool(MF.getConstantPool());
301 // Print out jump tables referenced by the function
302 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
306 // What's my mangled name?
307 CurrentFnName = Mang->getValueName(MF.getFunction());
309 // Emit the function start directives
310 emitFunctionStart(MF);
312 // Print out code for the function.
313 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
316 // Print a label for the basic block.
317 if (I != MF.begin()) {
318 printBasicBlockLabel(I, true, true);
322 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
324 // Print the assembly for the instruction.
325 printInstruction(II);
329 // Each Basic Block is separated by a newline
333 // Emit function end directives
336 // We didn't modify anything.
340 void MipsAsmPrinter::
341 printOperand(const MachineInstr *MI, int opNum)
343 const MachineOperand &MO = MI->getOperand(opNum);
344 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
346 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
347 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
349 // %hi and %lo used on mips gas to load global addresses on
350 // static code. %got is used to load global addresses when
351 // using PIC_. %call16 is used to load direct call targets
352 // on PIC_ and small code size. %call_lo and %call_hi load
353 // direct call targets on PIC_ and large code size.
354 if (MI->getOpcode() == Mips::LUi && !MO.isRegister()
355 && !MO.isImmediate()) {
356 if ((isPIC) && (isCodeLarge))
361 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isRegister()
362 && !MO.isImmediate()) {
365 } else if ((isPIC) && (MI->getOpcode() == Mips::LW)
366 && (!MO.isRegister()) && (!MO.isImmediate())) {
367 const MachineOperand &firstMO = MI->getOperand(opNum-1);
368 const MachineOperand &lastMO = MI->getOperand(opNum+1);
369 if ((firstMO.isRegister()) && (lastMO.isRegister())) {
370 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
373 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
375 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
382 switch (MO.getType())
384 case MachineOperand::MO_Register:
385 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
386 O << "$" << LowercaseString (RI.get(MO.getReg()).AsmName);
388 O << "$" << MO.getReg();
391 case MachineOperand::MO_Immediate:
392 if ((MI->getOpcode() == Mips::SLTiu) || (MI->getOpcode() == Mips::ORi) ||
393 (MI->getOpcode() == Mips::LUi) || (MI->getOpcode() == Mips::ANDi))
394 O << (unsigned short int)MO.getImm();
396 O << (short int)MO.getImm();
399 case MachineOperand::MO_MachineBasicBlock:
400 printBasicBlockLabel(MO.getMBB());
403 case MachineOperand::MO_GlobalAddress:
404 O << Mang->getValueName(MO.getGlobal());
407 case MachineOperand::MO_ExternalSymbol:
408 O << MO.getSymbolName();
411 case MachineOperand::MO_JumpTableIndex:
412 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
413 << '_' << MO.getIndex();
416 // FIXME: Verify correct
417 case MachineOperand::MO_ConstantPoolIndex:
418 O << TAI->getPrivateGlobalPrefix() << "CPI"
419 << getFunctionNumber() << "_" << MO.getIndex();
423 O << "<unknown operand type>"; abort (); break;
426 if (closeP) O << ")";
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 bool printSizeAndType = true;
495 // A data structure or array is aligned in memory to the largest
496 // alignment boundary required by any data type inside it (this matches
497 // the Preferred Type Alignment). For integral types, the alignment is
499 //unsigned Align = TD->getPreferredAlignmentLog(I);
500 //unsigned Align = TD->getPrefTypeAlignment(C->getType());
502 if (CTy->getTypeID() == Type::IntegerTyID ||
503 CTy->getTypeID() == Type::VoidTyID) {
504 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
505 Align = Log2_32(Size);
507 Align = TD->getPreferredTypeAlignmentShift(CTy);
509 // FIXME: ELF supports visibility
511 SwitchToDataSection(SectionName.c_str());
513 if (C->isNullValue() && !GVar->hasSection()) {
514 if (!GVar->isThreadLocal() &&
515 (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
516 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
518 if (GVar->hasInternalLinkage()) {
519 if (TAI->getLCOMMDirective())
520 O << TAI->getLCOMMDirective() << name << ',' << Size;
522 O << "\t.local\t" << name << '\n';
524 O << TAI->getCOMMDirective() << name << ',' << Size;
525 // The .comm alignment in bytes.
526 if (TAI->getCOMMDirectiveTakesAlignment())
527 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
533 switch (GVar->getLinkage()) {
534 case GlobalValue::LinkOnceLinkage:
535 case GlobalValue::CommonLinkage:
536 case GlobalValue::WeakLinkage:
537 // FIXME: Verify correct for weak.
538 // Nonnull linkonce -> weak
539 O << "\t.weak " << name << "\n";
541 case GlobalValue::AppendingLinkage:
542 // FIXME: appending linkage variables should go into a section of their name
543 // or something. For now, just emit them as external.
544 case GlobalValue::ExternalLinkage:
545 // If external or appending, declare as a global symbol
546 O << TAI->getGlobalDirective() << name << "\n";
548 case GlobalValue::InternalLinkage:
550 case GlobalValue::GhostLinkage:
551 cerr << "Should not have any unmaterialized functions!\n";
553 case GlobalValue::DLLImportLinkage:
554 cerr << "DLLImport linkage is not supported by this target!\n";
556 case GlobalValue::DLLExportLinkage:
557 cerr << "DLLExport linkage is not supported by this target!\n";
560 assert(0 && "Unknown linkage type!");
564 O << "\t.align " << Align << "\n";
566 if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
567 O << "\t.type " << name << ",@object\n";
568 O << "\t.size " << name << "," << Size << "\n";
572 EmitGlobalConstant(C);
575 bool MipsAsmPrinter::
576 doFinalization(Module &M)
578 // Print out module-level global variables here.
579 for (Module::const_global_iterator I = M.global_begin(),
580 E = M.global_end(); I != E; ++I)
581 printModuleLevelGV(I);
585 return AsmPrinter::doFinalization(M);