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;
244 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
246 struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
250 DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
251 const TargetAsmInfo *T)
252 : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
253 bool isPPC64 = Subtarget.isPPC64();
256 virtual const char *getPassName() const {
257 return "Darwin PPC Assembly Printer";
260 bool runOnMachineFunction(MachineFunction &F);
261 bool doInitialization(Module &M);
262 bool doFinalization(Module &M);
264 void getAnalysisUsage(AnalysisUsage &AU) const {
265 AU.setPreservesAll();
266 AU.addRequired<MachineDebugInfo>();
267 PPCAsmPrinter::getAnalysisUsage(AU);
271 } // end of anonymous namespace
273 /// createDarwinCodePrinterPass - Returns a pass that prints the PPC assembly
274 /// code for a MachineFunction to the given output stream, in a format that the
275 /// Darwin assembler can deal with.
277 FunctionPass *llvm::createDarwinCodePrinterPass(std::ostream &o,
278 PPCTargetMachine &tm) {
279 return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
282 // Include the auto-generated portion of the assembly writer
283 #include "PPCGenAsmWriter.inc"
285 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
286 switch (MO.getType()) {
287 case MachineOperand::MO_Immediate:
288 std::cerr << "printOp() does not handle immediate values\n";
292 case MachineOperand::MO_MachineBasicBlock:
293 printBasicBlockLabel(MO.getMachineBasicBlock());
295 case MachineOperand::MO_JumpTableIndex:
296 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
297 << '_' << MO.getJumpTableIndex();
298 // FIXME: PIC relocation model
300 case MachineOperand::MO_ConstantPoolIndex:
301 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
302 << '_' << MO.getConstantPoolIndex();
304 case MachineOperand::MO_ExternalSymbol:
305 // Computing the address of an external symbol, not calling it.
306 if (TM.getRelocationModel() != Reloc::Static) {
307 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
308 GVStubs.insert(Name);
309 O << "L" << Name << "$non_lazy_ptr";
312 O << TAI->getGlobalPrefix() << MO.getSymbolName();
314 case MachineOperand::MO_GlobalAddress: {
315 // Computing the address of a global symbol, not calling it.
316 GlobalValue *GV = MO.getGlobal();
317 std::string Name = Mang->getValueName(GV);
318 int offset = MO.getOffset();
320 // External or weakly linked global variables need non-lazily-resolved stubs
321 if (TM.getRelocationModel() != Reloc::Static) {
322 if (((GV->isExternal() || GV->hasWeakLinkage() ||
323 GV->hasLinkOnceLinkage()))) {
324 GVStubs.insert(Name);
325 O << "L" << Name << "$non_lazy_ptr";
335 O << "<unknown operand type: " << MO.getType() << ">";
340 /// PrintAsmOperand - Print out an operand for an inline asm expression.
342 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
344 const char *ExtraCode) {
345 // Does this asm operand have a single letter operand modifier?
346 if (ExtraCode && ExtraCode[0]) {
347 if (ExtraCode[1] != 0) return true; // Unknown modifier.
349 switch (ExtraCode[0]) {
350 default: return true; // Unknown modifier.
351 case 'L': // Write second word of DImode reference.
352 // Verify that this operand has two consecutive registers.
353 if (!MI->getOperand(OpNo).isRegister() ||
354 OpNo+1 == MI->getNumOperands() ||
355 !MI->getOperand(OpNo+1).isRegister())
357 ++OpNo; // Return the high-part.
362 printOperand(MI, OpNo);
366 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
368 const char *ExtraCode) {
369 if (ExtraCode && ExtraCode[0])
370 return true; // Unknown modifier.
371 printMemRegReg(MI, OpNo);
375 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
376 /// the current output stream.
378 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
381 // Check for slwi/srwi mnemonics.
382 if (MI->getOpcode() == PPC::RLWINM) {
383 bool FoundMnemonic = false;
384 unsigned char SH = MI->getOperand(2).getImmedValue();
385 unsigned char MB = MI->getOperand(3).getImmedValue();
386 unsigned char ME = MI->getOperand(4).getImmedValue();
387 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
388 O << "slwi "; FoundMnemonic = true;
390 if (SH <= 31 && MB == (32-SH) && ME == 31) {
391 O << "srwi "; FoundMnemonic = true;
398 O << ", " << (unsigned int)SH << "\n";
401 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
402 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
412 if (printInstruction(MI))
413 return; // Printer was automatically generated
415 assert(0 && "Unhandled instruction in asm writer!");
420 /// runOnMachineFunction - This uses the printMachineInstruction()
421 /// method to print assembly for each instruction.
423 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
424 DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
426 SetupMachineFunction(MF);
429 // Print out constants referenced by the function
430 EmitConstantPool(MF.getConstantPool());
432 // Print out jump tables referenced by the function
433 EmitJumpTableInfo(MF.getJumpTableInfo());
435 // Print out labels for the function.
436 const Function *F = MF.getFunction();
437 switch (F->getLinkage()) {
438 default: assert(0 && "Unknown linkage type!");
439 case Function::InternalLinkage: // Symbols default to internal.
440 SwitchToTextSection("\t.text", F);
442 case Function::ExternalLinkage:
443 SwitchToTextSection("\t.text", F);
444 O << "\t.globl\t" << CurrentFnName << "\n";
446 case Function::WeakLinkage:
447 case Function::LinkOnceLinkage:
449 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
450 O << "\t.globl\t" << CurrentFnName << "\n";
451 O << "\t.weak_definition\t" << CurrentFnName << "\n";
455 O << CurrentFnName << ":\n";
457 // Emit pre-function debug information.
458 DW.BeginFunction(&MF);
460 // Print out code for the function.
461 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
463 // Print a label for the basic block.
464 if (I != MF.begin()) {
465 printBasicBlockLabel(I, true);
468 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
470 // Print the assembly for the instruction.
472 printMachineInstruction(II);
476 // Emit post-function debug information.
479 // We didn't modify anything.
484 bool DarwinAsmPrinter::doInitialization(Module &M) {
485 if (Subtarget.isGigaProcessor())
486 O << "\t.machine ppc970\n";
487 AsmPrinter::doInitialization(M);
489 // Darwin wants symbols to be quoted if they have complex names.
490 Mang->setUseQuotes(true);
492 // Emit initial debug information.
497 bool DarwinAsmPrinter::doFinalization(Module &M) {
498 const TargetData *TD = TM.getTargetData();
500 // Print out module-level global variables here.
501 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
503 if (!I->hasInitializer()) continue; // External global require no code
505 // Check to see if this is a special global used by LLVM, if so, emit it.
506 if (EmitSpecialLLVMGlobal(I))
509 std::string name = Mang->getValueName(I);
510 Constant *C = I->getInitializer();
511 unsigned Size = TD->getTypeSize(C->getType());
512 unsigned Align = getPreferredAlignmentLog(I);
514 if (C->isNullValue() && /* FIXME: Verify correct */
515 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
516 I->hasLinkOnceLinkage() ||
517 (I->hasExternalLinkage() && !I->hasSection()))) {
518 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
519 if (I->hasExternalLinkage()) {
520 O << "\t.globl " << name << '\n';
521 O << "\t.zerofill __DATA, __common, " << name << ", "
522 << Size << ", " << Align;
523 } else if (I->hasInternalLinkage()) {
524 SwitchToDataSection("\t.data", I);
525 O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
527 SwitchToDataSection("\t.data", I);
528 O << ".comm " << name << "," << Size;
530 O << "\t\t; '" << I->getName() << "'\n";
532 switch (I->getLinkage()) {
533 case GlobalValue::LinkOnceLinkage:
534 case GlobalValue::WeakLinkage:
535 O << "\t.globl " << name << '\n'
536 << "\t.weak_definition " << name << '\n';
537 SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
539 case GlobalValue::AppendingLinkage:
540 // FIXME: appending linkage variables should go into a section of
541 // their name or something. For now, just emit them as external.
542 case GlobalValue::ExternalLinkage:
543 // If external or appending, declare as a global symbol
544 O << "\t.globl " << name << "\n";
546 case GlobalValue::InternalLinkage:
547 SwitchToDataSection("\t.data", I);
550 std::cerr << "Unknown linkage type!";
554 EmitAlignment(Align, I);
555 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
556 EmitGlobalConstant(C);
561 bool isPPC64 = TD->getPointerSizeInBits() == 64;
563 // Output stubs for dynamically-linked functions
564 if (TM.getRelocationModel() == Reloc::PIC_) {
565 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
567 SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
568 "pure_instructions,32", 0);
570 O << "L" << *i << "$stub:\n";
571 O << "\t.indirect_symbol " << *i << "\n";
573 O << "\tbcl 20,31,L0$" << *i << "\n";
574 O << "L0$" << *i << ":\n";
576 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
579 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
581 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
582 O << "\tmtctr r12\n";
584 SwitchToDataSection(".lazy_symbol_pointer", 0);
585 O << "L" << *i << "$lazy_ptr:\n";
586 O << "\t.indirect_symbol " << *i << "\n";
588 O << "\t.quad dyld_stub_binding_helper\n";
590 O << "\t.long dyld_stub_binding_helper\n";
593 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
595 SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
596 "pure_instructions,16", 0);
598 O << "L" << *i << "$stub:\n";
599 O << "\t.indirect_symbol " << *i << "\n";
600 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
602 O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
604 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
605 O << "\tmtctr r12\n";
607 SwitchToDataSection(".lazy_symbol_pointer", 0);
608 O << "L" << *i << "$lazy_ptr:\n";
609 O << "\t.indirect_symbol " << *i << "\n";
611 O << "\t.quad dyld_stub_binding_helper\n";
613 O << "\t.long dyld_stub_binding_helper\n";
619 // Output stubs for external and common global variables.
620 if (GVStubs.begin() != GVStubs.end()) {
621 SwitchToDataSection(".non_lazy_symbol_pointer", 0);
622 for (std::set<std::string>::iterator I = GVStubs.begin(),
623 E = GVStubs.end(); I != E; ++I) {
624 O << "L" << *I << "$non_lazy_ptr:\n";
625 O << "\t.indirect_symbol " << *I << "\n";
634 // Emit initial debug information.
637 // Funny Darwin hack: This flag tells the linker that no global symbols
638 // contain code that falls through to other global symbols (e.g. the obvious
639 // implementation of multiple entry points). If this doesn't occur, the
640 // linker can safely perform dead code stripping. Since LLVM never generates
641 // code that does this, it is always safe to set.
642 if (Subtarget.isDarwin())
643 O << "\t.subsections_via_symbols\n";
645 AsmPrinter::doFinalization(M);
646 return false; // success