1 //===-- SPUAsmPrinter.cpp - Print machine instrs to Cell SPU assembly -------=//
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 Cell SPU assembly language. This printer
12 // is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asmprinter"
18 #include "SPUTargetMachine.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
46 const std::string bss_section(".bss");
48 struct VISIBILITY_HIDDEN SPUAsmPrinter : public AsmPrinter {
49 std::set<std::string> FnStubs, GVStubs;
51 SPUAsmPrinter(raw_ostream &O, TargetMachine &TM, const TargetAsmInfo *T) :
56 virtual const char *getPassName() const {
57 return "STI CBEA SPU Assembly Printer";
60 SPUTargetMachine &getTM() {
61 return static_cast<SPUTargetMachine&>(TM);
64 /// printInstruction - This method is automatically generated by tablegen
65 /// from the instruction set description. This method returns true if the
66 /// machine instruction was sufficiently described to print it, otherwise it
68 bool printInstruction(const MachineInstr *MI);
70 void printMachineInstruction(const MachineInstr *MI);
71 void printOp(const MachineOperand &MO);
73 /// printRegister - Print register according to target requirements.
75 void printRegister(const MachineOperand &MO, bool R0AsZero) {
76 unsigned RegNo = MO.getReg();
77 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) &&
79 O << TM.getRegisterInfo()->get(RegNo).AsmName;
82 void printOperand(const MachineInstr *MI, unsigned OpNo) {
83 const MachineOperand &MO = MI->getOperand(OpNo);
84 if (MO.isRegister()) {
85 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
86 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
87 } else if (MO.isImmediate()) {
94 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
95 unsigned AsmVariant, const char *ExtraCode);
96 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
97 unsigned AsmVariant, const char *ExtraCode);
101 printS7ImmOperand(const MachineInstr *MI, unsigned OpNo)
103 int value = MI->getOperand(OpNo).getImm();
104 value = (value << (32 - 7)) >> (32 - 7);
106 assert((value >= -(1 << 8) && value <= (1 << 7) - 1)
107 && "Invalid s7 argument");
112 printU7ImmOperand(const MachineInstr *MI, unsigned OpNo)
114 unsigned int value = MI->getOperand(OpNo).getImm();
115 assert(value < (1 << 8) && "Invalid u7 argument");
120 printMemRegImmS7(const MachineInstr *MI, unsigned OpNo)
122 char value = MI->getOperand(OpNo).getImm();
125 printOperand(MI, OpNo+1);
130 printS16ImmOperand(const MachineInstr *MI, unsigned OpNo)
132 O << (short) MI->getOperand(OpNo).getImm();
136 printU16ImmOperand(const MachineInstr *MI, unsigned OpNo)
138 O << (unsigned short)MI->getOperand(OpNo).getImm();
142 printU32ImmOperand(const MachineInstr *MI, unsigned OpNo)
144 O << (unsigned)MI->getOperand(OpNo).getImm();
148 printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
149 // When used as the base register, r0 reads constant zero rather than
150 // the value contained in the register. For this reason, the darwin
151 // assembler requires that we print r0 as 0 (no r) when used as the base.
152 const MachineOperand &MO = MI->getOperand(OpNo);
153 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
155 printOperand(MI, OpNo+1);
159 printU18ImmOperand(const MachineInstr *MI, unsigned OpNo)
161 unsigned int value = MI->getOperand(OpNo).getImm();
162 assert(value <= (1 << 19) - 1 && "Invalid u18 argument");
167 printS10ImmOperand(const MachineInstr *MI, unsigned OpNo)
169 short value = (short) (((int) MI->getOperand(OpNo).getImm() << 16)
171 assert((value >= -(1 << 9) && value <= (1 << 9) - 1)
172 && "Invalid s10 argument");
177 printU10ImmOperand(const MachineInstr *MI, unsigned OpNo)
179 short value = (short) (((int) MI->getOperand(OpNo).getImm() << 16)
181 assert((value <= (1 << 10) - 1) && "Invalid u10 argument");
186 printMemRegImmS10(const MachineInstr *MI, unsigned OpNo)
188 const MachineOperand &MO = MI->getOperand(OpNo);
189 assert(MO.isImmediate()
190 && "printMemRegImmS10 first operand is not immedate");
191 printS10ImmOperand(MI, OpNo);
193 printOperand(MI, OpNo+1);
198 printAddr256K(const MachineInstr *MI, unsigned OpNo)
200 /* Note: operand 1 is an offset or symbol name. */
201 if (MI->getOperand(OpNo).isImmediate()) {
202 printS16ImmOperand(MI, OpNo);
204 printOp(MI->getOperand(OpNo));
205 if (MI->getOperand(OpNo+1).isImmediate()) {
206 int displ = int(MI->getOperand(OpNo+1).getImm());
215 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
216 printOp(MI->getOperand(OpNo));
219 void printPCRelativeOperand(const MachineInstr *MI, unsigned OpNo) {
220 printOp(MI->getOperand(OpNo));
224 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
225 if (MI->getOperand(OpNo).isImmediate()) {
226 printS16ImmOperand(MI, OpNo);
228 printOp(MI->getOperand(OpNo));
233 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
234 if (MI->getOperand(OpNo).isImmediate()) {
235 printS16ImmOperand(MI, OpNo);
237 printOp(MI->getOperand(OpNo));
242 /// Print local store address
243 void printSymbolLSA(const MachineInstr *MI, unsigned OpNo) {
244 printOp(MI->getOperand(OpNo));
247 void printROTHNeg7Imm(const MachineInstr *MI, unsigned OpNo) {
248 if (MI->getOperand(OpNo).isImmediate()) {
249 int value = (int) MI->getOperand(OpNo).getImm();
250 assert((value >= 0 && value < 16)
251 && "Invalid negated immediate rotate 7-bit argument");
254 assert(0 &&"Invalid/non-immediate rotate amount in printRotateNeg7Imm");
258 void printROTNeg7Imm(const MachineInstr *MI, unsigned OpNo) {
259 if (MI->getOperand(OpNo).isImmediate()) {
260 int value = (int) MI->getOperand(OpNo).getImm();
261 assert((value >= 0 && value < 32)
262 && "Invalid negated immediate rotate 7-bit argument");
265 assert(0 &&"Invalid/non-immediate rotate amount in printRotateNeg7Imm");
269 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
270 virtual bool doFinalization(Module &M) = 0;
273 /// LinuxAsmPrinter - SPU assembly printer, customized for Linux
274 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public SPUAsmPrinter {
277 MachineModuleInfo *MMI;
279 LinuxAsmPrinter(raw_ostream &O, SPUTargetMachine &TM,
280 const TargetAsmInfo *T) :
281 SPUAsmPrinter(O, TM, T),
286 virtual const char *getPassName() const {
287 return "STI CBEA SPU Assembly Printer";
290 bool runOnMachineFunction(MachineFunction &F);
291 bool doInitialization(Module &M);
292 bool doFinalization(Module &M);
294 void getAnalysisUsage(AnalysisUsage &AU) const {
295 AU.setPreservesAll();
296 AU.addRequired<MachineModuleInfo>();
297 SPUAsmPrinter::getAnalysisUsage(AU);
301 } // end of anonymous namespace
303 // Include the auto-generated portion of the assembly writer
304 #include "SPUGenAsmWriter.inc"
306 void SPUAsmPrinter::printOp(const MachineOperand &MO) {
307 switch (MO.getType()) {
308 case MachineOperand::MO_Immediate:
309 cerr << "printOp() does not handle immediate values\n";
313 case MachineOperand::MO_MachineBasicBlock:
314 printBasicBlockLabel(MO.getMBB());
316 case MachineOperand::MO_JumpTableIndex:
317 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
318 << '_' << MO.getIndex();
320 case MachineOperand::MO_ConstantPoolIndex:
321 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
322 << '_' << MO.getIndex();
324 case MachineOperand::MO_ExternalSymbol:
325 // Computing the address of an external symbol, not calling it.
326 if (TM.getRelocationModel() != Reloc::Static) {
327 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
328 GVStubs.insert(Name);
329 O << "L" << Name << "$non_lazy_ptr";
332 O << TAI->getGlobalPrefix() << MO.getSymbolName();
334 case MachineOperand::MO_GlobalAddress: {
335 // Computing the address of a global symbol, not calling it.
336 GlobalValue *GV = MO.getGlobal();
337 std::string Name = Mang->getValueName(GV);
339 // External or weakly linked global variables need non-lazily-resolved
341 if (TM.getRelocationModel() != Reloc::Static) {
342 if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
343 GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
344 GVStubs.insert(Name);
345 O << "L" << Name << "$non_lazy_ptr";
351 if (GV->hasExternalWeakLinkage())
352 ExtWeakSymbols.insert(GV);
357 O << "<unknown operand type: " << MO.getType() << ">";
362 /// PrintAsmOperand - Print out an operand for an inline asm expression.
364 bool SPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
366 const char *ExtraCode) {
367 // Does this asm operand have a single letter operand modifier?
368 if (ExtraCode && ExtraCode[0]) {
369 if (ExtraCode[1] != 0) return true; // Unknown modifier.
371 switch (ExtraCode[0]) {
372 default: return true; // Unknown modifier.
373 case 'L': // Write second word of DImode reference.
374 // Verify that this operand has two consecutive registers.
375 if (!MI->getOperand(OpNo).isRegister() ||
376 OpNo+1 == MI->getNumOperands() ||
377 !MI->getOperand(OpNo+1).isRegister())
379 ++OpNo; // Return the high-part.
384 printOperand(MI, OpNo);
388 bool SPUAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
391 const char *ExtraCode) {
392 if (ExtraCode && ExtraCode[0])
393 return true; // Unknown modifier.
394 printMemRegReg(MI, OpNo);
398 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax
399 /// to the current output stream.
401 void SPUAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
403 printInstruction(MI);
406 /// runOnMachineFunction - This uses the printMachineInstruction()
407 /// method to print assembly for each instruction.
410 LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF)
412 SetupMachineFunction(MF);
415 // Print out constants referenced by the function
416 EmitConstantPool(MF.getConstantPool());
418 // Print out labels for the function.
419 const Function *F = MF.getFunction();
421 SwitchToSection(TAI->SectionForGlobal(F));
424 switch (F->getLinkage()) {
425 default: assert(0 && "Unknown linkage type!");
426 case Function::InternalLinkage: // Symbols default to internal.
428 case Function::ExternalLinkage:
429 O << "\t.global\t" << CurrentFnName << "\n"
430 << "\t.type\t" << CurrentFnName << ", @function\n";
432 case Function::WeakLinkage:
433 case Function::LinkOnceLinkage:
434 O << "\t.global\t" << CurrentFnName << "\n";
435 O << "\t.weak_definition\t" << CurrentFnName << "\n";
438 O << CurrentFnName << ":\n";
440 // Emit pre-function debug information.
441 DW.BeginFunction(&MF);
443 // Print out code for the function.
444 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
446 // Print a label for the basic block.
447 if (I != MF.begin()) {
448 printBasicBlockLabel(I, true, true);
451 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
453 // Print the assembly for the instruction.
454 printMachineInstruction(II);
458 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
460 // Print out jump tables referenced by the function.
461 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
463 // Emit post-function debug information.
466 // We didn't modify anything.
471 bool LinuxAsmPrinter::doInitialization(Module &M) {
472 bool Result = AsmPrinter::doInitialization(M);
473 SwitchToTextSection("\t.text");
474 // Emit initial debug information.
476 MMI = getAnalysisToUpdate<MachineModuleInfo>();
477 DW.SetModuleInfo(MMI);
481 bool LinuxAsmPrinter::doFinalization(Module &M) {
482 const TargetData *TD = TM.getTargetData();
484 // Print out module-level global variables here.
485 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
487 if (!I->hasInitializer()) continue; // External global require no code
489 // Check to see if this is a special global used by LLVM, if so, emit it.
490 if (EmitSpecialLLVMGlobal(I))
493 std::string name = Mang->getValueName(I);
494 Constant *C = I->getInitializer();
495 unsigned Size = TD->getTypeStoreSize(C->getType());
496 unsigned Align = TD->getPreferredAlignmentLog(I);
498 if (C->isNullValue() && /* FIXME: Verify correct */
499 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
500 I->hasLinkOnceLinkage() || I->hasCommonLinkage() ||
501 (I->hasExternalLinkage() && !I->hasSection()))) {
502 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
503 if (I->hasExternalLinkage()) {
504 // External linkage globals -> .bss section
505 // FIXME: Want to set the global variable's section so that
506 // SwitchToDataSection emits the ".section" directive
507 SwitchToDataSection("\t.section\t.bss", I);
508 O << "\t.global\t" << name << '\n';
509 O << "\t.align\t" << Align << '\n';
510 O << "\t.type\t" << name << ", @object\n";
511 O << "\t.size\t" << name << ", " << Size << '\n';
513 O << "\t.zero\t" << Size;
514 } else if (I->hasInternalLinkage()) {
515 SwitchToDataSection("\t.data", I);
516 O << ".local " << name << "\n";
517 O << TAI->getCOMMDirective() << name << "," << Size << "," << Align << "\n";
519 SwitchToDataSection("\t.data", I);
520 O << ".comm " << name << "," << Size;
522 O << "\t\t# '" << I->getName() << "'\n";
524 switch (I->getLinkage()) {
525 case GlobalValue::LinkOnceLinkage:
526 case GlobalValue::WeakLinkage:
527 case GlobalValue::CommonLinkage:
528 O << "\t.global " << name << '\n'
529 << "\t.weak_definition " << name << '\n';
530 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
532 case GlobalValue::AppendingLinkage:
533 // FIXME: appending linkage variables should go into a section of
534 // their name or something. For now, just emit them as external.
535 case GlobalValue::ExternalLinkage:
536 // If external or appending, declare as a global symbol
537 O << "\t.global " << name << "\n";
539 case GlobalValue::InternalLinkage:
540 if (I->isConstant()) {
541 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
542 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
543 SwitchToDataSection("\t.cstring", I);
548 SwitchToDataSection("\t.data", I);
551 cerr << "Unknown linkage type!";
555 EmitAlignment(Align, I);
556 O << name << ":\t\t\t\t# '" << I->getName() << "'\n";
558 // If the initializer is a extern weak symbol, remember to emit the weak
560 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
561 if (GV->hasExternalWeakLinkage())
562 ExtWeakSymbols.insert(GV);
564 EmitGlobalConstant(C);
569 // Output stubs for dynamically-linked functions
570 if (TM.getRelocationModel() == Reloc::PIC_) {
571 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
573 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
574 "pure_instructions,32");
576 O << "L" << *i << "$stub:\n";
577 O << "\t.indirect_symbol " << *i << "\n";
579 O << "\tbcl 20,31,L0$" << *i << "\n";
580 O << "L0$" << *i << ":\n";
582 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
584 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
585 O << "\tmtctr r12\n";
587 SwitchToDataSection(".lazy_symbol_pointer");
588 O << "L" << *i << "$lazy_ptr:\n";
589 O << "\t.indirect_symbol " << *i << "\n";
590 O << "\t.long dyld_stub_binding_helper\n";
593 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
595 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
596 "pure_instructions,16");
598 O << "L" << *i << "$stub:\n";
599 O << "\t.indirect_symbol " << *i << "\n";
600 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
601 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
602 O << "\tmtctr r12\n";
604 SwitchToDataSection(".lazy_symbol_pointer");
605 O << "L" << *i << "$lazy_ptr:\n";
606 O << "\t.indirect_symbol " << *i << "\n";
607 O << "\t.long dyld_stub_binding_helper\n";
613 // Output stubs for external and common global variables.
614 if (GVStubs.begin() != GVStubs.end()) {
615 SwitchToDataSection(".non_lazy_symbol_pointer");
616 for (std::set<std::string>::iterator I = GVStubs.begin(),
617 E = GVStubs.end(); I != E; ++I) {
618 O << "L" << *I << "$non_lazy_ptr:\n";
619 O << "\t.indirect_symbol " << *I << "\n";
624 // Emit initial debug information.
627 // Emit ident information
628 O << "\t.ident\t\"(llvm 2.2+) STI CBEA Cell SPU backend\"\n";
630 return AsmPrinter::doFinalization(M);
635 /// createSPUCodePrinterPass - Returns a pass that prints the Cell SPU
636 /// assembly code for a MachineFunction to the given output stream, in a format
637 /// that the Linux SPU assembler can deal with.
639 FunctionPass *llvm::createSPUAsmPrinterPass(raw_ostream &o,
640 SPUTargetMachine &tm) {
641 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());