1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
21 #include "PPCTargetMachine.h"
22 #include "PPCSubtarget.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/CodeGen/MachineDebugInfo.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Target/TargetAsmInfo.h"
38 #include "llvm/Target/MRegisterInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringExtras.h"
48 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
50 struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
51 std::set<std::string> FnStubs, GVStubs;
53 PPCAsmPrinter(std::ostream &O, TargetMachine &TM, TargetAsmInfo *T)
54 : AsmPrinter(O, TM, T) {}
56 virtual const char *getPassName() const {
57 return "PowerPC Assembly Printer";
60 PPCTargetMachine &getTM() {
61 return static_cast<PPCTargetMachine&>(TM);
64 unsigned enumRegToMachineReg(unsigned enumReg) {
66 default: assert(0 && "Unhandled register!"); break;
67 case PPC::CR0: return 0;
68 case PPC::CR1: return 1;
69 case PPC::CR2: return 2;
70 case PPC::CR3: return 3;
71 case PPC::CR4: return 4;
72 case PPC::CR5: return 5;
73 case PPC::CR6: return 6;
74 case PPC::CR7: return 7;
79 /// printInstruction - This method is automatically generated by tablegen
80 /// from the instruction set description. This method returns true if the
81 /// machine instruction was sufficiently described to print it, otherwise it
83 bool printInstruction(const MachineInstr *MI);
85 void printMachineInstruction(const MachineInstr *MI);
86 void printOp(const MachineOperand &MO);
88 void printOperand(const MachineInstr *MI, unsigned OpNo) {
89 const MachineOperand &MO = MI->getOperand(OpNo);
90 if (MO.isRegister()) {
91 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
92 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
93 } else if (MO.isImmediate()) {
94 O << MO.getImmedValue();
100 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
101 unsigned AsmVariant, const char *ExtraCode);
102 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
103 unsigned AsmVariant, const char *ExtraCode);
106 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
107 char value = MI->getOperand(OpNo).getImmedValue();
108 value = (value << (32-5)) >> (32-5);
111 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
112 unsigned char value = MI->getOperand(OpNo).getImmedValue();
113 assert(value <= 31 && "Invalid u5imm argument!");
114 O << (unsigned int)value;
116 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
117 unsigned char value = MI->getOperand(OpNo).getImmedValue();
118 assert(value <= 63 && "Invalid u6imm argument!");
119 O << (unsigned int)value;
121 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
122 O << (short)MI->getOperand(OpNo).getImmedValue();
124 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
125 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
127 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
128 O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
130 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
131 // Branches can take an immediate operand. This is used by the branch
132 // selection pass to print $+8, an eight byte displacement from the PC.
133 if (MI->getOperand(OpNo).isImmediate()) {
134 O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
136 printOp(MI->getOperand(OpNo));
139 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
140 const MachineOperand &MO = MI->getOperand(OpNo);
141 if (TM.getRelocationModel() != Reloc::Static) {
142 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
143 GlobalValue *GV = MO.getGlobal();
144 if (((GV->isExternal() || GV->hasWeakLinkage() ||
145 GV->hasLinkOnceLinkage()))) {
146 // Dynamically-resolved functions need a stub for the function.
147 std::string Name = Mang->getValueName(GV);
148 FnStubs.insert(Name);
149 O << "L" << Name << "$stub";
153 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
154 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
155 FnStubs.insert(Name);
156 O << "L" << Name << "$stub";
161 printOp(MI->getOperand(OpNo));
163 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
164 O << (int)MI->getOperand(OpNo).getImmedValue()*4;
166 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
167 O << "\"L" << getFunctionNumber() << "$pb\"\n";
168 O << "\"L" << getFunctionNumber() << "$pb\":";
170 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
171 if (MI->getOperand(OpNo).isImmediate()) {
172 printS16ImmOperand(MI, OpNo);
175 printOp(MI->getOperand(OpNo));
176 if (TM.getRelocationModel() == Reloc::PIC_)
177 O << "-\"L" << getFunctionNumber() << "$pb\")";
182 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
183 if (MI->getOperand(OpNo).isImmediate()) {
184 printS16ImmOperand(MI, OpNo);
187 printOp(MI->getOperand(OpNo));
188 if (TM.getRelocationModel() == Reloc::PIC_)
189 O << "-\"L" << getFunctionNumber() << "$pb\")";
194 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
195 unsigned CCReg = MI->getOperand(OpNo).getReg();
196 unsigned RegNo = enumRegToMachineReg(CCReg);
197 O << (0x80 >> RegNo);
199 // The new addressing mode printers.
200 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
201 printSymbolLo(MI, OpNo);
203 if (MI->getOperand(OpNo+1).isRegister() &&
204 MI->getOperand(OpNo+1).getReg() == PPC::R0)
207 printOperand(MI, OpNo+1);
210 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
211 if (MI->getOperand(OpNo).isImmediate())
212 printS16X4ImmOperand(MI, OpNo);
214 printSymbolLo(MI, OpNo);
216 if (MI->getOperand(OpNo+1).isRegister() &&
217 MI->getOperand(OpNo+1).getReg() == PPC::R0)
220 printOperand(MI, OpNo+1);
224 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
225 // When used as the base register, r0 reads constant zero rather than
226 // the value contained in the register. For this reason, the darwin
227 // assembler requires that we print r0 as 0 (no r) when used as the base.
228 const MachineOperand &MO = MI->getOperand(OpNo);
229 if (MO.getReg() == PPC::R0)
232 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
234 printOperand(MI, OpNo+1);
237 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
238 virtual bool doFinalization(Module &M) = 0;
242 struct VISIBILITY_HIDDEN DarwinTargetAsmInfo : public TargetAsmInfo {
243 DarwinTargetAsmInfo(PPCTargetMachine &TM) {
244 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
248 PrivateGlobalPrefix = "L";
249 ZeroDirective = "\t.space\t";
250 SetDirective = "\t.set";
251 Data64bitsDirective = isPPC64 ? ".quad\t" : 0;
252 AlignmentIsInBytes = false;
253 ConstantPoolSection = "\t.const\t";
254 JumpTableDataSection = ".const";
255 JumpTableTextSection = "\t.text";
256 LCOMMDirective = "\t.lcomm\t";
257 StaticCtorsSection = ".mod_init_func";
258 StaticDtorsSection = ".mod_term_func";
259 InlineAsmStart = "# InlineAsm Start";
260 InlineAsmEnd = "# InlineAsm End";
263 AddressSize = isPPC64 ? 8 : 4;
264 DwarfAbbrevSection = ".section __DWARF,__debug_abbrev";
265 DwarfInfoSection = ".section __DWARF,__debug_info";
266 DwarfLineSection = ".section __DWARF,__debug_line";
267 DwarfFrameSection = ".section __DWARF,__debug_frame";
268 DwarfPubNamesSection = ".section __DWARF,__debug_pubnames";
269 DwarfPubTypesSection = ".section __DWARF,__debug_pubtypes";
270 DwarfStrSection = ".section __DWARF,__debug_str";
271 DwarfLocSection = ".section __DWARF,__debug_loc";
272 DwarfARangesSection = ".section __DWARF,__debug_aranges";
273 DwarfRangesSection = ".section __DWARF,__debug_ranges";
274 DwarfMacInfoSection = ".section __DWARF,__debug_macinfo";
278 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
280 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
284 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM, TargetAsmInfo *T)
285 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
286 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
289 virtual const char *getPassName() const {
290 return "Darwin PPC Assembly Printer";
293 bool runOnMachineFunction(MachineFunction &F);
294 bool doInitialization(Module &M);
295 bool doFinalization(Module &M);
297 void getAnalysisUsage(AnalysisUsage &AU) const {
298 AU.setPreservesAll();
299 AU.addRequired<MachineDebugInfo>();
300 PPCAsmPrinter::getAnalysisUsage(AU);
304 } // end of anonymous namespace
306 /// createDarwinCodePrinterPass - Returns a pass that prints the PPC assembly
307 /// code for a MachineFunction to the given output stream, in a format that the
308 /// Darwin assembler can deal with.
310 FunctionPass *llvm::createDarwinCodePrinterPass(std::ostream &o,
311 PPCTargetMachine &tm) {
312 TargetAsmInfo *TAI = new DarwinTargetAsmInfo(tm);
313 return new DarwinAsmPrinter(o, tm, TAI);
316 // Include the auto-generated portion of the assembly writer
317 #include "PPCGenAsmWriter.inc"
319 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
320 switch (MO.getType()) {
321 case MachineOperand::MO_Immediate:
322 std::cerr << "printOp() does not handle immediate values\n";
326 case MachineOperand::MO_MachineBasicBlock:
327 printBasicBlockLabel(MO.getMachineBasicBlock());
329 case MachineOperand::MO_JumpTableIndex:
330 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
331 << '_' << MO.getJumpTableIndex();
332 // FIXME: PIC relocation model
334 case MachineOperand::MO_ConstantPoolIndex:
335 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
336 << '_' << MO.getConstantPoolIndex();
338 case MachineOperand::MO_ExternalSymbol:
339 // Computing the address of an external symbol, not calling it.
340 if (TM.getRelocationModel() != Reloc::Static) {
341 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
342 GVStubs.insert(Name);
343 O << "L" << Name << "$non_lazy_ptr";
346 O << TAI->getGlobalPrefix() << MO.getSymbolName();
348 case MachineOperand::MO_GlobalAddress: {
349 // Computing the address of a global symbol, not calling it.
350 GlobalValue *GV = MO.getGlobal();
351 std::string Name = Mang->getValueName(GV);
352 int offset = MO.getOffset();
354 // External or weakly linked global variables need non-lazily-resolved stubs
355 if (TM.getRelocationModel() != Reloc::Static) {
356 if (((GV->isExternal() || GV->hasWeakLinkage() ||
357 GV->hasLinkOnceLinkage()))) {
358 GVStubs.insert(Name);
359 O << "L" << Name << "$non_lazy_ptr";
369 O << "<unknown operand type: " << MO.getType() << ">";
374 /// PrintAsmOperand - Print out an operand for an inline asm expression.
376 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
378 const char *ExtraCode) {
379 // Does this asm operand have a single letter operand modifier?
380 if (ExtraCode && ExtraCode[0]) {
381 if (ExtraCode[1] != 0) return true; // Unknown modifier.
383 switch (ExtraCode[0]) {
384 default: return true; // Unknown modifier.
385 case 'L': // Write second word of DImode reference.
386 // Verify that this operand has two consecutive registers.
387 if (!MI->getOperand(OpNo).isRegister() ||
388 OpNo+1 == MI->getNumOperands() ||
389 !MI->getOperand(OpNo+1).isRegister())
391 ++OpNo; // Return the high-part.
396 printOperand(MI, OpNo);
400 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
402 const char *ExtraCode) {
403 if (ExtraCode && ExtraCode[0])
404 return true; // Unknown modifier.
405 printMemRegReg(MI, OpNo);
409 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
410 /// the current output stream.
412 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
415 // Check for slwi/srwi mnemonics.
416 if (MI->getOpcode() == PPC::RLWINM) {
417 bool FoundMnemonic = false;
418 unsigned char SH = MI->getOperand(2).getImmedValue();
419 unsigned char MB = MI->getOperand(3).getImmedValue();
420 unsigned char ME = MI->getOperand(4).getImmedValue();
421 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
422 O << "slwi "; FoundMnemonic = true;
424 if (SH <= 31 && MB == (32-SH) && ME == 31) {
425 O << "srwi "; FoundMnemonic = true;
432 O << ", " << (unsigned int)SH << "\n";
435 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
436 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
446 if (printInstruction(MI))
447 return; // Printer was automatically generated
449 assert(0 && "Unhandled instruction in asm writer!");
454 /// runOnMachineFunction - This uses the printMachineInstruction()
455 /// method to print assembly for each instruction.
457 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
458 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
460 SetupMachineFunction(MF);
463 // Print out constants referenced by the function
464 EmitConstantPool(MF.getConstantPool());
466 // Print out jump tables referenced by the function
467 EmitJumpTableInfo(MF.getJumpTableInfo());
469 // Print out labels for the function.
470 const Function *F = MF.getFunction();
471 switch (F->getLinkage()) {
472 default: assert(0 && "Unknown linkage type!");
473 case Function::InternalLinkage: // Symbols default to internal.
474 SwitchToTextSection("\t.text", F);
476 case Function::ExternalLinkage:
477 SwitchToTextSection("\t.text", F);
478 O << "\t.globl\t" << CurrentFnName << "\n";
480 case Function::WeakLinkage:
481 case Function::LinkOnceLinkage:
483 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
484 O << "\t.globl\t" << CurrentFnName << "\n";
485 O << "\t.weak_definition\t" << CurrentFnName << "\n";
489 O << CurrentFnName << ":\n";
491 // Emit pre-function debug information.
492 DW.BeginFunction(&MF);
494 // Print out code for the function.
495 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
497 // Print a label for the basic block.
498 if (I != MF.begin()) {
499 printBasicBlockLabel(I, true);
502 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
504 // Print the assembly for the instruction.
506 printMachineInstruction(II);
510 // Emit post-function debug information.
513 // We didn't modify anything.
518 bool DarwinAsmPrinter::doInitialization(Module &M) {
519 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
520 O << "\t.machine ppc970\n";
521 AsmPrinter::doInitialization(M);
523 // Darwin wants symbols to be quoted if they have complex names.
524 Mang->setUseQuotes(true);
526 // Emit initial debug information.
531 bool DarwinAsmPrinter::doFinalization(Module &M) {
532 const TargetData *TD = TM.getTargetData();
534 // Print out module-level global variables here.
535 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
537 if (!I->hasInitializer()) continue; // External global require no code
539 // Check to see if this is a special global used by LLVM, if so, emit it.
540 if (EmitSpecialLLVMGlobal(I))
543 std::string name = Mang->getValueName(I);
544 Constant *C = I->getInitializer();
545 unsigned Size = TD->getTypeSize(C->getType());
546 unsigned Align = getPreferredAlignmentLog(I);
548 if (C->isNullValue() && /* FIXME: Verify correct */
549 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
550 I->hasLinkOnceLinkage() ||
551 (I->hasExternalLinkage() && !I->hasSection()))) {
552 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
553 if (I->hasExternalLinkage()) {
554 O << "\t.globl " << name << '\n';
555 O << "\t.zerofill __DATA, __common, " << name << ", "
556 << Size << ", " << Align;
557 } else if (I->hasInternalLinkage()) {
558 SwitchToDataSection("\t.data", I);
559 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
561 SwitchToDataSection("\t.data", I);
562 O << ".comm " << name << "," << Size;
564 O << "\t\t; '" << I->getName() << "'\n";
566 switch (I->getLinkage()) {
567 case GlobalValue::LinkOnceLinkage:
568 case GlobalValue::WeakLinkage:
569 O << "\t.globl " << name << '\n'
570 << "\t.weak_definition " << name << '\n';
571 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
573 case GlobalValue::AppendingLinkage:
574 // FIXME: appending linkage variables should go into a section of
575 // their name or something. For now, just emit them as external.
576 case GlobalValue::ExternalLinkage:
577 // If external or appending, declare as a global symbol
578 O << "\t.globl " << name << "\n";
580 case GlobalValue::InternalLinkage:
581 SwitchToDataSection("\t.data", I);
584 std::cerr << "Unknown linkage type!";
588 EmitAlignment(Align, I);
589 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
590 EmitGlobalConstant(C);
595 bool isPPC64 = TD->getPointerSizeInBits() == 64;
597 // Output stubs for dynamically-linked functions
598 if (TM.getRelocationModel() == Reloc::PIC_) {
599 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
601 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
602 "pure_instructions,32", 0);
604 O << "L" << *i << "$stub:\n";
605 O << "\t.indirect_symbol " << *i << "\n";
607 O << "\tbcl 20,31,L0$" << *i << "\n";
608 O << "L0$" << *i << ":\n";
610 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
613 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
615 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
616 O << "\tmtctr r12\n";
618 SwitchToDataSection(".lazy_symbol_pointer", 0);
619 O << "L" << *i << "$lazy_ptr:\n";
620 O << "\t.indirect_symbol " << *i << "\n";
622 O << "\t.quad dyld_stub_binding_helper\n";
624 O << "\t.long dyld_stub_binding_helper\n";
627 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
629 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
630 "pure_instructions,16", 0);
632 O << "L" << *i << "$stub:\n";
633 O << "\t.indirect_symbol " << *i << "\n";
634 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
636 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
638 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
639 O << "\tmtctr r12\n";
641 SwitchToDataSection(".lazy_symbol_pointer", 0);
642 O << "L" << *i << "$lazy_ptr:\n";
643 O << "\t.indirect_symbol " << *i << "\n";
645 O << "\t.quad dyld_stub_binding_helper\n";
647 O << "\t.long dyld_stub_binding_helper\n";
653 // Output stubs for external and common global variables.
654 if (GVStubs.begin() != GVStubs.end()) {
655 SwitchToDataSection(".non_lazy_symbol_pointer", 0);
656 for (std::set<std::string>::iterator I = GVStubs.begin(),
657 E = GVStubs.end(); I != E; ++I) {
658 O << "L" << *I << "$non_lazy_ptr:\n";
659 O << "\t.indirect_symbol " << *I << "\n";
668 // Emit initial debug information.
671 // Funny Darwin hack: This flag tells the linker that no global symbols
672 // contain code that falls through to other global symbols (e.g. the obvious
673 // implementation of multiple entry points). If this doesn't occur, the
674 // linker can safely perform dead code stripping. Since LLVM never generates
675 // code that does this, it is always safe to set.
676 O << "\t.subsections_via_symbols\n";
678 AsmPrinter::doFinalization(M);
679 return false; // success