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;
52 const PPCSubtarget &Subtarget;
54 PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
55 : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
58 virtual const char *getPassName() const {
59 return "PowerPC Assembly Printer";
62 PPCTargetMachine &getTM() {
63 return static_cast<PPCTargetMachine&>(TM);
66 unsigned enumRegToMachineReg(unsigned enumReg) {
68 default: assert(0 && "Unhandled register!"); break;
69 case PPC::CR0: return 0;
70 case PPC::CR1: return 1;
71 case PPC::CR2: return 2;
72 case PPC::CR3: return 3;
73 case PPC::CR4: return 4;
74 case PPC::CR5: return 5;
75 case PPC::CR6: return 6;
76 case PPC::CR7: return 7;
81 /// printInstruction - This method is automatically generated by tablegen
82 /// from the instruction set description. This method returns true if the
83 /// machine instruction was sufficiently described to print it, otherwise it
85 bool printInstruction(const MachineInstr *MI);
87 void printMachineInstruction(const MachineInstr *MI);
88 void printOp(const MachineOperand &MO);
90 void printOperand(const MachineInstr *MI, unsigned OpNo) {
91 const MachineOperand &MO = MI->getOperand(OpNo);
92 if (MO.isRegister()) {
93 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
94 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
95 } else if (MO.isImmediate()) {
96 O << MO.getImmedValue();
102 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
103 unsigned AsmVariant, const char *ExtraCode);
104 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
105 unsigned AsmVariant, const char *ExtraCode);
108 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
109 char value = MI->getOperand(OpNo).getImmedValue();
110 value = (value << (32-5)) >> (32-5);
113 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
114 unsigned char value = MI->getOperand(OpNo).getImmedValue();
115 assert(value <= 31 && "Invalid u5imm argument!");
116 O << (unsigned int)value;
118 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
119 unsigned char value = MI->getOperand(OpNo).getImmedValue();
120 assert(value <= 63 && "Invalid u6imm argument!");
121 O << (unsigned int)value;
123 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
124 O << (short)MI->getOperand(OpNo).getImmedValue();
126 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
127 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
129 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
130 O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
132 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
133 // Branches can take an immediate operand. This is used by the branch
134 // selection pass to print $+8, an eight byte displacement from the PC.
135 if (MI->getOperand(OpNo).isImmediate()) {
136 O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
138 printOp(MI->getOperand(OpNo));
141 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
142 const MachineOperand &MO = MI->getOperand(OpNo);
143 if (TM.getRelocationModel() != Reloc::Static) {
144 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
145 GlobalValue *GV = MO.getGlobal();
146 if (((GV->isExternal() || GV->hasWeakLinkage() ||
147 GV->hasLinkOnceLinkage()))) {
148 // Dynamically-resolved functions need a stub for the function.
149 std::string Name = Mang->getValueName(GV);
150 FnStubs.insert(Name);
151 O << "L" << Name << "$stub";
155 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
156 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
157 FnStubs.insert(Name);
158 O << "L" << Name << "$stub";
163 printOp(MI->getOperand(OpNo));
165 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
166 O << (int)MI->getOperand(OpNo).getImmedValue()*4;
168 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
169 O << "\"L" << getFunctionNumber() << "$pb\"\n";
170 O << "\"L" << getFunctionNumber() << "$pb\":";
172 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
173 if (MI->getOperand(OpNo).isImmediate()) {
174 printS16ImmOperand(MI, OpNo);
177 printOp(MI->getOperand(OpNo));
178 if (TM.getRelocationModel() == Reloc::PIC_)
179 O << "-\"L" << getFunctionNumber() << "$pb\")";
184 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
185 if (MI->getOperand(OpNo).isImmediate()) {
186 printS16ImmOperand(MI, OpNo);
189 printOp(MI->getOperand(OpNo));
190 if (TM.getRelocationModel() == Reloc::PIC_)
191 O << "-\"L" << getFunctionNumber() << "$pb\")";
196 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
197 unsigned CCReg = MI->getOperand(OpNo).getReg();
198 unsigned RegNo = enumRegToMachineReg(CCReg);
199 O << (0x80 >> RegNo);
201 // The new addressing mode printers.
202 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
203 printSymbolLo(MI, OpNo);
205 if (MI->getOperand(OpNo+1).isRegister() &&
206 MI->getOperand(OpNo+1).getReg() == PPC::R0)
209 printOperand(MI, OpNo+1);
212 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
213 if (MI->getOperand(OpNo).isImmediate())
214 printS16X4ImmOperand(MI, OpNo);
216 printSymbolLo(MI, OpNo);
218 if (MI->getOperand(OpNo+1).isRegister() &&
219 MI->getOperand(OpNo+1).getReg() == PPC::R0)
222 printOperand(MI, OpNo+1);
226 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
227 // When used as the base register, r0 reads constant zero rather than
228 // the value contained in the register. For this reason, the darwin
229 // assembler requires that we print r0 as 0 (no r) when used as the base.
230 const MachineOperand &MO = MI->getOperand(OpNo);
231 if (MO.getReg() == PPC::R0)
234 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
236 printOperand(MI, OpNo+1);
239 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
240 virtual bool doFinalization(Module &M) = 0;
243 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
245 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
249 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
250 const TargetAsmInfo *T)
251 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
252 bool isPPC64 = Subtarget.isPPC64();
255 virtual const char *getPassName() const {
256 return "Darwin PPC Assembly Printer";
259 bool runOnMachineFunction(MachineFunction &F);
260 bool doInitialization(Module &M);
261 bool doFinalization(Module &M);
263 void getAnalysisUsage(AnalysisUsage &AU) const {
264 AU.setPreservesAll();
265 AU.addRequired<MachineDebugInfo>();
266 PPCAsmPrinter::getAnalysisUsage(AU);
269 /// getSectionForFunction - Return the section that we should emit the
270 /// specified function body into.
271 virtual std::string getSectionForFunction(const Function &F) const;
273 } // end of anonymous namespace
275 // Include the auto-generated portion of the assembly writer
276 #include "PPCGenAsmWriter.inc"
278 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
279 switch (MO.getType()) {
280 case MachineOperand::MO_Immediate:
281 std::cerr << "printOp() does not handle immediate values\n";
285 case MachineOperand::MO_MachineBasicBlock:
286 printBasicBlockLabel(MO.getMachineBasicBlock());
288 case MachineOperand::MO_JumpTableIndex:
289 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
290 << '_' << MO.getJumpTableIndex();
291 // FIXME: PIC relocation model
293 case MachineOperand::MO_ConstantPoolIndex:
294 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
295 << '_' << MO.getConstantPoolIndex();
297 case MachineOperand::MO_ExternalSymbol:
298 // Computing the address of an external symbol, not calling it.
299 if (TM.getRelocationModel() != Reloc::Static) {
300 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
301 GVStubs.insert(Name);
302 O << "L" << Name << "$non_lazy_ptr";
305 O << TAI->getGlobalPrefix() << MO.getSymbolName();
307 case MachineOperand::MO_GlobalAddress: {
308 // Computing the address of a global symbol, not calling it.
309 GlobalValue *GV = MO.getGlobal();
310 std::string Name = Mang->getValueName(GV);
311 int offset = MO.getOffset();
313 // External or weakly linked global variables need non-lazily-resolved stubs
314 if (TM.getRelocationModel() != Reloc::Static) {
315 if (((GV->isExternal() || GV->hasWeakLinkage() ||
316 GV->hasLinkOnceLinkage()))) {
317 GVStubs.insert(Name);
318 O << "L" << Name << "$non_lazy_ptr";
328 O << "<unknown operand type: " << MO.getType() << ">";
333 /// PrintAsmOperand - Print out an operand for an inline asm expression.
335 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
337 const char *ExtraCode) {
338 // Does this asm operand have a single letter operand modifier?
339 if (ExtraCode && ExtraCode[0]) {
340 if (ExtraCode[1] != 0) return true; // Unknown modifier.
342 switch (ExtraCode[0]) {
343 default: return true; // Unknown modifier.
344 case 'L': // Write second word of DImode reference.
345 // Verify that this operand has two consecutive registers.
346 if (!MI->getOperand(OpNo).isRegister() ||
347 OpNo+1 == MI->getNumOperands() ||
348 !MI->getOperand(OpNo+1).isRegister())
350 ++OpNo; // Return the high-part.
355 printOperand(MI, OpNo);
359 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
361 const char *ExtraCode) {
362 if (ExtraCode && ExtraCode[0])
363 return true; // Unknown modifier.
364 printMemRegReg(MI, OpNo);
368 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
369 /// the current output stream.
371 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
374 // Check for slwi/srwi mnemonics.
375 if (MI->getOpcode() == PPC::RLWINM) {
376 bool FoundMnemonic = false;
377 unsigned char SH = MI->getOperand(2).getImmedValue();
378 unsigned char MB = MI->getOperand(3).getImmedValue();
379 unsigned char ME = MI->getOperand(4).getImmedValue();
380 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
381 O << "slwi "; FoundMnemonic = true;
383 if (SH <= 31 && MB == (32-SH) && ME == 31) {
384 O << "srwi "; FoundMnemonic = true;
391 O << ", " << (unsigned int)SH << "\n";
394 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
395 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
405 if (printInstruction(MI))
406 return; // Printer was automatically generated
408 assert(0 && "Unhandled instruction in asm writer!");
415 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
416 switch (F.getLinkage()) {
417 default: assert(0 && "Unknown linkage type!");
418 case Function::ExternalLinkage:
419 case Function::InternalLinkage: return TAI->getTextSection();
420 case Function::WeakLinkage:
421 case Function::LinkOnceLinkage:
422 return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
426 /// runOnMachineFunction - This uses the printMachineInstruction()
427 /// method to print assembly for each instruction.
429 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
430 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
432 SetupMachineFunction(MF);
435 // Print out constants referenced by the function
436 EmitConstantPool(MF.getConstantPool());
438 // Print out labels for the function.
439 const Function *F = MF.getFunction();
440 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
442 switch (F->getLinkage()) {
443 default: assert(0 && "Unknown linkage type!");
444 case Function::InternalLinkage: // Symbols default to internal.
446 case Function::ExternalLinkage:
447 O << "\t.globl\t" << CurrentFnName << "\n";
449 case Function::WeakLinkage:
450 case Function::LinkOnceLinkage:
451 O << "\t.globl\t" << CurrentFnName << "\n";
452 O << "\t.weak_definition\t" << CurrentFnName << "\n";
456 O << CurrentFnName << ":\n";
458 // Emit pre-function debug information.
459 DW.BeginFunction(&MF);
461 // Print out code for the function.
462 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
464 // Print a label for the basic block.
465 if (I != MF.begin()) {
466 printBasicBlockLabel(I, true);
469 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
471 // Print the assembly for the instruction.
473 printMachineInstruction(II);
477 // Print out jump tables referenced by the function.
478 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
480 // Emit post-function debug information.
483 // We didn't modify anything.
488 bool DarwinAsmPrinter::doInitialization(Module &M) {
489 if (Subtarget.isGigaProcessor())
490 O << "\t.machine ppc970\n";
491 AsmPrinter::doInitialization(M);
493 // Darwin wants symbols to be quoted if they have complex names.
494 Mang->setUseQuotes(true);
496 // Emit initial debug information.
501 bool DarwinAsmPrinter::doFinalization(Module &M) {
502 const TargetData *TD = TM.getTargetData();
504 // Print out module-level global variables here.
505 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
507 if (!I->hasInitializer()) continue; // External global require no code
509 // Check to see if this is a special global used by LLVM, if so, emit it.
510 if (EmitSpecialLLVMGlobal(I))
513 std::string name = Mang->getValueName(I);
514 Constant *C = I->getInitializer();
515 unsigned Size = TD->getTypeSize(C->getType());
516 unsigned Align = TD->getPreferredAlignmentLog(I);
518 if (C->isNullValue() && /* FIXME: Verify correct */
519 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
520 I->hasLinkOnceLinkage() ||
521 (I->hasExternalLinkage() && !I->hasSection()))) {
522 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
523 if (I->hasExternalLinkage()) {
524 O << "\t.globl " << name << '\n';
525 O << "\t.zerofill __DATA, __common, " << name << ", "
526 << Size << ", " << Align;
527 } else if (I->hasInternalLinkage()) {
528 SwitchToDataSection("\t.data", I);
529 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
531 SwitchToDataSection("\t.data", I);
532 O << ".comm " << name << "," << Size;
534 O << "\t\t; '" << I->getName() << "'\n";
536 switch (I->getLinkage()) {
537 case GlobalValue::LinkOnceLinkage:
538 case GlobalValue::WeakLinkage:
539 O << "\t.globl " << name << '\n'
540 << "\t.weak_definition " << name << '\n';
541 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
543 case GlobalValue::AppendingLinkage:
544 // FIXME: appending linkage variables should go into a section of
545 // their name or something. For now, just emit them as external.
546 case GlobalValue::ExternalLinkage:
547 // If external or appending, declare as a global symbol
548 O << "\t.globl " << name << "\n";
550 case GlobalValue::InternalLinkage:
551 if (I->isConstant()) {
552 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
553 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
554 SwitchToDataSection(TAI->getCStringSection(), I);
559 SwitchToDataSection("\t.data", I);
562 std::cerr << "Unknown linkage type!";
566 EmitAlignment(Align, I);
567 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
568 EmitGlobalConstant(C);
573 bool isPPC64 = TD->getPointerSizeInBits() == 64;
575 // Output stubs for dynamically-linked functions
576 if (TM.getRelocationModel() == Reloc::PIC_) {
577 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
579 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
580 "pure_instructions,32");
582 O << "L" << *i << "$stub:\n";
583 O << "\t.indirect_symbol " << *i << "\n";
585 O << "\tbcl 20,31,L0$" << *i << "\n";
586 O << "L0$" << *i << ":\n";
588 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
591 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
593 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
594 O << "\tmtctr r12\n";
596 SwitchToDataSection(".lazy_symbol_pointer");
597 O << "L" << *i << "$lazy_ptr:\n";
598 O << "\t.indirect_symbol " << *i << "\n";
600 O << "\t.quad dyld_stub_binding_helper\n";
602 O << "\t.long dyld_stub_binding_helper\n";
605 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
607 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
608 "pure_instructions,16");
610 O << "L" << *i << "$stub:\n";
611 O << "\t.indirect_symbol " << *i << "\n";
612 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
614 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
616 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
617 O << "\tmtctr r12\n";
619 SwitchToDataSection(".lazy_symbol_pointer");
620 O << "L" << *i << "$lazy_ptr:\n";
621 O << "\t.indirect_symbol " << *i << "\n";
623 O << "\t.quad dyld_stub_binding_helper\n";
625 O << "\t.long dyld_stub_binding_helper\n";
631 // Output stubs for external and common global variables.
632 if (GVStubs.begin() != GVStubs.end()) {
633 SwitchToDataSection(".non_lazy_symbol_pointer");
634 for (std::set<std::string>::iterator I = GVStubs.begin(),
635 E = GVStubs.end(); I != E; ++I) {
636 O << "L" << *I << "$non_lazy_ptr:\n";
637 O << "\t.indirect_symbol " << *I << "\n";
646 // Emit initial debug information.
649 // Funny Darwin hack: This flag tells the linker that no global symbols
650 // contain code that falls through to other global symbols (e.g. the obvious
651 // implementation of multiple entry points). If this doesn't occur, the
652 // linker can safely perform dead code stripping. Since LLVM never generates
653 // code that does this, it is always safe to set.
654 O << "\t.subsections_via_symbols\n";
656 AsmPrinter::doFinalization(M);
657 return false; // success
662 /// createDarwinCodePrinterPass - Returns a pass that prints the PPC assembly
663 /// code for a MachineFunction to the given output stream, in a format that the
664 /// Darwin assembler can deal with.
666 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
667 PPCTargetMachine &tm) {
668 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());