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();
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.
280 Data64bitsDirective = ".quad\t"; // we can't emit a 64-bit unit
282 Data64bitsDirective = 0; // we can't emit a 64-bit unit
283 AlignmentIsInBytes = false; // Alignment is by power of 2.
284 ConstantPoolSection = "\t.const\t";
285 JumpTableDataSection = ".const";
286 JumpTableTextSection = "\t.text";
287 LCOMMDirective = "\t.lcomm\t";
288 StaticCtorsSection = ".mod_init_func";
289 StaticDtorsSection = ".mod_term_func";
290 InlineAsmStart = "# InlineAsm Start";
291 InlineAsmEnd = "# InlineAsm End";
294 virtual const char *getPassName() const {
295 return "Darwin PPC Assembly Printer";
298 bool runOnMachineFunction(MachineFunction &F);
299 bool doInitialization(Module &M);
300 bool doFinalization(Module &M);
302 void getAnalysisUsage(AnalysisUsage &AU) const {
303 AU.setPreservesAll();
304 AU.addRequired<MachineDebugInfo>();
305 PPCAsmPrinter::getAnalysisUsage(AU);
309 } // end of anonymous namespace
311 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
312 /// code for a MachineFunction to the given output stream, in a format that the
313 /// Darwin assembler can deal with.
315 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o,
316 PPCTargetMachine &tm) {
317 return new DarwinAsmPrinter(o, tm);
320 // Include the auto-generated portion of the assembly writer
321 #include "PPCGenAsmWriter.inc"
323 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
324 switch (MO.getType()) {
325 case MachineOperand::MO_Immediate:
326 std::cerr << "printOp() does not handle immediate values\n";
330 case MachineOperand::MO_MachineBasicBlock:
331 printBasicBlockLabel(MO.getMachineBasicBlock());
333 case MachineOperand::MO_JumpTableIndex:
334 O << PrivateGlobalPrefix << "JTI" << getFunctionNumber()
335 << '_' << MO.getJumpTableIndex();
336 // FIXME: PIC relocation model
338 case MachineOperand::MO_ConstantPoolIndex:
339 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
340 << '_' << MO.getConstantPoolIndex();
342 case MachineOperand::MO_ExternalSymbol:
343 // Computing the address of an external symbol, not calling it.
344 if (TM.getRelocationModel() != Reloc::Static) {
345 std::string Name(GlobalPrefix); Name += MO.getSymbolName();
346 GVStubs.insert(Name);
347 O << "L" << Name << "$non_lazy_ptr";
350 O << GlobalPrefix << MO.getSymbolName();
352 case MachineOperand::MO_GlobalAddress: {
353 // Computing the address of a global symbol, not calling it.
354 GlobalValue *GV = MO.getGlobal();
355 std::string Name = Mang->getValueName(GV);
356 int offset = MO.getOffset();
358 // External or weakly linked global variables need non-lazily-resolved stubs
359 if (TM.getRelocationModel() != Reloc::Static) {
360 if (((GV->isExternal() || GV->hasWeakLinkage() ||
361 GV->hasLinkOnceLinkage()))) {
362 GVStubs.insert(Name);
363 O << "L" << Name << "$non_lazy_ptr";
373 O << "<unknown operand type: " << MO.getType() << ">";
378 /// PrintAsmOperand - Print out an operand for an inline asm expression.
380 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
382 const char *ExtraCode) {
383 // Does this asm operand have a single letter operand modifier?
384 if (ExtraCode && ExtraCode[0]) {
385 if (ExtraCode[1] != 0) return true; // Unknown modifier.
387 switch (ExtraCode[0]) {
388 default: return true; // Unknown modifier.
389 case 'L': // Write second word of DImode reference.
390 // Verify that this operand has two consecutive registers.
391 if (!MI->getOperand(OpNo).isRegister() ||
392 OpNo+1 == MI->getNumOperands() ||
393 !MI->getOperand(OpNo+1).isRegister())
395 ++OpNo; // Return the high-part.
400 printOperand(MI, OpNo);
404 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
406 const char *ExtraCode) {
407 if (ExtraCode && ExtraCode[0])
408 return true; // Unknown modifier.
409 printMemRegReg(MI, OpNo);
413 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
414 /// the current output stream.
416 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
419 // Check for slwi/srwi mnemonics.
420 if (MI->getOpcode() == PPC::RLWINM) {
421 bool FoundMnemonic = false;
422 unsigned char SH = MI->getOperand(2).getImmedValue();
423 unsigned char MB = MI->getOperand(3).getImmedValue();
424 unsigned char ME = MI->getOperand(4).getImmedValue();
425 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
426 O << "slwi "; FoundMnemonic = true;
428 if (SH <= 31 && MB == (32-SH) && ME == 31) {
429 O << "srwi "; FoundMnemonic = true;
436 O << ", " << (unsigned int)SH << "\n";
439 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
440 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
450 if (printInstruction(MI))
451 return; // Printer was automatically generated
453 assert(0 && "Unhandled instruction in asm writer!");
458 /// runOnMachineFunction - This uses the printMachineInstruction()
459 /// method to print assembly for each instruction.
461 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
462 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
464 SetupMachineFunction(MF);
467 // Print out constants referenced by the function
468 EmitConstantPool(MF.getConstantPool());
470 // Print out jump tables referenced by the function
471 EmitJumpTableInfo(MF.getJumpTableInfo());
473 // Print out labels for the function.
474 const Function *F = MF.getFunction();
475 switch (F->getLinkage()) {
476 default: assert(0 && "Unknown linkage type!");
477 case Function::InternalLinkage: // Symbols default to internal.
478 SwitchToTextSection("\t.text", F);
480 case Function::ExternalLinkage:
481 SwitchToTextSection("\t.text", F);
482 O << "\t.globl\t" << CurrentFnName << "\n";
484 case Function::WeakLinkage:
485 case Function::LinkOnceLinkage:
487 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
488 O << "\t.globl\t" << CurrentFnName << "\n";
489 O << "\t.weak_definition\t" << CurrentFnName << "\n";
493 O << CurrentFnName << ":\n";
495 // Emit pre-function debug information.
496 DW.BeginFunction(&MF);
498 // Print out code for the function.
499 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
501 // Print a label for the basic block.
502 if (I != MF.begin()) {
503 printBasicBlockLabel(I, true);
506 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
508 // Print the assembly for the instruction.
510 printMachineInstruction(II);
514 // Emit post-function debug information.
517 // We didn't modify anything.
522 bool DarwinAsmPrinter::doInitialization(Module &M) {
523 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
524 O << "\t.machine ppc970\n";
525 AsmPrinter::doInitialization(M);
527 // Darwin wants symbols to be quoted if they have complex names.
528 Mang->setUseQuotes(true);
530 // Emit initial debug information.
535 bool DarwinAsmPrinter::doFinalization(Module &M) {
536 const TargetData *TD = TM.getTargetData();
538 // Print out module-level global variables here.
539 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
541 if (!I->hasInitializer()) continue; // External global require no code
543 // Check to see if this is a special global used by LLVM, if so, emit it.
544 if (EmitSpecialLLVMGlobal(I))
547 std::string name = Mang->getValueName(I);
548 Constant *C = I->getInitializer();
549 unsigned Size = TD->getTypeSize(C->getType());
550 unsigned Align = getPreferredAlignmentLog(I);
552 if (C->isNullValue() && /* FIXME: Verify correct */
553 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
554 I->hasLinkOnceLinkage() ||
555 (I->hasExternalLinkage() && !I->hasSection()))) {
556 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
557 if (I->hasExternalLinkage()) {
558 O << "\t.globl " << name << '\n';
559 O << "\t.zerofill __DATA, __common, " << name << ", "
560 << Size << ", " << Align;
561 } else if (I->hasInternalLinkage()) {
562 SwitchToDataSection("\t.data", I);
563 O << LCOMMDirective << name << "," << Size << "," << Align;
565 SwitchToDataSection("\t.data", I);
566 O << ".comm " << name << "," << Size;
568 O << "\t\t; '" << I->getName() << "'\n";
570 switch (I->getLinkage()) {
571 case GlobalValue::LinkOnceLinkage:
572 case GlobalValue::WeakLinkage:
573 O << "\t.globl " << name << '\n'
574 << "\t.weak_definition " << name << '\n';
575 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
577 case GlobalValue::AppendingLinkage:
578 // FIXME: appending linkage variables should go into a section of
579 // their name or something. For now, just emit them as external.
580 case GlobalValue::ExternalLinkage:
581 // If external or appending, declare as a global symbol
582 O << "\t.globl " << name << "\n";
584 case GlobalValue::InternalLinkage:
585 SwitchToDataSection("\t.data", I);
588 std::cerr << "Unknown linkage type!";
592 EmitAlignment(Align, I);
593 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
594 EmitGlobalConstant(C);
599 bool isPPC64 = TD->getPointerSizeInBits() == 64;
601 // Output stubs for dynamically-linked functions
602 if (TM.getRelocationModel() == Reloc::PIC_) {
603 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
605 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
606 "pure_instructions,32", 0);
608 O << "L" << *i << "$stub:\n";
609 O << "\t.indirect_symbol " << *i << "\n";
611 O << "\tbcl 20,31,L0$" << *i << "\n";
612 O << "L0$" << *i << ":\n";
614 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
617 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
619 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
620 O << "\tmtctr r12\n";
622 SwitchToDataSection(".lazy_symbol_pointer", 0);
623 O << "L" << *i << "$lazy_ptr:\n";
624 O << "\t.indirect_symbol " << *i << "\n";
626 O << "\t.quad dyld_stub_binding_helper\n";
628 O << "\t.long dyld_stub_binding_helper\n";
631 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
633 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
634 "pure_instructions,16", 0);
636 O << "L" << *i << "$stub:\n";
637 O << "\t.indirect_symbol " << *i << "\n";
638 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
640 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
642 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
643 O << "\tmtctr r12\n";
645 SwitchToDataSection(".lazy_symbol_pointer", 0);
646 O << "L" << *i << "$lazy_ptr:\n";
647 O << "\t.indirect_symbol " << *i << "\n";
649 O << "\t.quad dyld_stub_binding_helper\n";
651 O << "\t.long dyld_stub_binding_helper\n";
657 // Output stubs for external and common global variables.
658 if (GVStubs.begin() != GVStubs.end()) {
659 SwitchToDataSection(".non_lazy_symbol_pointer", 0);
660 for (std::set<std::string>::iterator I = GVStubs.begin(),
661 E = GVStubs.end(); I != E; ++I) {
662 O << "L" << *I << "$non_lazy_ptr:\n";
663 O << "\t.indirect_symbol " << *I << "\n";
672 // Emit initial debug information.
675 // Funny Darwin hack: This flag tells the linker that no global symbols
676 // contain code that falls through to other global symbols (e.g. the obvious
677 // implementation of multiple entry points). If this doesn't occur, the
678 // linker can safely perform dead code stripping. Since LLVM never generates
679 // code that does this, it is always safe to set.
680 O << "\t.subsections_via_symbols\n";
682 AsmPrinter::doFinalization(M);
683 return false; // success