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/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/StringExtras.h"
43 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
45 class PPCAsmPrinter : public AsmPrinter {
47 std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
49 PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
50 : AsmPrinter(O, TM) {}
52 virtual const char *getPassName() const {
53 return "PowerPC Assembly Printer";
56 PPCTargetMachine &getTM() {
57 return static_cast<PPCTargetMachine&>(TM);
60 unsigned enumRegToMachineReg(unsigned enumReg) {
62 default: assert(0 && "Unhandled register!"); break;
63 case PPC::CR0: return 0;
64 case PPC::CR1: return 1;
65 case PPC::CR2: return 2;
66 case PPC::CR3: return 3;
67 case PPC::CR4: return 4;
68 case PPC::CR5: return 5;
69 case PPC::CR6: return 6;
70 case PPC::CR7: return 7;
75 /// printInstruction - This method is automatically generated by tablegen
76 /// from the instruction set description. This method returns true if the
77 /// machine instruction was sufficiently described to print it, otherwise it
79 bool printInstruction(const MachineInstr *MI);
81 void printMachineInstruction(const MachineInstr *MI);
82 void printOp(const MachineOperand &MO);
84 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
85 const MachineOperand &MO = MI->getOperand(OpNo);
86 if (MO.getType() == MachineOperand::MO_MachineRegister) {
87 assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
88 O << TM.getRegisterInfo()->get(MO.getReg()).Name;
89 } else if (MO.isImmediate()) {
90 O << MO.getImmedValue();
96 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
98 unsigned char value = MI->getOperand(OpNo).getImmedValue();
99 assert(value <= 31 && "Invalid u5imm argument!");
100 O << (unsigned int)value;
102 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
104 unsigned char value = MI->getOperand(OpNo).getImmedValue();
105 assert(value <= 63 && "Invalid u6imm argument!");
106 O << (unsigned int)value;
108 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
110 O << (short)MI->getOperand(OpNo).getImmedValue();
112 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
114 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
116 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
118 O << (short)MI->getOperand(OpNo).getImmedValue()*4;
120 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
122 // Branches can take an immediate operand. This is used by the branch
123 // selection pass to print $+8, an eight byte displacement from the PC.
124 if (MI->getOperand(OpNo).isImmediate()) {
125 O << "$+" << MI->getOperand(OpNo).getImmedValue();
127 printOp(MI->getOperand(OpNo));
130 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
132 const MachineOperand &MO = MI->getOperand(OpNo);
133 if (!PPCGenerateStaticCode) {
134 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
135 std::string Name(GlobalPrefix); Name += MO.getSymbolName();
136 FnStubs.insert(Name);
137 O << "L" << Name << "$stub";
139 } else if (MO.getType() == MachineOperand::MO_GlobalAddress &&
140 isa<Function>(MO.getGlobal()) &&
141 cast<Function>(MO.getGlobal())->isExternal()) {
142 // Dynamically-resolved functions need a stub for the function.
143 std::string Name = Mang->getValueName(MO.getGlobal());
144 FnStubs.insert(Name);
145 O << "L" << Name << "$stub";
150 printOp(MI->getOperand(OpNo));
152 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
154 O << (int)MI->getOperand(OpNo).getImmedValue()*4;
156 void printPICLabel(const MachineInstr *MI, unsigned OpNo,
158 // FIXME: should probably be converted to cout.width and cout.fill
159 O << "\"L0000" << getFunctionNumber() << "$pb\"\n";
160 O << "\"L0000" << getFunctionNumber() << "$pb\":";
162 void printSymbolHi(const MachineInstr *MI, unsigned OpNo,
164 if (MI->getOperand(OpNo).isImmediate()) {
165 printS16ImmOperand(MI, OpNo, VT);
168 printOp(MI->getOperand(OpNo));
170 O << "-\"L0000" << getFunctionNumber() << "$pb\")";
175 void printSymbolLo(const MachineInstr *MI, unsigned OpNo,
177 if (MI->getOperand(OpNo).isImmediate()) {
178 printS16ImmOperand(MI, OpNo, VT);
181 printOp(MI->getOperand(OpNo));
183 O << "-\"L0000" << getFunctionNumber() << "$pb\")";
188 void printcrbitm(const MachineInstr *MI, unsigned OpNo,
190 unsigned CCReg = MI->getOperand(OpNo).getReg();
191 unsigned RegNo = enumRegToMachineReg(CCReg);
192 O << (0x80 >> RegNo);
195 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
196 virtual bool doFinalization(Module &M) = 0;
199 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
202 struct DarwinAsmPrinter : public PPCAsmPrinter {
204 DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
205 : PPCAsmPrinter(O, TM) {
208 PrivateGlobalPrefix = "L"; // Marker for constant pool idxs
209 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
210 Data64bitsDirective = 0; // we can't emit a 64-bit unit
211 AlignmentIsInBytes = false; // Alignment is by power of 2.
212 ConstantPoolSection = "\t.const\t";
215 virtual const char *getPassName() const {
216 return "Darwin PPC Assembly Printer";
219 bool runOnMachineFunction(MachineFunction &F);
220 bool doInitialization(Module &M);
221 bool doFinalization(Module &M);
224 /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
226 struct AIXAsmPrinter : public PPCAsmPrinter {
227 /// Map for labels corresponding to global variables
229 std::map<const GlobalVariable*,std::string> GVToLabelMap;
231 AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
232 : PPCAsmPrinter(O, TM) {
235 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
236 Data64bitsDirective = 0; // we can't emit a 64-bit unit
237 AlignmentIsInBytes = false; // Alignment is by power of 2.
238 ConstantPoolSection = "\t.const\t";
241 virtual const char *getPassName() const {
242 return "AIX PPC Assembly Printer";
245 bool runOnMachineFunction(MachineFunction &F);
246 bool doInitialization(Module &M);
247 bool doFinalization(Module &M);
249 } // end of anonymous namespace
251 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
252 /// code for a MachineFunction to the given output stream, in a format that the
253 /// Darwin assembler can deal with.
255 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
256 return new DarwinAsmPrinter(o, tm);
259 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
260 /// for a MachineFunction to the given output stream, in a format that the
261 /// AIX 5L assembler can deal with.
263 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
264 return new AIXAsmPrinter(o, tm);
267 // Include the auto-generated portion of the assembly writer
268 #include "PPCGenAsmWriter.inc"
270 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
271 const MRegisterInfo &RI = *TM.getRegisterInfo();
274 switch (MO.getType()) {
275 case MachineOperand::MO_VirtualRegister:
276 if (Value *V = MO.getVRegValueOrNull()) {
277 O << "<" << V->getName() << ">";
281 case MachineOperand::MO_MachineRegister:
282 case MachineOperand::MO_CCRegister:
283 O << RI.get(MO.getReg()).Name;
286 case MachineOperand::MO_SignExtendedImmed:
287 case MachineOperand::MO_UnextendedImmed:
288 std::cerr << "printOp() does not handle immediate values\n";
292 case MachineOperand::MO_PCRelativeDisp:
293 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
297 case MachineOperand::MO_MachineBasicBlock: {
298 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
299 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << "_"
300 << MBBOp->getNumber() << "\t; " << MBBOp->getBasicBlock()->getName();
304 case MachineOperand::MO_ConstantPoolIndex:
305 O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
306 << '_' << MO.getConstantPoolIndex();
309 case MachineOperand::MO_ExternalSymbol:
310 O << GlobalPrefix << MO.getSymbolName();
313 case MachineOperand::MO_GlobalAddress: {
314 GlobalValue *GV = MO.getGlobal();
315 std::string Name = Mang->getValueName(GV);
317 // External or weakly linked global variables need non-lazily-resolved stubs
318 if (!PPCGenerateStaticCode &&
319 ((GV->isExternal() || GV->hasWeakLinkage() ||
320 GV->hasLinkOnceLinkage()))) {
321 if (GV->hasLinkOnceLinkage())
322 LinkOnceStubs.insert(Name);
324 GVStubs.insert(Name);
325 O << "L" << Name << "$non_lazy_ptr";
334 O << "<unknown operand type: " << MO.getType() << ">";
339 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
340 /// the current output stream.
342 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
345 // Check for slwi/srwi mnemonics.
346 if (MI->getOpcode() == PPC::RLWINM) {
347 bool FoundMnemonic = false;
348 unsigned char SH = MI->getOperand(2).getImmedValue();
349 unsigned char MB = MI->getOperand(3).getImmedValue();
350 unsigned char ME = MI->getOperand(4).getImmedValue();
351 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
352 O << "slwi "; FoundMnemonic = true;
354 if (SH <= 31 && MB == (32-SH) && ME == 31) {
355 O << "srwi "; FoundMnemonic = true;
359 printOperand(MI, 0, MVT::i64);
361 printOperand(MI, 1, MVT::i64);
362 O << ", " << (unsigned int)SH << "\n";
367 if (printInstruction(MI))
368 return; // Printer was automatically generated
370 assert(0 && "Unhandled instruction in asm writer!");
376 /// runOnMachineFunction - This uses the printMachineInstruction()
377 /// method to print assembly for each instruction.
379 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
380 SetupMachineFunction(MF);
383 // Print out constants referenced by the function
384 EmitConstantPool(MF.getConstantPool());
386 // Print out labels for the function.
387 const Function *F = MF.getFunction();
388 SwitchSection(".text", F);
390 if (!F->hasInternalLinkage())
391 O << "\t.globl\t" << CurrentFnName << "\n";
392 O << CurrentFnName << ":\n";
394 // Print out code for the function.
395 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
397 // Print a label for the basic block.
398 if (I != MF.begin()) {
399 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
400 << I->getNumber() << ":\t";
401 if (!I->getBasicBlock()->getName().empty())
402 O << CommentString << " " << I->getBasicBlock()->getName();
405 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
407 // Print the assembly for the instruction.
409 printMachineInstruction(II);
413 // We didn't modify anything.
418 bool DarwinAsmPrinter::doInitialization(Module &M) {
419 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
420 O << "\t.machine ppc970\n";
421 AsmPrinter::doInitialization(M);
423 // Darwin wants symbols to be quoted if they have complex names.
424 Mang->setUseQuotes(true);
428 bool DarwinAsmPrinter::doFinalization(Module &M) {
429 const TargetData &TD = TM.getTargetData();
431 // Print out module-level global variables here.
432 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
434 if (I->hasInitializer()) { // External global require no code
436 std::string name = Mang->getValueName(I);
437 Constant *C = I->getInitializer();
438 unsigned Size = TD.getTypeSize(C->getType());
439 unsigned Align = TD.getTypeAlignmentShift(C->getType());
441 if (C->isNullValue() && /* FIXME: Verify correct */
442 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
443 I->hasLinkOnceLinkage())) {
444 SwitchSection(".data", I);
445 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
446 if (I->hasInternalLinkage())
447 O << ".lcomm " << name << "," << Size << "," << Align;
449 O << ".comm " << name << "," << Size;
450 O << "\t\t; '" << I->getName() << "'\n";
452 switch (I->getLinkage()) {
453 case GlobalValue::LinkOnceLinkage:
454 SwitchSection("", 0);
455 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
456 << ".weak_definition " << name << '\n'
457 << ".private_extern " << name << '\n'
458 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
459 LinkOnceStubs.insert(name);
461 case GlobalValue::WeakLinkage:
462 O << ".weak_definition " << name << '\n'
463 << ".private_extern " << name << '\n';
465 case GlobalValue::AppendingLinkage:
466 // FIXME: appending linkage variables should go into a section of
467 // their name or something. For now, just emit them as external.
468 case GlobalValue::ExternalLinkage:
469 // If external or appending, declare as a global symbol
470 O << "\t.globl " << name << "\n";
472 case GlobalValue::InternalLinkage:
473 SwitchSection(".data", I);
476 std::cerr << "Unknown linkage type!";
480 EmitAlignment(Align, I);
481 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
482 EmitGlobalConstant(C);
486 // Output stubs for dynamically-linked functions
487 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
492 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
494 O << "L" << *i << "$stub:\n";
495 O << "\t.indirect_symbol " << *i << "\n";
497 O << "\tbcl 20,31,L0$" << *i << "\n";
498 O << "L0$" << *i << ":\n";
500 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
502 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
503 O << "\tmtctr r12\n";
506 O << ".lazy_symbol_pointer\n";
507 O << "L" << *i << "$lazy_ptr:\n";
508 O << "\t.indirect_symbol " << *i << "\n";
509 O << "\t.long dyld_stub_binding_helper\n";
511 O << "\t.section __TEXT,__symbol_stub1,symbol_stubs,pure_instructions,16\n";
513 O << "L" << *i << "$stub:\n";
514 O << "\t.indirect_symbol " << *i << "\n";
515 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
516 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
517 O << "\tmtctr r12\n";
519 O << "\t.lazy_symbol_pointer\n";
520 O << "L" << *i << "$lazy_ptr:\n";
521 O << "\t.indirect_symbol " << *i << "\n";
522 O << "\t.long dyld_stub_binding_helper\n";
528 // Output stubs for external global variables
529 if (GVStubs.begin() != GVStubs.end())
530 O << ".data\n.non_lazy_symbol_pointer\n";
531 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
533 O << "L" << *i << "$non_lazy_ptr:\n";
534 O << "\t.indirect_symbol " << *i << "\n";
538 // Output stubs for link-once variables
539 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
540 O << ".data\n.align 2\n";
541 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
542 e = LinkOnceStubs.end(); i != e; ++i) {
543 O << "L" << *i << "$non_lazy_ptr:\n"
544 << "\t.long\t" << *i << '\n';
547 // Funny Darwin hack: This flag tells the linker that no global symbols
548 // contain code that falls through to other global symbols (e.g. the obvious
549 // implementation of multiple entry points). If this doesn't occur, the
550 // linker can safely perform dead code stripping. Since LLVM never generates
551 // code that does this, it is always safe to set.
552 O << "\t.subsections_via_symbols\n";
554 AsmPrinter::doFinalization(M);
555 return false; // success
558 /// runOnMachineFunction - This uses the printMachineInstruction()
559 /// method to print assembly for each instruction.
561 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
562 SetupMachineFunction(MF);
564 // Print out constants referenced by the function
565 EmitConstantPool(MF.getConstantPool());
567 // Print out header for the function.
568 O << "\t.csect .text[PR]\n"
570 << "\t.globl " << CurrentFnName << '\n'
571 << "\t.globl ." << CurrentFnName << '\n'
572 << "\t.csect " << CurrentFnName << "[DS],3\n"
573 << CurrentFnName << ":\n"
574 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
575 << "\t.csect .text[PR]\n"
576 << '.' << CurrentFnName << ":\n";
578 // Print out code for the function.
579 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
581 // Print a label for the basic block.
582 O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
584 << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
585 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
587 // Print the assembly for the instruction.
589 printMachineInstruction(II);
593 O << "LT.." << CurrentFnName << ":\n"
595 << "\t.byte 0,0,32,65,128,0,0,0\n"
596 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
598 << "\t.byte \"" << CurrentFnName << "\"\n"
601 // We didn't modify anything.
605 bool AIXAsmPrinter::doInitialization(Module &M) {
606 SwitchSection("", 0);
607 const TargetData &TD = TM.getTargetData();
609 O << "\t.machine \"ppc64\"\n"
611 << "\t.csect .text[PR]\n";
613 // Print out module-level global variables
614 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
616 if (!I->hasInitializer())
619 std::string Name = I->getName();
620 Constant *C = I->getInitializer();
621 // N.B.: We are defaulting to writable strings
622 if (I->hasExternalLinkage()) {
623 O << "\t.globl " << Name << '\n'
624 << "\t.csect .data[RW],3\n";
626 O << "\t.csect _global.rw_c[RW],3\n";
629 EmitGlobalConstant(C);
632 // Output labels for globals
633 if (M.global_begin() != M.global_end()) O << "\t.toc\n";
634 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
636 const GlobalVariable *GV = I;
637 // Do not output labels for unused variables
638 if (GV->isExternal() && GV->use_begin() == GV->use_end())
641 IncrementFunctionNumber();
642 std::string Name = GV->getName();
643 std::string Label = "LC.." + utostr(getFunctionNumber());
644 GVToLabelMap[GV] = Label;
646 << "\t.tc " << Name << "[TC]," << Name;
647 if (GV->isExternal()) O << "[RW]";
651 AsmPrinter::doInitialization(M);
652 return false; // success
655 bool AIXAsmPrinter::doFinalization(Module &M) {
656 const TargetData &TD = TM.getTargetData();
657 // Print out module-level global variables
658 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
660 if (I->hasInitializer() || I->hasExternalLinkage())
663 std::string Name = I->getName();
664 if (I->hasInternalLinkage()) {
665 O << "\t.lcomm " << Name << ",16,_global.bss_c";
667 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
668 << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
670 O << "\t\t" << CommentString << " ";
671 WriteAsOperand(O, I, false, true, &M);
675 O << "_section_.text:\n"
676 << "\t.csect .data[RW],3\n"
677 << "\t.llong _section_.text\n";
678 AsmPrinter::doFinalization(M);
679 return false; // success