Update comments.
[llvm/msp430.git] / lib / Target / Mips / AsmPrinter / MipsAsmPrinter.cpp
blob532c82df06fb8af19796845bddef6b2d2190dc29
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-asm-printer"
17 #include "Mips.h"
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/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <cctype>
44 using namespace llvm;
46 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48 namespace {
49 class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
50 const MipsSubtarget *Subtarget;
51 public:
52 MipsAsmPrinter(raw_ostream &O, MipsTargetMachine &TM,
53 const TargetAsmInfo *T, bool F, bool V)
54 : AsmPrinter(O, TM, T, F, V) {
55 Subtarget = &TM.getSubtarget<MipsSubtarget>();
58 virtual const char *getPassName() const {
59 return "Mips Assembly Printer";
62 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
63 unsigned AsmVariant, const char *ExtraCode);
64 void printOperand(const MachineInstr *MI, int opNum);
65 void printUnsignedImm(const MachineInstr *MI, int opNum);
66 void printMemOperand(const MachineInstr *MI, int opNum,
67 const char *Modifier = 0);
68 void printFCCOperand(const MachineInstr *MI, int opNum,
69 const char *Modifier = 0);
70 void printModuleLevelGV(const GlobalVariable* GVar);
71 void printSavedRegsBitmask(MachineFunction &MF);
72 void printHex32(unsigned int Value);
74 const char *emitCurrentABIString(void);
75 void emitFunctionStart(MachineFunction &MF);
76 void emitFunctionEnd(MachineFunction &MF);
77 void emitFrameDirective(MachineFunction &MF);
79 bool printInstruction(const MachineInstr *MI); // autogenerated.
80 bool runOnMachineFunction(MachineFunction &F);
81 bool doInitialization(Module &M);
82 bool doFinalization(Module &M);
84 } // end of anonymous namespace
86 #include "MipsGenAsmWriter.inc"
88 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
89 /// assembly code for a MachineFunction to the given output stream,
90 /// using the given target machine description. This should work
91 /// regardless of whether the function is in SSA form.
92 FunctionPass *llvm::createMipsCodePrinterPass(raw_ostream &o,
93 MipsTargetMachine &tm,
94 bool fast, bool verbose) {
95 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo(), fast, verbose);
98 //===----------------------------------------------------------------------===//
100 // Mips Asm Directives
102 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
103 // Describe the stack frame.
105 // -- Mask directives "(f)mask bitmask, offset"
106 // Tells the assembler which registers are saved and where.
107 // bitmask - contain a little endian bitset indicating which registers are
108 // saved on function prologue (e.g. with a 0x80000000 mask, the
109 // assembler knows the register 31 (RA) is saved at prologue.
110 // offset - the position before stack pointer subtraction indicating where
111 // the first saved register on prologue is located. (e.g. with a
113 // Consider the following function prologue:
115 // .frame $fp,48,$ra
116 // .mask 0xc0000000,-8
117 // addiu $sp, $sp, -48
118 // sw $ra, 40($sp)
119 // sw $fp, 36($sp)
121 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
122 // 30 (FP) are saved at prologue. As the save order on prologue is from
123 // left to right, RA is saved first. A -8 offset means that after the
124 // stack pointer subtration, the first register in the mask (RA) will be
125 // saved at address 48-8=40.
127 //===----------------------------------------------------------------------===//
129 //===----------------------------------------------------------------------===//
130 // Mask directives
131 //===----------------------------------------------------------------------===//
133 // Create a bitmask with all callee saved registers for CPU or Floating Point
134 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
135 void MipsAsmPrinter::
136 printSavedRegsBitmask(MachineFunction &MF)
138 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
139 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
141 // CPU and FPU Saved Registers Bitmasks
142 unsigned int CPUBitmask = 0;
143 unsigned int FPUBitmask = 0;
145 // Set the CPU and FPU Bitmasks
146 MachineFrameInfo *MFI = MF.getFrameInfo();
147 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
148 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
149 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
150 if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
151 CPUBitmask |= (1 << RegNum);
152 else
153 FPUBitmask |= (1 << RegNum);
156 // Return Address and Frame registers must also be set in CPUBitmask.
157 if (RI.hasFP(MF))
158 CPUBitmask |= (1 << MipsRegisterInfo::
159 getRegisterNumbering(RI.getFrameRegister(MF)));
161 if (MF.getFrameInfo()->hasCalls())
162 CPUBitmask |= (1 << MipsRegisterInfo::
163 getRegisterNumbering(RI.getRARegister()));
165 // Print CPUBitmask
166 O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
167 << MipsFI->getCPUTopSavedRegOff() << '\n';
169 // Print FPUBitmask
170 O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
171 << MipsFI->getFPUTopSavedRegOff() << '\n';
174 // Print a 32 bit hex number with all numbers.
175 void MipsAsmPrinter::
176 printHex32(unsigned int Value)
178 O << "0x";
179 for (int i = 7; i >= 0; i--)
180 O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
183 //===----------------------------------------------------------------------===//
184 // Frame and Set directives
185 //===----------------------------------------------------------------------===//
187 /// Frame Directive
188 void MipsAsmPrinter::
189 emitFrameDirective(MachineFunction &MF)
191 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
193 unsigned stackReg = RI.getFrameRegister(MF);
194 unsigned returnReg = RI.getRARegister();
195 unsigned stackSize = MF.getFrameInfo()->getStackSize();
198 O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
199 << ',' << stackSize << ','
200 << '$' << LowercaseString(RI.get(returnReg).AsmName)
201 << '\n';
204 /// Emit Set directives.
205 const char * MipsAsmPrinter::
206 emitCurrentABIString(void)
208 switch(Subtarget->getTargetABI()) {
209 case MipsSubtarget::O32: return "abi32";
210 case MipsSubtarget::O64: return "abiO64";
211 case MipsSubtarget::N32: return "abiN32";
212 case MipsSubtarget::N64: return "abi64";
213 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
214 default: break;
217 assert(0 && "Unknown Mips ABI");
218 return NULL;
221 /// Emit the directives used by GAS on the start of functions
222 void MipsAsmPrinter::
223 emitFunctionStart(MachineFunction &MF)
225 // Print out the label for the function.
226 const Function *F = MF.getFunction();
227 SwitchToSection(TAI->SectionForGlobal(F));
229 // 2 bits aligned
230 EmitAlignment(2, F);
232 O << "\t.globl\t" << CurrentFnName << '\n';
233 O << "\t.ent\t" << CurrentFnName << '\n';
235 printVisibility(CurrentFnName, F->getVisibility());
237 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
238 O << "\t.type\t" << CurrentFnName << ", @function\n";
240 O << CurrentFnName << ":\n";
242 emitFrameDirective(MF);
243 printSavedRegsBitmask(MF);
245 O << '\n';
248 /// Emit the directives used by GAS on the end of functions
249 void MipsAsmPrinter::
250 emitFunctionEnd(MachineFunction &MF)
252 // There are instruction for this macros, but they must
253 // always be at the function end, and we can't emit and
254 // break with BB logic.
255 O << "\t.set\tmacro\n";
256 O << "\t.set\treorder\n";
258 O << "\t.end\t" << CurrentFnName << '\n';
259 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
260 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
263 /// runOnMachineFunction - This uses the printMachineInstruction()
264 /// method to print assembly for each instruction.
265 bool MipsAsmPrinter::
266 runOnMachineFunction(MachineFunction &MF)
268 this->MF = &MF;
270 SetupMachineFunction(MF);
272 // Print out constants referenced by the function
273 EmitConstantPool(MF.getConstantPool());
275 // Print out jump tables referenced by the function
276 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
278 O << "\n\n";
280 // Emit the function start directives
281 emitFunctionStart(MF);
283 // Print out code for the function.
284 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
285 I != E; ++I) {
287 // Print a label for the basic block.
288 if (I != MF.begin()) {
289 printBasicBlockLabel(I, true, true);
290 O << '\n';
293 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
294 II != E; ++II) {
295 // Print the assembly for the instruction.
296 printInstruction(II);
297 ++EmittedInsts;
300 // Each Basic Block is separated by a newline
301 O << '\n';
304 // Emit function end directives
305 emitFunctionEnd(MF);
307 // We didn't modify anything.
308 return false;
311 // Print out an operand for an inline asm expression.
312 bool MipsAsmPrinter::
313 PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
314 unsigned AsmVariant, const char *ExtraCode)
316 // Does this asm operand have a single letter operand modifier?
317 if (ExtraCode && ExtraCode[0])
318 return true; // Unknown modifier.
320 printOperand(MI, OpNo);
321 return false;
324 void MipsAsmPrinter::
325 printOperand(const MachineInstr *MI, int opNum)
327 const MachineOperand &MO = MI->getOperand(opNum);
328 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
329 bool closeP = false;
330 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
331 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
333 // %hi and %lo used on mips gas to load global addresses on
334 // static code. %got is used to load global addresses when
335 // using PIC_. %call16 is used to load direct call targets
336 // on PIC_ and small code size. %call_lo and %call_hi load
337 // direct call targets on PIC_ and large code size.
338 if (MI->getOpcode() == Mips::LUi && !MO.isReg() && !MO.isImm()) {
339 if ((isPIC) && (isCodeLarge))
340 O << "%call_hi(";
341 else
342 O << "%hi(";
343 closeP = true;
344 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isReg() && !MO.isImm()) {
345 const MachineOperand &firstMO = MI->getOperand(opNum-1);
346 if (firstMO.getReg() == Mips::GP)
347 O << "%gp_rel(";
348 else
349 O << "%lo(";
350 closeP = true;
351 } else if ((isPIC) && (MI->getOpcode() == Mips::LW) &&
352 (!MO.isReg()) && (!MO.isImm())) {
353 const MachineOperand &firstMO = MI->getOperand(opNum-1);
354 const MachineOperand &lastMO = MI->getOperand(opNum+1);
355 if ((firstMO.isReg()) && (lastMO.isReg())) {
356 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
357 && (!isCodeLarge))
358 O << "%call16(";
359 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
360 O << "%got(";
361 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
362 && (isCodeLarge))
363 O << "%call_lo(";
364 closeP = true;
368 switch (MO.getType())
370 case MachineOperand::MO_Register:
371 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
372 O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
373 else
374 O << '$' << MO.getReg();
375 break;
377 case MachineOperand::MO_Immediate:
378 O << (short int)MO.getImm();
379 break;
381 case MachineOperand::MO_MachineBasicBlock:
382 printBasicBlockLabel(MO.getMBB());
383 return;
385 case MachineOperand::MO_GlobalAddress:
387 const GlobalValue *GV = MO.getGlobal();
388 O << Mang->getValueName(GV);
390 break;
392 case MachineOperand::MO_ExternalSymbol:
393 O << MO.getSymbolName();
394 break;
396 case MachineOperand::MO_JumpTableIndex:
397 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
398 << '_' << MO.getIndex();
399 break;
401 case MachineOperand::MO_ConstantPoolIndex:
402 O << TAI->getPrivateGlobalPrefix() << "CPI"
403 << getFunctionNumber() << "_" << MO.getIndex();
404 break;
406 default:
407 O << "<unknown operand type>"; abort (); break;
410 if (closeP) O << ")";
413 void MipsAsmPrinter::
414 printUnsignedImm(const MachineInstr *MI, int opNum)
416 const MachineOperand &MO = MI->getOperand(opNum);
417 if (MO.getType() == MachineOperand::MO_Immediate)
418 O << (unsigned short int)MO.getImm();
419 else
420 printOperand(MI, opNum);
423 void MipsAsmPrinter::
424 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
426 // when using stack locations for not load/store instructions
427 // print the same way as all normal 3 operand instructions.
428 if (Modifier && !strcmp(Modifier, "stackloc")) {
429 printOperand(MI, opNum+1);
430 O << ", ";
431 printOperand(MI, opNum);
432 return;
435 // Load/Store memory operands -- imm($reg)
436 // If PIC target the target is loaded as the
437 // pattern lw $25,%call16($28)
438 printOperand(MI, opNum);
439 O << "(";
440 printOperand(MI, opNum+1);
441 O << ")";
444 void MipsAsmPrinter::
445 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier)
447 const MachineOperand& MO = MI->getOperand(opNum);
448 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
451 bool MipsAsmPrinter::
452 doInitialization(Module &M)
454 Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
456 // Tell the assembler which ABI we are using
457 O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
459 // TODO: handle O64 ABI
460 if (Subtarget->isABI_EABI())
461 O << "\t.section .gcc_compiled_long" <<
462 (Subtarget->isGP32bit() ? "32" : "64") << '\n';
464 // return to previous section
465 O << "\t.previous" << '\n';
467 return false; // success
470 void MipsAsmPrinter::
471 printModuleLevelGV(const GlobalVariable* GVar) {
472 const TargetData *TD = TM.getTargetData();
474 if (!GVar->hasInitializer())
475 return; // External global require no code
477 // Check to see if this is a special global used by LLVM, if so, emit it.
478 if (EmitSpecialLLVMGlobal(GVar))
479 return;
481 O << "\n\n";
482 std::string name = Mang->getValueName(GVar);
483 Constant *C = GVar->getInitializer();
484 const Type *CTy = C->getType();
485 unsigned Size = TD->getTypePaddedSize(CTy);
486 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
487 bool printSizeAndType = true;
489 // A data structure or array is aligned in memory to the largest
490 // alignment boundary required by any data type inside it (this matches
491 // the Preferred Type Alignment). For integral types, the alignment is
492 // the type size.
493 unsigned Align;
494 if (CTy->getTypeID() == Type::IntegerTyID ||
495 CTy->getTypeID() == Type::VoidTyID) {
496 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
497 Align = Log2_32(Size);
498 } else
499 Align = TD->getPreferredTypeAlignmentShift(CTy);
501 printVisibility(name, GVar->getVisibility());
503 SwitchToSection(TAI->SectionForGlobal(GVar));
505 if (C->isNullValue() && !GVar->hasSection()) {
506 if (!GVar->isThreadLocal() &&
507 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
508 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
510 if (GVar->hasLocalLinkage())
511 O << "\t.local\t" << name << '\n';
513 O << TAI->getCOMMDirective() << name << ',' << Size;
514 if (TAI->getCOMMDirectiveTakesAlignment())
515 O << ',' << (1 << Align);
517 O << '\n';
518 return;
521 switch (GVar->getLinkage()) {
522 case GlobalValue::LinkOnceAnyLinkage:
523 case GlobalValue::LinkOnceODRLinkage:
524 case GlobalValue::CommonLinkage:
525 case GlobalValue::WeakAnyLinkage:
526 case GlobalValue::WeakODRLinkage:
527 // FIXME: Verify correct for weak.
528 // Nonnull linkonce -> weak
529 O << "\t.weak " << name << '\n';
530 break;
531 case GlobalValue::AppendingLinkage:
532 // FIXME: appending linkage variables should go into a section of their name
533 // or something. For now, just emit them as external.
534 case GlobalValue::ExternalLinkage:
535 // If external or appending, declare as a global symbol
536 O << TAI->getGlobalDirective() << name << '\n';
537 // Fall Through
538 case GlobalValue::PrivateLinkage:
539 case GlobalValue::InternalLinkage:
540 if (CVA && CVA->isCString())
541 printSizeAndType = false;
542 break;
543 case GlobalValue::GhostLinkage:
544 cerr << "Should not have any unmaterialized functions!\n";
545 abort();
546 case GlobalValue::DLLImportLinkage:
547 cerr << "DLLImport linkage is not supported by this target!\n";
548 abort();
549 case GlobalValue::DLLExportLinkage:
550 cerr << "DLLExport linkage is not supported by this target!\n";
551 abort();
552 default:
553 assert(0 && "Unknown linkage type!");
556 EmitAlignment(Align, GVar);
558 if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
559 O << "\t.type " << name << ",@object\n";
560 O << "\t.size " << name << ',' << Size << '\n';
563 O << name << ":\n";
564 EmitGlobalConstant(C);
567 bool MipsAsmPrinter::
568 doFinalization(Module &M)
570 // Print out module-level global variables here.
571 for (Module::const_global_iterator I = M.global_begin(),
572 E = M.global_end(); I != E; ++I)
573 printModuleLevelGV(I);
575 O << '\n';
577 return AsmPrinter::doFinalization(M);