1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 class PPCAsmPrinter : public AsmPrinter {
61 DenseMap<const MCSymbol*, const MCSymbol*> TOC;
62 const PPCSubtarget &Subtarget;
65 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
66 const MCAsmInfo *T, bool V)
67 : AsmPrinter(O, TM, T, V),
68 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
70 virtual const char *getPassName() const {
71 return "PowerPC Assembly Printer";
74 PPCTargetMachine &getTM() {
75 return static_cast<PPCTargetMachine&>(TM);
78 unsigned enumRegToMachineReg(unsigned enumReg) {
80 default: llvm_unreachable("Unhandled register!");
81 case PPC::CR0: return 0;
82 case PPC::CR1: return 1;
83 case PPC::CR2: return 2;
84 case PPC::CR3: return 3;
85 case PPC::CR4: return 4;
86 case PPC::CR5: return 5;
87 case PPC::CR6: return 6;
88 case PPC::CR7: return 7;
93 /// printInstruction - This method is automatically generated by tablegen
94 /// from the instruction set description. This method returns true if the
95 /// machine instruction was sufficiently described to print it, otherwise it
97 void printInstruction(const MachineInstr *MI);
98 static const char *getRegisterName(unsigned RegNo);
101 void printMachineInstruction(const MachineInstr *MI);
102 void printOp(const MachineOperand &MO);
104 /// stripRegisterPrefix - This method strips the character prefix from a
105 /// register name so that only the number is left. Used by for linux asm.
106 const char *stripRegisterPrefix(const char *RegName) {
107 switch (RegName[0]) {
110 case 'v': return RegName + 1;
111 case 'c': if (RegName[1] == 'r') return RegName + 2;
117 /// printRegister - Print register according to target requirements.
119 void printRegister(const MachineOperand &MO, bool R0AsZero) {
120 unsigned RegNo = MO.getReg();
121 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
123 // If we should use 0 for R0.
124 if (R0AsZero && RegNo == PPC::R0) {
129 const char *RegName = getRegisterName(RegNo);
130 // Linux assembler (Others?) does not take register mnemonics.
131 // FIXME - What about special registers used in mfspr/mtspr?
132 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
136 void printOperand(const MachineInstr *MI, unsigned OpNo) {
137 const MachineOperand &MO = MI->getOperand(OpNo);
139 printRegister(MO, false);
140 } else if (MO.isImm()) {
147 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
148 unsigned AsmVariant, const char *ExtraCode);
149 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
150 unsigned AsmVariant, const char *ExtraCode);
153 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
154 char value = MI->getOperand(OpNo).getImm();
155 value = (value << (32-5)) >> (32-5);
158 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
159 unsigned char value = MI->getOperand(OpNo).getImm();
160 assert(value <= 31 && "Invalid u5imm argument!");
161 O << (unsigned int)value;
163 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
164 unsigned char value = MI->getOperand(OpNo).getImm();
165 assert(value <= 63 && "Invalid u6imm argument!");
166 O << (unsigned int)value;
168 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
169 O << (short)MI->getOperand(OpNo).getImm();
171 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
172 O << (unsigned short)MI->getOperand(OpNo).getImm();
174 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
175 if (MI->getOperand(OpNo).isImm()) {
176 O << (short)(MI->getOperand(OpNo).getImm()*4);
179 printOp(MI->getOperand(OpNo));
180 if (TM.getRelocationModel() == Reloc::PIC_)
181 O << "-\"L" << getFunctionNumber() << "$pb\")";
186 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
187 // Branches can take an immediate operand. This is used by the branch
188 // selection pass to print $+8, an eight byte displacement from the PC.
189 if (MI->getOperand(OpNo).isImm()) {
190 O << "$+" << MI->getOperand(OpNo).getImm()*4;
192 printOp(MI->getOperand(OpNo));
195 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
196 const MachineOperand &MO = MI->getOperand(OpNo);
197 if (TM.getRelocationModel() != Reloc::Static) {
198 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
199 GlobalValue *GV = MO.getGlobal();
200 if (GV->isDeclaration() || GV->isWeakForLinker()) {
201 // Dynamically-resolved functions need a stub for the function.
202 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
203 const MCSymbol *&StubSym =
204 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
206 StubSym = GetGlobalValueSymbol(GV);
211 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
212 SmallString<128> TempNameStr;
213 TempNameStr += StringRef(MO.getSymbolName());
214 TempNameStr += StringRef("$stub");
216 const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
217 const MCSymbol *&StubSym =
218 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
220 StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
226 printOp(MI->getOperand(OpNo));
228 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
229 O << (int)MI->getOperand(OpNo).getImm()*4;
231 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
232 O << "\"L" << getFunctionNumber() << "$pb\"\n";
233 O << "\"L" << getFunctionNumber() << "$pb\":";
235 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
236 if (MI->getOperand(OpNo).isImm()) {
237 printS16ImmOperand(MI, OpNo);
239 if (Subtarget.isDarwin()) O << "ha16(";
240 printOp(MI->getOperand(OpNo));
241 if (TM.getRelocationModel() == Reloc::PIC_)
242 O << "-\"L" << getFunctionNumber() << "$pb\"";
243 if (Subtarget.isDarwin())
249 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
250 if (MI->getOperand(OpNo).isImm()) {
251 printS16ImmOperand(MI, OpNo);
253 if (Subtarget.isDarwin()) O << "lo16(";
254 printOp(MI->getOperand(OpNo));
255 if (TM.getRelocationModel() == Reloc::PIC_)
256 O << "-\"L" << getFunctionNumber() << "$pb\"";
257 if (Subtarget.isDarwin())
263 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
264 unsigned CCReg = MI->getOperand(OpNo).getReg();
265 unsigned RegNo = enumRegToMachineReg(CCReg);
266 O << (0x80 >> RegNo);
268 // The new addressing mode printers.
269 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
270 printSymbolLo(MI, OpNo);
272 if (MI->getOperand(OpNo+1).isReg() &&
273 MI->getOperand(OpNo+1).getReg() == PPC::R0)
276 printOperand(MI, OpNo+1);
279 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
280 if (MI->getOperand(OpNo).isImm())
281 printS16X4ImmOperand(MI, OpNo);
283 printSymbolLo(MI, OpNo);
285 if (MI->getOperand(OpNo+1).isReg() &&
286 MI->getOperand(OpNo+1).getReg() == PPC::R0)
289 printOperand(MI, OpNo+1);
293 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
294 // When used as the base register, r0 reads constant zero rather than
295 // the value contained in the register. For this reason, the darwin
296 // assembler requires that we print r0 as 0 (no r) when used as the base.
297 const MachineOperand &MO = MI->getOperand(OpNo);
298 printRegister(MO, true);
300 printOperand(MI, OpNo+1);
303 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
304 const MachineOperand &MO = MI->getOperand(OpNo);
306 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
308 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
310 // Map symbol -> label of TOC entry.
311 const MCSymbol *&TOCEntry = TOC[Sym];
313 TOCEntry = OutContext.
314 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
317 O << *TOCEntry << "@toc";
320 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
321 const char *Modifier);
324 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
325 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
327 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
328 const MCAsmInfo *T, bool V)
329 : PPCAsmPrinter(O, TM, T, V){}
331 virtual const char *getPassName() const {
332 return "Linux PPC Assembly Printer";
335 bool runOnMachineFunction(MachineFunction &F);
336 bool doFinalization(Module &M);
338 virtual void EmitFunctionEntryLabel();
340 void getAnalysisUsage(AnalysisUsage &AU) const {
341 AU.setPreservesAll();
342 AU.addRequired<MachineModuleInfo>();
343 AU.addRequired<DwarfWriter>();
344 PPCAsmPrinter::getAnalysisUsage(AU);
348 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
350 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
351 formatted_raw_ostream &OS;
353 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
354 const MCAsmInfo *T, bool V)
355 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
357 virtual const char *getPassName() const {
358 return "Darwin PPC Assembly Printer";
361 bool runOnMachineFunction(MachineFunction &F);
362 bool doFinalization(Module &M);
363 void EmitStartOfAsmFile(Module &M);
365 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
367 void getAnalysisUsage(AnalysisUsage &AU) const {
368 AU.setPreservesAll();
369 AU.addRequired<MachineModuleInfo>();
370 AU.addRequired<DwarfWriter>();
371 PPCAsmPrinter::getAnalysisUsage(AU);
374 } // end of anonymous namespace
376 // Include the auto-generated portion of the assembly writer
377 #include "PPCGenAsmWriter.inc"
379 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
380 switch (MO.getType()) {
381 case MachineOperand::MO_Immediate:
382 llvm_unreachable("printOp() does not handle immediate values");
384 case MachineOperand::MO_MachineBasicBlock:
385 O << *MO.getMBB()->getSymbol(OutContext);
387 case MachineOperand::MO_JumpTableIndex:
388 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
389 << '_' << MO.getIndex();
390 // FIXME: PIC relocation model
392 case MachineOperand::MO_ConstantPoolIndex:
393 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
394 << '_' << MO.getIndex();
396 case MachineOperand::MO_BlockAddress:
397 O << *GetBlockAddressSymbol(MO.getBlockAddress());
399 case MachineOperand::MO_ExternalSymbol: {
400 // Computing the address of an external symbol, not calling it.
401 if (TM.getRelocationModel() == Reloc::Static) {
402 O << *GetExternalSymbolSymbol(MO.getSymbolName());
406 const MCSymbol *NLPSym =
407 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
408 MO.getSymbolName()+"$non_lazy_ptr");
409 const MCSymbol *&StubSym =
410 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
412 StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
417 case MachineOperand::MO_GlobalAddress: {
418 // Computing the address of a global symbol, not calling it.
419 GlobalValue *GV = MO.getGlobal();
420 MCSymbol *SymToPrint;
422 // External or weakly linked global variables need non-lazily-resolved stubs
423 if (TM.getRelocationModel() != Reloc::Static &&
424 (GV->isDeclaration() || GV->isWeakForLinker())) {
425 if (!GV->hasHiddenVisibility()) {
426 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
427 const MCSymbol *&StubSym =
428 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(SymToPrint);
430 StubSym = GetGlobalValueSymbol(GV);
431 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
432 GV->hasAvailableExternallyLinkage()) {
433 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
435 const MCSymbol *&StubSym =
436 MMI->getObjFileInfo<MachineModuleInfoMachO>().
437 getHiddenGVStubEntry(SymToPrint);
439 StubSym = GetGlobalValueSymbol(GV);
441 SymToPrint = GetGlobalValueSymbol(GV);
444 SymToPrint = GetGlobalValueSymbol(GV);
449 printOffset(MO.getOffset());
454 O << "<unknown operand type: " << MO.getType() << ">";
459 /// PrintAsmOperand - Print out an operand for an inline asm expression.
461 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
463 const char *ExtraCode) {
464 // Does this asm operand have a single letter operand modifier?
465 if (ExtraCode && ExtraCode[0]) {
466 if (ExtraCode[1] != 0) return true; // Unknown modifier.
468 switch (ExtraCode[0]) {
469 default: return true; // Unknown modifier.
470 case 'c': // Don't print "$" before a global var name or constant.
471 // PPC never has a prefix.
472 printOperand(MI, OpNo);
474 case 'L': // Write second word of DImode reference.
475 // Verify that this operand has two consecutive registers.
476 if (!MI->getOperand(OpNo).isReg() ||
477 OpNo+1 == MI->getNumOperands() ||
478 !MI->getOperand(OpNo+1).isReg())
480 ++OpNo; // Return the high-part.
483 // Write 'i' if an integer constant, otherwise nothing. Used to print
485 if (MI->getOperand(OpNo).isImm())
491 printOperand(MI, OpNo);
495 // At the moment, all inline asm memory operands are a single register.
496 // In any case, the output of this routine should always be just one
497 // assembler operand.
499 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
501 const char *ExtraCode) {
502 if (ExtraCode && ExtraCode[0])
503 return true; // Unknown modifier.
504 assert (MI->getOperand(OpNo).isReg());
506 printOperand(MI, OpNo);
511 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
512 const char *Modifier) {
513 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
514 unsigned Code = MI->getOperand(OpNo).getImm();
515 if (!strcmp(Modifier, "cc")) {
516 switch ((PPC::Predicate)Code) {
517 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
518 case PPC::PRED_LT: O << "lt"; return;
519 case PPC::PRED_LE: O << "le"; return;
520 case PPC::PRED_EQ: O << "eq"; return;
521 case PPC::PRED_GE: O << "ge"; return;
522 case PPC::PRED_GT: O << "gt"; return;
523 case PPC::PRED_NE: O << "ne"; return;
524 case PPC::PRED_UN: O << "un"; return;
525 case PPC::PRED_NU: O << "nu"; return;
529 assert(!strcmp(Modifier, "reg") &&
530 "Need to specify 'cc' or 'reg' as predicate op modifier!");
531 // Don't print the register for 'always'.
532 if (Code == PPC::PRED_ALWAYS) return;
533 printOperand(MI, OpNo+1);
538 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
539 /// the current output stream.
541 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
544 processDebugLoc(MI, true);
546 // Check for slwi/srwi mnemonics.
547 bool useSubstituteMnemonic = false;
548 if (MI->getOpcode() == PPC::RLWINM) {
549 unsigned char SH = MI->getOperand(2).getImm();
550 unsigned char MB = MI->getOperand(3).getImm();
551 unsigned char ME = MI->getOperand(4).getImm();
552 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
553 O << "\tslwi "; useSubstituteMnemonic = true;
555 if (SH <= 31 && MB == (32-SH) && ME == 31) {
556 O << "\tsrwi "; useSubstituteMnemonic = true;
559 if (useSubstituteMnemonic) {
563 O << ", " << (unsigned int)SH;
565 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
566 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
567 useSubstituteMnemonic = true;
573 } else if (MI->getOpcode() == PPC::RLDICR) {
574 unsigned char SH = MI->getOperand(2).getImm();
575 unsigned char ME = MI->getOperand(3).getImm();
576 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
578 useSubstituteMnemonic = true;
583 O << ", " << (unsigned int)SH;
587 if (!useSubstituteMnemonic)
588 printInstruction(MI);
594 processDebugLoc(MI, false);
597 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
598 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
599 return AsmPrinter::EmitFunctionEntryLabel();
601 // Emit an official procedure descriptor.
602 // FIXME 64-bit SVR4: Use MCSection here!
603 O << "\t.section\t\".opd\",\"aw\"\n";
605 OutStreamer.EmitLabel(CurrentFnSym);
606 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
607 O << "\t.previous\n";
608 O << ".L." << *CurrentFnSym << ":\n";
612 /// runOnMachineFunction - This uses the printMachineInstruction()
613 /// method to print assembly for each instruction.
615 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
616 SetupMachineFunction(MF);
619 EmitFunctionHeader();
621 // Print out code for the function.
622 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
624 // Print a label for the basic block.
625 EmitBasicBlockStart(I);
627 // Print the assembly for the instructions.
628 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
630 printMachineInstruction(II);
633 O << "\t.size\t" << *CurrentFnSym << ",.-" << *CurrentFnSym << '\n';
635 // Emit post-function debug information.
636 DW->EndFunction(&MF);
638 // Print out jump tables referenced by the function.
641 // We didn't modify anything.
645 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
646 const TargetData *TD = TM.getTargetData();
648 bool isPPC64 = TD->getPointerSizeInBits() == 64;
650 if (isPPC64 && !TOC.empty()) {
651 // FIXME 64-bit SVR4: Use MCSection here?
652 O << "\t.section\t\".toc\",\"aw\"\n";
654 // FIXME: This is nondeterminstic!
655 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
656 E = TOC.end(); I != E; ++I) {
657 O << *I->second << ":\n";
658 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
662 return AsmPrinter::doFinalization(M);
665 /// runOnMachineFunction - This uses the printMachineInstruction()
666 /// method to print assembly for each instruction.
668 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
669 SetupMachineFunction(MF);
672 EmitFunctionHeader();
674 // If the function is empty, then we need to emit *something*. Otherwise, the
675 // function's label might be associated with something that it wasn't meant to
676 // be associated with. We emit a noop in this situation.
677 MachineFunction::iterator I = MF.begin();
679 if (++I == MF.end() && MF.front().empty())
682 // Print out code for the function.
683 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
685 // Print a label for the basic block.
686 EmitBasicBlockStart(I);
687 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
689 // Print the assembly for the instruction.
690 printMachineInstruction(II);
694 // Emit post-function debug information.
695 DW->EndFunction(&MF);
697 // Print out jump tables referenced by the function.
700 // We didn't modify anything.
705 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
706 static const char *const CPUDirectives[] = {
718 unsigned Directive = Subtarget.getDarwinDirective();
719 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
720 Directive = PPC::DIR_970;
721 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
722 Directive = PPC::DIR_7400;
723 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
724 Directive = PPC::DIR_64;
725 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
726 O << "\t.machine " << CPUDirectives[Directive] << '\n';
728 // Prime text sections so they are adjacent. This reduces the likelihood a
729 // large data or debug section causes a branch to exceed 16M limit.
730 TargetLoweringObjectFileMachO &TLOFMacho =
731 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
732 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
733 if (TM.getRelocationModel() == Reloc::PIC_) {
734 OutStreamer.SwitchSection(
735 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
736 MCSectionMachO::S_SYMBOL_STUBS |
737 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
738 32, SectionKind::getText()));
739 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
740 OutStreamer.SwitchSection(
741 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
742 MCSectionMachO::S_SYMBOL_STUBS |
743 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
744 16, SectionKind::getText()));
746 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
749 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
750 // Remove $stub suffix, add $lazy_ptr.
751 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
752 TmpStr += "$lazy_ptr";
753 return Ctx.GetOrCreateSymbol(TmpStr.str());
756 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
757 // Add $tmp suffix to $stub, yielding $stub$tmp.
758 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
760 return Ctx.GetOrCreateSymbol(TmpStr.str());
763 void PPCDarwinAsmPrinter::
764 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
765 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
767 TargetLoweringObjectFileMachO &TLOFMacho =
768 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
770 // .lazy_symbol_pointer
771 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
773 // Output stubs for dynamically-linked functions
774 if (TM.getRelocationModel() == Reloc::PIC_) {
775 const MCSection *StubSection =
776 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
777 MCSectionMachO::S_SYMBOL_STUBS |
778 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
779 32, SectionKind::getText());
780 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
781 OutStreamer.SwitchSection(StubSection);
784 const MCSymbol *Stub = Stubs[i].first;
785 const MCSymbol *RawSym = Stubs[i].second;
786 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
787 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
790 O << "\t.indirect_symbol " << *RawSym << '\n';
792 O << "\tbcl 20,31," << *AnonSymbol << '\n';
793 O << *AnonSymbol << ":\n";
795 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
798 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
799 << '-' << *AnonSymbol << ")(r11)\n";
800 O << "\tmtctr r12\n";
803 OutStreamer.SwitchSection(LSPSection);
804 O << *LazyPtr << ":\n";
805 O << "\t.indirect_symbol " << *RawSym << '\n';
806 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
812 const MCSection *StubSection =
813 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
814 MCSectionMachO::S_SYMBOL_STUBS |
815 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
816 16, SectionKind::getText());
817 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
818 const MCSymbol *Stub = Stubs[i].first;
819 const MCSymbol *RawSym = Stubs[i].second;
820 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
822 OutStreamer.SwitchSection(StubSection);
825 O << "\t.indirect_symbol " << *RawSym << '\n';
826 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
827 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
829 O << "\tmtctr r12\n";
831 OutStreamer.SwitchSection(LSPSection);
832 O << *LazyPtr << ":\n";
833 O << "\t.indirect_symbol " << *RawSym << '\n';
834 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
841 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
842 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
844 // Darwin/PPC always uses mach-o.
845 TargetLoweringObjectFileMachO &TLOFMacho =
846 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
847 MachineModuleInfoMachO &MMIMacho =
848 MMI->getObjFileInfo<MachineModuleInfoMachO>();
850 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
852 EmitFunctionStubs(Stubs);
854 if (MAI->doesSupportExceptionHandling() && MMI) {
855 // Add the (possibly multiple) personalities to the set of global values.
856 // Only referenced functions get into the Personalities list.
857 const std::vector<Function *> &Personalities = MMI->getPersonalities();
858 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
859 E = Personalities.end(); I != E; ++I) {
861 const MCSymbol *NLPSym =
862 GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
863 const MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
864 StubSym = GetGlobalValueSymbol(*I);
869 // Output stubs for dynamically-linked functions.
870 Stubs = MMIMacho.GetGVStubList();
872 // Output macho stubs for external and common global variables.
873 if (!Stubs.empty()) {
874 // Switch with ".non_lazy_symbol_pointer" directive.
875 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
876 EmitAlignment(isPPC64 ? 3 : 2);
878 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
879 O << *Stubs[i].first << ":\n";
880 O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
881 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
885 Stubs = MMIMacho.GetHiddenGVStubList();
886 if (!Stubs.empty()) {
887 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
888 EmitAlignment(isPPC64 ? 3 : 2);
890 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
891 O << *Stubs[i].first << ":\n";
892 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
896 // Funny Darwin hack: This flag tells the linker that no global symbols
897 // contain code that falls through to other global symbols (e.g. the obvious
898 // implementation of multiple entry points). If this doesn't occur, the
899 // linker can safely perform dead code stripping. Since LLVM never generates
900 // code that does this, it is always safe to set.
901 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
903 return AsmPrinter::doFinalization(M);
908 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
909 /// for a MachineFunction to the given output stream, in a format that the
910 /// Darwin assembler can deal with.
912 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
914 const MCAsmInfo *tai,
916 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
918 if (Subtarget->isDarwin())
919 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
920 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
923 // Force static initialization.
924 extern "C" void LLVMInitializePowerPCAsmPrinter() {
925 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
926 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);