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/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/ValueTypes.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/Target/MRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
44 Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
46 struct PPCAsmPrinter : public AsmPrinter {
47 std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
49 PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
50 : AsmPrinter(O, TM), LabelNumber(0) {}
52 /// Unique incrementer for label values for referencing Global values.
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, bool IsCallOp = false);
88 void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
89 const MachineOperand &MO = MI->getOperand(OpNo);
90 if (MO.getType() == MachineOperand::MO_MachineRegister) {
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 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
102 unsigned char value = MI->getOperand(OpNo).getImmedValue();
103 assert(value <= 31 && "Invalid u5imm argument!");
104 O << (unsigned int)value;
106 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
108 unsigned char value = MI->getOperand(OpNo).getImmedValue();
109 assert(value <= 63 && "Invalid u6imm argument!");
110 O << (unsigned int)value;
112 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
114 O << (short)MI->getOperand(OpNo).getImmedValue();
116 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
118 O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
120 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
122 O << (short)MI->getOperand(OpNo).getImmedValue()*4;
124 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
126 // Branches can take an immediate operand. This is used by the branch
127 // selection pass to print $+8, an eight byte displacement from the PC.
128 if (MI->getOperand(OpNo).isImmediate()) {
129 O << "$+" << MI->getOperand(OpNo).getImmedValue();
131 printOp(MI->getOperand(OpNo),
132 TM.getInstrInfo()->isCall(MI->getOpcode()));
135 void printPICLabel(const MachineInstr *MI, unsigned OpNo,
137 // FIXME: should probably be converted to cout.width and cout.fill
138 O << "\"L0000" << LabelNumber << "$pb\"\n";
139 O << "\"L0000" << LabelNumber << "$pb\":";
141 void printSymbolHi(const MachineInstr *MI, unsigned OpNo,
143 if (MI->getOperand(OpNo).isImmediate()) {
144 printS16ImmOperand(MI, OpNo, VT);
147 printOp(MI->getOperand(OpNo));
149 O << "-\"L0000" << LabelNumber << "$pb\")";
154 void printSymbolLo(const MachineInstr *MI, unsigned OpNo,
156 if (MI->getOperand(OpNo).isImmediate()) {
157 printS16ImmOperand(MI, OpNo, VT);
160 printOp(MI->getOperand(OpNo));
162 O << "-\"L0000" << LabelNumber << "$pb\")";
167 void printcrbitm(const MachineInstr *MI, unsigned OpNo,
169 unsigned CCReg = MI->getOperand(OpNo).getReg();
170 unsigned RegNo = enumRegToMachineReg(CCReg);
171 O << (0x80 >> RegNo);
174 virtual void printConstantPool(MachineConstantPool *MCP) = 0;
175 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
176 virtual bool doFinalization(Module &M) = 0;
179 /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
182 struct DarwinAsmPrinter : public PPCAsmPrinter {
184 DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
185 : PPCAsmPrinter(O, TM) {
188 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
189 Data64bitsDirective = 0; // we can't emit a 64-bit unit
190 AlignmentIsInBytes = false; // Alignment is by power of 2.
193 virtual const char *getPassName() const {
194 return "Darwin PPC Assembly Printer";
197 void printConstantPool(MachineConstantPool *MCP);
198 bool runOnMachineFunction(MachineFunction &F);
199 bool doInitialization(Module &M);
200 bool doFinalization(Module &M);
203 /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
205 struct AIXAsmPrinter : public PPCAsmPrinter {
206 /// Map for labels corresponding to global variables
208 std::map<const GlobalVariable*,std::string> GVToLabelMap;
210 AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
211 : PPCAsmPrinter(O, TM) {
214 ZeroDirective = "\t.space\t"; // ".space N" emits N zeros.
215 Data64bitsDirective = 0; // we can't emit a 64-bit unit
216 AlignmentIsInBytes = false; // Alignment is by power of 2.
219 virtual const char *getPassName() const {
220 return "AIX PPC Assembly Printer";
223 void printConstantPool(MachineConstantPool *MCP);
224 bool runOnMachineFunction(MachineFunction &F);
225 bool doInitialization(Module &M);
226 bool doFinalization(Module &M);
228 } // end of anonymous namespace
230 // SwitchSection - Switch to the specified section of the executable if we are
231 // not already in it!
233 static void SwitchSection(std::ostream &OS, std::string &CurSection,
234 const char *NewSection) {
235 if (CurSection != NewSection) {
236 CurSection = NewSection;
237 if (!CurSection.empty())
238 OS << "\t" << NewSection << "\n";
242 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
243 /// code for a MachineFunction to the given output stream, in a format that the
244 /// Darwin assembler can deal with.
246 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
247 return new DarwinAsmPrinter(o, tm);
250 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
251 /// for a MachineFunction to the given output stream, in a format that the
252 /// AIX 5L assembler can deal with.
254 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
255 return new AIXAsmPrinter(o, tm);
258 // Include the auto-generated portion of the assembly writer
259 #include "PPCGenAsmWriter.inc"
261 void PPCAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
262 const MRegisterInfo &RI = *TM.getRegisterInfo();
265 switch (MO.getType()) {
266 case MachineOperand::MO_VirtualRegister:
267 if (Value *V = MO.getVRegValueOrNull()) {
268 O << "<" << V->getName() << ">";
272 case MachineOperand::MO_MachineRegister:
273 case MachineOperand::MO_CCRegister:
274 O << RI.get(MO.getReg()).Name;
277 case MachineOperand::MO_SignExtendedImmed:
278 case MachineOperand::MO_UnextendedImmed:
279 std::cerr << "printOp() does not handle immediate values\n";
283 case MachineOperand::MO_PCRelativeDisp:
284 std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
288 case MachineOperand::MO_MachineBasicBlock: {
289 MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
290 O << "LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
291 << "_" << MBBOp->getNumber() << "\t; "
292 << MBBOp->getBasicBlock()->getName();
296 case MachineOperand::MO_ConstantPoolIndex:
297 O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
300 case MachineOperand::MO_ExternalSymbol:
302 std::string Name(GlobalPrefix); Name += MO.getSymbolName();
303 FnStubs.insert(Name);
304 O << "L" << Name << "$stub";
307 O << GlobalPrefix << MO.getSymbolName();
310 case MachineOperand::MO_GlobalAddress: {
311 GlobalValue *GV = MO.getGlobal();
312 std::string Name = Mang->getValueName(GV);
314 // Dynamically-resolved functions need a stub for the function. Be
315 // wary however not to output $stub for external functions whose addresses
316 // are taken. Those should be emitted as $non_lazy_ptr below.
317 Function *F = dyn_cast<Function>(GV);
318 if (F && IsCallOp && F->isExternal()) {
319 FnStubs.insert(Name);
320 O << "L" << Name << "$stub";
324 // External or weakly linked global variables need non-lazily-resolved stubs
325 if ((GV->isExternal() || GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())){
326 if (GV->hasLinkOnceLinkage())
327 LinkOnceStubs.insert(Name);
329 GVStubs.insert(Name);
330 O << "L" << Name << "$non_lazy_ptr";
334 O << Mang->getValueName(GV);
339 O << "<unknown operand type: " << MO.getType() << ">";
344 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
345 /// the current output stream.
347 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
350 // Check for slwi/srwi mnemonics.
351 if (MI->getOpcode() == PPC::RLWINM) {
352 bool FoundMnemonic = false;
353 unsigned char SH = MI->getOperand(2).getImmedValue();
354 unsigned char MB = MI->getOperand(3).getImmedValue();
355 unsigned char ME = MI->getOperand(4).getImmedValue();
356 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
357 O << "slwi "; FoundMnemonic = true;
359 if (SH <= 31 && MB == (32-SH) && ME == 31) {
360 O << "srwi "; FoundMnemonic = true;
364 printOperand(MI, 0, MVT::i64);
366 printOperand(MI, 1, MVT::i64);
367 O << ", " << (unsigned int)SH << "\n";
372 if (printInstruction(MI))
373 return; // Printer was automatically generated
375 assert(0 && "Unhandled instruction in asm writer!");
380 /// runOnMachineFunction - This uses the printMachineInstruction()
381 /// method to print assembly for each instruction.
383 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
384 setupMachineFunction(MF);
387 // Print out constants referenced by the function
388 printConstantPool(MF.getConstantPool());
390 // Print out labels for the function.
393 O << "\t.globl\t" << CurrentFnName << "\n";
394 O << CurrentFnName << ":\n";
396 // Print out code for the function.
397 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
399 // Print a label for the basic block.
400 if (I != MF.begin()) {
401 O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t";
402 if (!I->getBasicBlock()->getName().empty())
403 O << CommentString << " " << I->getBasicBlock()->getName();
406 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
408 // Print the assembly for the instruction.
410 printMachineInstruction(II);
415 // We didn't modify anything.
419 /// printConstantPool - Print to the current output stream assembly
420 /// representations of the constants in the constant pool MCP. This is
421 /// used to print out constants which have been "spilled to memory" by
422 /// the code generator.
424 void DarwinAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
425 const std::vector<Constant*> &CP = MCP->getConstants();
426 const TargetData &TD = TM.getTargetData();
428 if (CP.empty()) return;
430 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
432 // FIXME: force doubles to be naturally aligned. We should handle this
433 // more correctly in the future.
434 if (Type::DoubleTy == CP[i]->getType())
437 emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
438 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
440 emitGlobalConstant(CP[i]);
444 bool DarwinAsmPrinter::doInitialization(Module &M) {
445 if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
446 O << "\t.machine ppc970\n";
447 AsmPrinter::doInitialization(M);
451 bool DarwinAsmPrinter::doFinalization(Module &M) {
452 const TargetData &TD = TM.getTargetData();
453 std::string CurSection;
455 // Print out module-level global variables here.
456 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
457 if (I->hasInitializer()) { // External global require no code
459 std::string name = Mang->getValueName(I);
460 Constant *C = I->getInitializer();
461 unsigned Size = TD.getTypeSize(C->getType());
462 unsigned Align = TD.getTypeAlignmentShift(C->getType());
464 if (C->isNullValue() && /* FIXME: Verify correct */
465 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
466 I->hasLinkOnceLinkage())) {
467 SwitchSection(O, CurSection, ".data");
468 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
469 if (I->hasInternalLinkage())
470 O << ".lcomm " << name << "," << Size << "," << Align;
472 O << ".comm " << name << "," << Size;
473 O << "\t\t; '" << I->getName() << "'\n";
475 switch (I->getLinkage()) {
476 case GlobalValue::LinkOnceLinkage:
477 O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
478 << ".weak_definition " << name << '\n'
479 << ".private_extern " << name << '\n'
480 << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
481 LinkOnceStubs.insert(name);
483 case GlobalValue::WeakLinkage:
484 O << ".weak_definition " << name << '\n'
485 << ".private_extern " << name << '\n';
487 case GlobalValue::AppendingLinkage:
488 // FIXME: appending linkage variables should go into a section of
489 // their name or something. For now, just emit them as external.
490 case GlobalValue::ExternalLinkage:
491 // If external or appending, declare as a global symbol
492 O << "\t.globl " << name << "\n";
494 case GlobalValue::InternalLinkage:
495 SwitchSection(O, CurSection, ".data");
497 case GlobalValue::GhostLinkage:
498 std::cerr << "Error: unmaterialized (GhostLinkage) function in asm!";
502 emitAlignment(Align);
503 O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
504 emitGlobalConstant(C);
508 // Output stubs for dynamically-linked functions
509 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
514 O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
516 O << "L" << *i << "$stub:\n";
517 O << "\t.indirect_symbol " << *i << "\n";
519 O << "\tbcl 20,31,L0$" << *i << "\n";
520 O << "L0$" << *i << ":\n";
522 O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
524 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
525 O << "\tmtctr r12\n";
528 O << ".lazy_symbol_pointer\n";
529 O << "L" << *i << "$lazy_ptr:\n";
530 O << "\t.indirect_symbol " << *i << "\n";
531 O << "\t.long dyld_stub_binding_helper\n";
533 O << "\t.section __TEXT,__symbol_stub1,symbol_stubs,pure_instructions,16\n";
535 O << "L" << *i << "$stub:\n";
536 O << "\t.indirect_symbol " << *i << "\n";
537 O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
538 O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
539 O << "\tmtctr r12\n";
541 O << "\t.lazy_symbol_pointer\n";
542 O << "L" << *i << "$lazy_ptr:\n";
543 O << "\t.indirect_symbol " << *i << "\n";
544 O << "\t.long dyld_stub_binding_helper\n";
550 // Output stubs for external global variables
551 if (GVStubs.begin() != GVStubs.end())
552 O << ".data\n.non_lazy_symbol_pointer\n";
553 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
555 O << "L" << *i << "$non_lazy_ptr:\n";
556 O << "\t.indirect_symbol " << *i << "\n";
560 // Output stubs for link-once variables
561 if (LinkOnceStubs.begin() != LinkOnceStubs.end())
562 O << ".data\n.align 2\n";
563 for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
564 e = LinkOnceStubs.end(); i != e; ++i) {
565 O << "L" << *i << "$non_lazy_ptr:\n"
566 << "\t.long\t" << *i << '\n';
569 AsmPrinter::doFinalization(M);
570 return false; // success
573 /// runOnMachineFunction - This uses the printMachineInstruction()
574 /// method to print assembly for each instruction.
576 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
577 CurrentFnName = MF.getFunction()->getName();
579 // Print out constants referenced by the function
580 printConstantPool(MF.getConstantPool());
582 // Print out header for the function.
583 O << "\t.csect .text[PR]\n"
585 << "\t.globl " << CurrentFnName << '\n'
586 << "\t.globl ." << CurrentFnName << '\n'
587 << "\t.csect " << CurrentFnName << "[DS],3\n"
588 << CurrentFnName << ":\n"
589 << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
590 << "\t.csect .text[PR]\n"
591 << '.' << CurrentFnName << ":\n";
593 // Print out code for the function.
594 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
596 // Print a label for the basic block.
597 O << "LBB" << CurrentFnName << "_" << I->getNumber() << ":\t# "
598 << I->getBasicBlock()->getName() << "\n";
599 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
601 // Print the assembly for the instruction.
603 printMachineInstruction(II);
608 O << "LT.." << CurrentFnName << ":\n"
610 << "\t.byte 0,0,32,65,128,0,0,0\n"
611 << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
613 << "\t.byte \"" << CurrentFnName << "\"\n"
616 // We didn't modify anything.
620 /// printConstantPool - Print to the current output stream assembly
621 /// representations of the constants in the constant pool MCP. This is
622 /// used to print out constants which have been "spilled to memory" by
623 /// the code generator.
625 void AIXAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
626 const std::vector<Constant*> &CP = MCP->getConstants();
627 const TargetData &TD = TM.getTargetData();
629 if (CP.empty()) return;
631 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
633 O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
635 O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
637 emitGlobalConstant(CP[i]);
641 bool AIXAsmPrinter::doInitialization(Module &M) {
642 const TargetData &TD = TM.getTargetData();
643 std::string CurSection;
645 O << "\t.machine \"ppc64\"\n"
647 << "\t.csect .text[PR]\n";
649 // Print out module-level global variables
650 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
652 if (!I->hasInitializer())
655 std::string Name = I->getName();
656 Constant *C = I->getInitializer();
657 // N.B.: We are defaulting to writable strings
658 if (I->hasExternalLinkage()) {
659 O << "\t.globl " << Name << '\n'
660 << "\t.csect .data[RW],3\n";
662 O << "\t.csect _global.rw_c[RW],3\n";
665 emitGlobalConstant(C);
668 // Output labels for globals
669 if (M.global_begin() != M.global_end()) O << "\t.toc\n";
670 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
672 const GlobalVariable *GV = I;
673 // Do not output labels for unused variables
674 if (GV->isExternal() && GV->use_begin() == GV->use_end())
677 std::string Name = GV->getName();
678 std::string Label = "LC.." + utostr(LabelNumber++);
679 GVToLabelMap[GV] = Label;
681 << "\t.tc " << Name << "[TC]," << Name;
682 if (GV->isExternal()) O << "[RW]";
686 Mang = new Mangler(M, ".");
687 return false; // success
690 bool AIXAsmPrinter::doFinalization(Module &M) {
691 const TargetData &TD = TM.getTargetData();
692 // Print out module-level global variables
693 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
695 if (I->hasInitializer() || I->hasExternalLinkage())
698 std::string Name = I->getName();
699 if (I->hasInternalLinkage()) {
700 O << "\t.lcomm " << Name << ",16,_global.bss_c";
702 O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
703 << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
706 WriteAsOperand(O, I, false, true, &M);
710 O << "_section_.text:\n"
711 << "\t.csect .data[RW],3\n"
712 << "\t.llong _section_.text\n";
715 return false; // success