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/Visibility.h"
37 #include "llvm/Target/MRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringExtras.h"
47 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
49 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
51 std::set<std::string> FnStubs, GVStubs;
53 PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
54 : AsmPrinter(O, TM) {}
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(GlobalPrefix); 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 /// DarwinDwarfWriter - Dwarf debug info writer customized for Darwin/Mac OS X
244 struct VISIBILITY_HIDDEN DarwinDwarfWriter : public DwarfWriter {
246 DarwinDwarfWriter(std::ostream &o, AsmPrinter *ap)
250 DwarfAbbrevSection = ".section __DWARF,__debug_abbrev";
251 DwarfInfoSection = ".section __DWARF,__debug_info";
252 DwarfLineSection = ".section __DWARF,__debug_line";
253 DwarfFrameSection = ".section __DWARF,__debug_frame";
254 DwarfPubNamesSection = ".section __DWARF,__debug_pubnames";
255 DwarfPubTypesSection = ".section __DWARF,__debug_pubtypes";
256 DwarfStrSection = ".section __DWARF,__debug_str";
257 DwarfLocSection = ".section __DWARF,__debug_loc";
258 DwarfARangesSection = ".section __DWARF,__debug_aranges";
259 DwarfRangesSection = ".section __DWARF,__debug_ranges";
260 DwarfMacInfoSection = ".section __DWARF,__debug_macinfo";
261 TextSection = ".text";
262 DataSection = ".data";
266 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
268 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
270 DarwinDwarfWriter DW;
272 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM)
273 : PPCAsmPrinter(O, TM), DW(O, this) {
274 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
277 PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
278 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
279 SetDirective = "\t.set";
281 Data64bitsDirective = ".quad\t"; // we can't emit a 64-bit unit
283 Data64bitsDirective = 0; // we can't emit a 64-bit unit
284 AlignmentIsInBytes = false; // Alignment is by power of 2.
285 ConstantPoolSection = "\t.const\t";
286 JumpTableDataSection = ".const";
287 JumpTableTextSection = "\t.text";
288 LCOMMDirective = "\t.lcomm\t";
289 StaticCtorsSection = ".mod_init_func";
290 StaticDtorsSection = ".mod_term_func";
291 InlineAsmStart = "# InlineAsm Start";
292 InlineAsmEnd = "# InlineAsm End";
295 virtual const char *getPassName() const {
296 return "Darwin PPC Assembly Printer";
299 bool runOnMachineFunction(MachineFunction &F);
300 bool doInitialization(Module &M);
301 bool doFinalization(Module &M);
303 void getAnalysisUsage(AnalysisUsage &AU) const {
304 AU.setPreservesAll();
305 AU.addRequired<MachineDebugInfo>();
306 PPCAsmPrinter::getAnalysisUsage(AU);
310 } // end of anonymous namespace
312 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
313 /// code for a MachineFunction to the given output stream, in a format that the
314 /// Darwin assembler can deal with.
316 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o,
317 PPCTargetMachine &tm) {
318 return new DarwinAsmPrinter(o, tm);
321 // Include the auto-generated portion of the assembly writer
322 #include "PPCGenAsmWriter.inc"
324 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
325 switch (MO.getType()) {
326 case MachineOperand::MO_Immediate:
327 std::cerr << "printOp() does not handle immediate values\n";
331 case MachineOperand::MO_MachineBasicBlock:
332 printBasicBlockLabel(MO.getMachineBasicBlock());
334 case MachineOperand::MO_JumpTableIndex:
335 O << PrivateGlobalPrefix << "JTI" << getFunctionNumber()
336 << '_' << MO.getJumpTableIndex();
337 // FIXME: PIC relocation model
339 case MachineOperand::MO_ConstantPoolIndex:
340 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
341 << '_' << MO.getConstantPoolIndex();
343 case MachineOperand::MO_ExternalSymbol:
344 // Computing the address of an external symbol, not calling it.
345 if (TM.getRelocationModel() != Reloc::Static) {
346 std::string Name(GlobalPrefix); Name += MO.getSymbolName();
347 GVStubs.insert(Name);
348 O << "L" << Name << "$non_lazy_ptr";
351 O << GlobalPrefix << MO.getSymbolName();
353 case MachineOperand::MO_GlobalAddress: {
354 // Computing the address of a global symbol, not calling it.
355 GlobalValue *GV = MO.getGlobal();
356 std::string Name = Mang->getValueName(GV);
357 int offset = MO.getOffset();
359 // External or weakly linked global variables need non-lazily-resolved stubs
360 if (TM.getRelocationModel() != Reloc::Static) {
361 if (((GV->isExternal() || GV->hasWeakLinkage() ||
362 GV->hasLinkOnceLinkage()))) {
363 GVStubs.insert(Name);
364 O << "L" << Name << "$non_lazy_ptr";
374 O << "<unknown operand type: " << MO.getType() << ">";
379 /// PrintAsmOperand - Print out an operand for an inline asm expression.
381 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
383 const char *ExtraCode) {
384 // Does this asm operand have a single letter operand modifier?
385 if (ExtraCode && ExtraCode[0]) {
386 if (ExtraCode[1] != 0) return true; // Unknown modifier.
388 switch (ExtraCode[0]) {
389 default: return true; // Unknown modifier.
390 case 'L': // Write second word of DImode reference.
391 // Verify that this operand has two consecutive registers.
392 if (!MI->getOperand(OpNo).isRegister() ||
393 OpNo+1 == MI->getNumOperands() ||
394 !MI->getOperand(OpNo+1).isRegister())
396 ++OpNo; // Return the high-part.
401 printOperand(MI, OpNo);
405 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
407 const char *ExtraCode) {
408 if (ExtraCode && ExtraCode[0])
409 return true; // Unknown modifier.
410 printMemRegReg(MI, OpNo);
414 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
415 /// the current output stream.
417 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
420 // Check for slwi/srwi mnemonics.
421 if (MI->getOpcode() == PPC::RLWINM) {
422 bool FoundMnemonic = false;
423 unsigned char SH = MI->getOperand(2).getImmedValue();
424 unsigned char MB = MI->getOperand(3).getImmedValue();
425 unsigned char ME = MI->getOperand(4).getImmedValue();
426 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
427 O << "slwi "; FoundMnemonic = true;
429 if (SH <= 31 && MB == (32-SH) && ME == 31) {
430 O << "srwi "; FoundMnemonic = true;
437 O << ", " << (unsigned int)SH << "\n";
440 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
441 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
451 if (printInstruction(MI))
452 return; // Printer was automatically generated
454 assert(0 && "Unhandled instruction in asm writer!");
459 /// runOnMachineFunction - This uses the printMachineInstruction()
460 /// method to print assembly for each instruction.
462 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
463 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
465 SetupMachineFunction(MF);
468 // Print out constants referenced by the function
469 EmitConstantPool(MF.getConstantPool());
471 // Print out jump tables referenced by the function
472 EmitJumpTableInfo(MF.getJumpTableInfo());
474 // Print out labels for the function.
475 const Function *F = MF.getFunction();
476 switch (F->getLinkage()) {
477 default: assert(0 && "Unknown linkage type!");
478 case Function::InternalLinkage: // Symbols default to internal.
479 SwitchToTextSection("\t.text", F);
481 case Function::ExternalLinkage:
482 SwitchToTextSection("\t.text", F);
483 O << "\t.globl\t" << CurrentFnName << "\n";
485 case Function::WeakLinkage:
486 case Function::LinkOnceLinkage:
488 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
489 O << "\t.globl\t" << CurrentFnName << "\n";
490 O << "\t.weak_definition\t" << CurrentFnName << "\n";
494 O << CurrentFnName << ":\n";
496 // Emit pre-function debug information.
497 DW.BeginFunction(&MF);
499 // Print out code for the function.
500 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
502 // Print a label for the basic block.
503 if (I != MF.begin()) {
504 printBasicBlockLabel(I, true);
507 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
509 // Print the assembly for the instruction.
511 printMachineInstruction(II);
515 // Emit post-function debug information.
518 // We didn't modify anything.
523 bool DarwinAsmPrinter::doInitialization(Module &M) {
524 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
525 O << "\t.machine ppc970\n";
526 AsmPrinter::doInitialization(M);
528 // Darwin wants symbols to be quoted if they have complex names.
529 Mang->setUseQuotes(true);
531 // Emit initial debug information.
536 bool DarwinAsmPrinter::doFinalization(Module &M) {
537 const TargetData *TD = TM.getTargetData();
539 // Print out module-level global variables here.
540 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
542 if (!I->hasInitializer()) continue; // External global require no code
544 // Check to see if this is a special global used by LLVM, if so, emit it.
545 if (EmitSpecialLLVMGlobal(I))
548 std::string name = Mang->getValueName(I);
549 Constant *C = I->getInitializer();
550 unsigned Size = TD->getTypeSize(C->getType());
551 unsigned Align = getPreferredAlignmentLog(I);
553 if (C->isNullValue() && /* FIXME: Verify correct */
554 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
555 I->hasLinkOnceLinkage() ||
556 (I->hasExternalLinkage() && !I->hasSection()))) {
557 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
558 if (I->hasExternalLinkage()) {
559 O << "\t.globl " << name << '\n';
560 O << "\t.zerofill __DATA, __common, " << name << ", "
561 << Size << ", " << Align;
562 } else if (I->hasInternalLinkage()) {
563 SwitchToDataSection("\t.data", I);
564 O << LCOMMDirective << name << "," << Size << "," << Align;
566 SwitchToDataSection("\t.data", I);
567 O << ".comm " << name << "," << Size;
569 O << "\t\t; '" << I->getName() << "'\n";
571 switch (I->getLinkage()) {
572 case GlobalValue::LinkOnceLinkage:
573 case GlobalValue::WeakLinkage:
574 O << "\t.globl " << name << '\n'
575 << "\t.weak_definition " << name << '\n';
576 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
578 case GlobalValue::AppendingLinkage:
579 // FIXME: appending linkage variables should go into a section of
580 // their name or something. For now, just emit them as external.
581 case GlobalValue::ExternalLinkage:
582 // If external or appending, declare as a global symbol
583 O << "\t.globl " << name << "\n";
585 case GlobalValue::InternalLinkage:
586 SwitchToDataSection("\t.data", I);
589 std::cerr << "Unknown linkage type!";
593 EmitAlignment(Align, I);
594 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
595 EmitGlobalConstant(C);
600 bool isPPC64 = TD->getPointerSizeInBits() == 64;
602 // Output stubs for dynamically-linked functions
603 if (TM.getRelocationModel() == Reloc::PIC_) {
604 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
606 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
607 "pure_instructions,32", 0);
609 O << "L" << *i << "$stub:\n";
610 O << "\t.indirect_symbol " << *i << "\n";
612 O << "\tbcl 20,31,L0$" << *i << "\n";
613 O << "L0$" << *i << ":\n";
615 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
618 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
620 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
621 O << "\tmtctr r12\n";
623 SwitchToDataSection(".lazy_symbol_pointer", 0);
624 O << "L" << *i << "$lazy_ptr:\n";
625 O << "\t.indirect_symbol " << *i << "\n";
627 O << "\t.quad dyld_stub_binding_helper\n";
629 O << "\t.long dyld_stub_binding_helper\n";
632 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
634 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
635 "pure_instructions,16", 0);
637 O << "L" << *i << "$stub:\n";
638 O << "\t.indirect_symbol " << *i << "\n";
639 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
641 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
643 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
644 O << "\tmtctr r12\n";
646 SwitchToDataSection(".lazy_symbol_pointer", 0);
647 O << "L" << *i << "$lazy_ptr:\n";
648 O << "\t.indirect_symbol " << *i << "\n";
650 O << "\t.quad dyld_stub_binding_helper\n";
652 O << "\t.long dyld_stub_binding_helper\n";
658 // Output stubs for external and common global variables.
659 if (GVStubs.begin() != GVStubs.end()) {
660 SwitchToDataSection(".non_lazy_symbol_pointer", 0);
661 for (std::set<std::string>::iterator I = GVStubs.begin(),
662 E = GVStubs.end(); I != E; ++I) {
663 O << "L" << *I << "$non_lazy_ptr:\n";
664 O << "\t.indirect_symbol " << *I << "\n";
673 // Emit initial debug information.
676 // Funny Darwin hack: This flag tells the linker that no global symbols
677 // contain code that falls through to other global symbols (e.g. the obvious
678 // implementation of multiple entry points). If this doesn't occur, the
679 // linker can safely perform dead code stripping. Since LLVM never generates
680 // code that does this, it is always safe to set.
681 O << "\t.subsections_via_symbols\n";
683 AsmPrinter::doFinalization(M);
684 return false; // success