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/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/StringExtras.h"
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45 const std::string bss_section(".bss");
47 struct VISIBILITY_HIDDEN SPUAsmPrinter : public AsmPrinter {
48 std::set<std::string> FnStubs, GVStubs;
50 SPUAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T) :
55 virtual const char *getPassName() const {
56 return "STI CBEA SPU Assembly Printer";
59 SPUTargetMachine &getTM() {
60 return static_cast<SPUTargetMachine&>(TM);
63 /// printInstruction - This method is automatically generated by tablegen
64 /// from the instruction set description. This method returns true if the
65 /// machine instruction was sufficiently described to print it, otherwise it
67 bool printInstruction(const MachineInstr *MI);
69 void printMachineInstruction(const MachineInstr *MI);
70 void printOp(const MachineOperand &MO);
72 /// printRegister - Print register according to target requirements.
74 void printRegister(const MachineOperand &MO, bool R0AsZero) {
75 unsigned RegNo = MO.getReg();
76 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) &&
78 O << TM.getRegisterInfo()->get(RegNo).AsmName;
81 void printOperand(const MachineInstr *MI, unsigned OpNo) {
82 const MachineOperand &MO = MI->getOperand(OpNo);
83 if (MO.isRegister()) {
84 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
85 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
86 } else if (MO.isImmediate()) {
93 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
94 unsigned AsmVariant, const char *ExtraCode);
95 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
96 unsigned AsmVariant, const char *ExtraCode);
100 printS7ImmOperand(const MachineInstr *MI, unsigned OpNo)
102 int value = MI->getOperand(OpNo).getImm();
103 value = (value << (32 - 7)) >> (32 - 7);
105 assert((value >= -(1 << 8) && value <= (1 << 7) - 1)
106 && "Invalid s7 argument");
111 printU7ImmOperand(const MachineInstr *MI, unsigned OpNo)
113 unsigned int value = MI->getOperand(OpNo).getImm();
114 assert(value < (1 << 8) && "Invalid u7 argument");
119 printMemRegImmS7(const MachineInstr *MI, unsigned OpNo)
121 char value = MI->getOperand(OpNo).getImm();
124 printOperand(MI, OpNo+1);
129 printS16ImmOperand(const MachineInstr *MI, unsigned OpNo)
131 O << (short) MI->getOperand(OpNo).getImm();
135 printU16ImmOperand(const MachineInstr *MI, unsigned OpNo)
137 O << (unsigned short)MI->getOperand(OpNo).getImm();
141 printU32ImmOperand(const MachineInstr *MI, unsigned OpNo)
143 O << (unsigned)MI->getOperand(OpNo).getImm();
147 printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
148 // When used as the base register, r0 reads constant zero rather than
149 // the value contained in the register. For this reason, the darwin
150 // assembler requires that we print r0 as 0 (no r) when used as the base.
151 const MachineOperand &MO = MI->getOperand(OpNo);
152 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
154 printOperand(MI, OpNo+1);
158 printU18ImmOperand(const MachineInstr *MI, unsigned OpNo)
160 unsigned int value = MI->getOperand(OpNo).getImm();
161 assert(value <= (1 << 19) - 1 && "Invalid u18 argument");
166 printS10ImmOperand(const MachineInstr *MI, unsigned OpNo)
168 short value = (short) (((int) MI->getOperand(OpNo).getImm() << 16)
170 assert((value >= -(1 << 9) && value <= (1 << 9) - 1)
171 && "Invalid s10 argument");
176 printU10ImmOperand(const MachineInstr *MI, unsigned OpNo)
178 short value = (short) (((int) MI->getOperand(OpNo).getImm() << 16)
180 assert((value <= (1 << 10) - 1) && "Invalid u10 argument");
185 printMemRegImmS10(const MachineInstr *MI, unsigned OpNo)
187 const MachineOperand &MO = MI->getOperand(OpNo);
188 assert(MO.isImmediate()
189 && "printMemRegImmS10 first operand is not immedate");
190 printS10ImmOperand(MI, OpNo);
192 printOperand(MI, OpNo+1);
197 printAddr256K(const MachineInstr *MI, unsigned OpNo)
199 /* Note: operand 1 is an offset or symbol name. */
200 if (MI->getOperand(OpNo).isImmediate()) {
201 printS16ImmOperand(MI, OpNo);
203 printOp(MI->getOperand(OpNo));
204 if (MI->getOperand(OpNo+1).isImmediate()) {
205 int displ = int(MI->getOperand(OpNo+1).getImm());
214 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
215 printOp(MI->getOperand(OpNo));
218 void printPCRelativeOperand(const MachineInstr *MI, unsigned OpNo) {
219 printOp(MI->getOperand(OpNo));
223 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
224 if (MI->getOperand(OpNo).isImmediate()) {
225 printS16ImmOperand(MI, OpNo);
227 printOp(MI->getOperand(OpNo));
232 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
233 if (MI->getOperand(OpNo).isImmediate()) {
234 printS16ImmOperand(MI, OpNo);
236 printOp(MI->getOperand(OpNo));
241 /// Print local store address
242 void printSymbolLSA(const MachineInstr *MI, unsigned OpNo) {
243 printOp(MI->getOperand(OpNo));
246 void printROTHNeg7Imm(const MachineInstr *MI, unsigned OpNo) {
247 if (MI->getOperand(OpNo).isImmediate()) {
248 int value = (int) MI->getOperand(OpNo).getImm();
249 assert((value >= 0 && value < 16)
250 && "Invalid negated immediate rotate 7-bit argument");
253 assert(0 &&"Invalid/non-immediate rotate amount in printRotateNeg7Imm");
257 void printROTNeg7Imm(const MachineInstr *MI, unsigned OpNo) {
258 if (MI->getOperand(OpNo).isImmediate()) {
259 int value = (int) MI->getOperand(OpNo).getImm();
260 assert((value >= 0 && value < 32)
261 && "Invalid negated immediate rotate 7-bit argument");
264 assert(0 &&"Invalid/non-immediate rotate amount in printRotateNeg7Imm");
268 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
269 virtual bool doFinalization(Module &M) = 0;
272 /// LinuxAsmPrinter - SPU assembly printer, customized for Linux
273 struct VISIBILITY_HIDDEN LinuxAsmPrinter : public SPUAsmPrinter {
277 LinuxAsmPrinter(std::ostream &O, SPUTargetMachine &TM,
278 const TargetAsmInfo *T) :
279 SPUAsmPrinter(O, TM, T),
283 virtual const char *getPassName() const {
284 return "STI CBEA SPU Assembly Printer";
287 bool runOnMachineFunction(MachineFunction &F);
288 bool doInitialization(Module &M);
289 bool doFinalization(Module &M);
291 void getAnalysisUsage(AnalysisUsage &AU) const {
292 AU.setPreservesAll();
293 AU.addRequired<MachineModuleInfo>();
294 SPUAsmPrinter::getAnalysisUsage(AU);
297 /// getSectionForFunction - Return the section that we should emit the
298 /// specified function body into.
299 virtual std::string getSectionForFunction(const Function &F) const;
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);
408 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
409 switch (F.getLinkage()) {
410 default: assert(0 && "Unknown linkage type!");
411 case Function::ExternalLinkage:
412 case Function::InternalLinkage: return TAI->getTextSection();
413 case Function::WeakLinkage:
414 case Function::LinkOnceLinkage:
415 return ""; // Print nothing for the time being...
419 /// runOnMachineFunction - This uses the printMachineInstruction()
420 /// method to print assembly for each instruction.
423 LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF)
425 DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
427 SetupMachineFunction(MF);
430 // Print out constants referenced by the function
431 EmitConstantPool(MF.getConstantPool());
433 // Print out labels for the function.
434 const Function *F = MF.getFunction();
436 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
439 switch (F->getLinkage()) {
440 default: assert(0 && "Unknown linkage type!");
441 case Function::InternalLinkage: // Symbols default to internal.
443 case Function::ExternalLinkage:
444 O << "\t.global\t" << CurrentFnName << "\n"
445 << "\t.type\t" << CurrentFnName << ", @function\n";
447 case Function::WeakLinkage:
448 case Function::LinkOnceLinkage:
449 O << "\t.global\t" << CurrentFnName << "\n";
450 O << "\t.weak_definition\t" << CurrentFnName << "\n";
453 O << CurrentFnName << ":\n";
455 // Emit pre-function debug information.
456 DW.BeginFunction(&MF);
458 // Print out code for the function.
459 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
461 // Print a label for the basic block.
462 if (I != MF.begin()) {
463 printBasicBlockLabel(I, true, true);
466 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
468 // Print the assembly for the instruction.
469 printMachineInstruction(II);
473 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
475 // Print out jump tables referenced by the function.
476 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
478 // Emit post-function debug information.
481 // We didn't modify anything.
486 bool LinuxAsmPrinter::doInitialization(Module &M) {
487 bool Result = AsmPrinter::doInitialization(M);
488 SwitchToTextSection(TAI->getTextSection());
489 // Emit initial debug information.
494 bool LinuxAsmPrinter::doFinalization(Module &M) {
495 const TargetData *TD = TM.getTargetData();
497 // Print out module-level global variables here.
498 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
500 if (!I->hasInitializer()) continue; // External global require no code
502 // Check to see if this is a special global used by LLVM, if so, emit it.
503 if (EmitSpecialLLVMGlobal(I))
506 std::string name = Mang->getValueName(I);
507 Constant *C = I->getInitializer();
508 unsigned Size = TD->getTypeStoreSize(C->getType());
509 unsigned Align = TD->getPreferredAlignmentLog(I);
511 if (C->isNullValue() && /* FIXME: Verify correct */
512 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
513 I->hasLinkOnceLinkage() || I->hasCommonLinkage() ||
514 (I->hasExternalLinkage() && !I->hasSection()))) {
515 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
516 if (I->hasExternalLinkage()) {
517 // External linkage globals -> .bss section
518 // FIXME: Want to set the global variable's section so that
519 // SwitchToDataSection emits the ".section" directive
520 SwitchToDataSection("\t.section\t.bss", I);
521 O << "\t.global\t" << name << '\n';
522 O << "\t.align\t" << Align << '\n';
523 O << "\t.type\t" << name << ", @object\n";
524 O << "\t.size\t" << name << ", " << Size << '\n';
526 O << "\t.zero\t" << Size;
527 } else if (I->hasInternalLinkage()) {
528 SwitchToDataSection("\t.data", I);
529 O << ".local " << name << "\n";
530 O << TAI->getCOMMDirective() << name << "," << Size << "," << Align << "\n";
532 SwitchToDataSection("\t.data", I);
533 O << ".comm " << name << "," << Size;
535 O << "\t\t# '" << I->getName() << "'\n";
537 switch (I->getLinkage()) {
538 case GlobalValue::LinkOnceLinkage:
539 case GlobalValue::WeakLinkage:
540 case GlobalValue::CommonLinkage:
541 O << "\t.global " << name << '\n'
542 << "\t.weak_definition " << name << '\n';
543 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
545 case GlobalValue::AppendingLinkage:
546 // FIXME: appending linkage variables should go into a section of
547 // their name or something. For now, just emit them as external.
548 case GlobalValue::ExternalLinkage:
549 // If external or appending, declare as a global symbol
550 O << "\t.global " << name << "\n";
552 case GlobalValue::InternalLinkage:
553 if (I->isConstant()) {
554 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
555 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
556 SwitchToDataSection(TAI->getCStringSection(), I);
561 SwitchToDataSection("\t.data", I);
564 cerr << "Unknown linkage type!";
568 EmitAlignment(Align, I);
569 O << name << ":\t\t\t\t# '" << I->getName() << "'\n";
571 // If the initializer is a extern weak symbol, remember to emit the weak
573 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
574 if (GV->hasExternalWeakLinkage())
575 ExtWeakSymbols.insert(GV);
577 EmitGlobalConstant(C);
582 // Output stubs for dynamically-linked functions
583 if (TM.getRelocationModel() == Reloc::PIC_) {
584 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
586 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
587 "pure_instructions,32");
589 O << "L" << *i << "$stub:\n";
590 O << "\t.indirect_symbol " << *i << "\n";
592 O << "\tbcl 20,31,L0$" << *i << "\n";
593 O << "L0$" << *i << ":\n";
595 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
597 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
598 O << "\tmtctr r12\n";
600 SwitchToDataSection(".lazy_symbol_pointer");
601 O << "L" << *i << "$lazy_ptr:\n";
602 O << "\t.indirect_symbol " << *i << "\n";
603 O << "\t.long dyld_stub_binding_helper\n";
606 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
608 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
609 "pure_instructions,16");
611 O << "L" << *i << "$stub:\n";
612 O << "\t.indirect_symbol " << *i << "\n";
613 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
614 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
615 O << "\tmtctr r12\n";
617 SwitchToDataSection(".lazy_symbol_pointer");
618 O << "L" << *i << "$lazy_ptr:\n";
619 O << "\t.indirect_symbol " << *i << "\n";
620 O << "\t.long dyld_stub_binding_helper\n";
626 // Output stubs for external and common global variables.
627 if (GVStubs.begin() != GVStubs.end()) {
628 SwitchToDataSection(".non_lazy_symbol_pointer");
629 for (std::set<std::string>::iterator I = GVStubs.begin(),
630 E = GVStubs.end(); I != E; ++I) {
631 O << "L" << *I << "$non_lazy_ptr:\n";
632 O << "\t.indirect_symbol " << *I << "\n";
637 // Emit initial debug information.
640 // Emit ident information
641 O << "\t.ident\t\"(llvm 2.2+) STI CBEA Cell SPU backend\"\n";
643 return AsmPrinter::doFinalization(M);
648 /// createSPUCodePrinterPass - Returns a pass that prints the Cell SPU
649 /// assembly code for a MachineFunction to the given output stream, in a format
650 /// that the Linux SPU assembler can deal with.
652 FunctionPass *llvm::createSPUAsmPrinterPass(std::ostream &o,
653 SPUTargetMachine &tm) {
654 return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());