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/CodeGen/TargetLoweringObjectFileImpl.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCSectionMachO.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/FormattedStream.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
57 class PPCAsmPrinter : public AsmPrinter {
59 DenseMap<const MCSymbol*, const MCSymbol*> TOC;
60 const PPCSubtarget &Subtarget;
63 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
64 MCContext &Ctx, MCStreamer &Streamer,
66 : AsmPrinter(O, TM, Ctx, Streamer, T),
67 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
69 virtual const char *getPassName() const {
70 return "PowerPC Assembly Printer";
73 PPCTargetMachine &getTM() {
74 return static_cast<PPCTargetMachine&>(TM);
77 unsigned enumRegToMachineReg(unsigned enumReg) {
79 default: llvm_unreachable("Unhandled register!");
80 case PPC::CR0: return 0;
81 case PPC::CR1: return 1;
82 case PPC::CR2: return 2;
83 case PPC::CR3: return 3;
84 case PPC::CR4: return 4;
85 case PPC::CR5: return 5;
86 case PPC::CR6: return 6;
87 case PPC::CR7: return 7;
92 /// printInstruction - This method is automatically generated by tablegen
93 /// from the instruction set description. This method returns true if the
94 /// machine instruction was sufficiently described to print it, otherwise it
96 void printInstruction(const MachineInstr *MI);
97 static const char *getRegisterName(unsigned RegNo);
100 virtual void EmitInstruction(const MachineInstr *MI);
101 void printOp(const MachineOperand &MO);
103 /// stripRegisterPrefix - This method strips the character prefix from a
104 /// register name so that only the number is left. Used by for linux asm.
105 const char *stripRegisterPrefix(const char *RegName) {
106 switch (RegName[0]) {
109 case 'v': return RegName + 1;
110 case 'c': if (RegName[1] == 'r') return RegName + 2;
116 /// printRegister - Print register according to target requirements.
118 void printRegister(const MachineOperand &MO, bool R0AsZero) {
119 unsigned RegNo = MO.getReg();
120 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
122 // If we should use 0 for R0.
123 if (R0AsZero && RegNo == PPC::R0) {
128 const char *RegName = getRegisterName(RegNo);
129 // Linux assembler (Others?) does not take register mnemonics.
130 // FIXME - What about special registers used in mfspr/mtspr?
131 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
135 void printOperand(const MachineInstr *MI, unsigned OpNo) {
136 const MachineOperand &MO = MI->getOperand(OpNo);
138 printRegister(MO, false);
139 } else if (MO.isImm()) {
146 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
147 unsigned AsmVariant, const char *ExtraCode);
148 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
149 unsigned AsmVariant, const char *ExtraCode);
152 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
153 char value = MI->getOperand(OpNo).getImm();
154 value = (value << (32-5)) >> (32-5);
157 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
158 unsigned char value = MI->getOperand(OpNo).getImm();
159 assert(value <= 31 && "Invalid u5imm argument!");
160 O << (unsigned int)value;
162 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
163 unsigned char value = MI->getOperand(OpNo).getImm();
164 assert(value <= 63 && "Invalid u6imm argument!");
165 O << (unsigned int)value;
167 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
168 O << (short)MI->getOperand(OpNo).getImm();
170 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
171 O << (unsigned short)MI->getOperand(OpNo).getImm();
173 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
174 if (MI->getOperand(OpNo).isImm()) {
175 O << (short)(MI->getOperand(OpNo).getImm()*4);
178 printOp(MI->getOperand(OpNo));
179 if (TM.getRelocationModel() == Reloc::PIC_)
180 O << "-\"L" << getFunctionNumber() << "$pb\")";
185 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
186 // Branches can take an immediate operand. This is used by the branch
187 // selection pass to print $+8, an eight byte displacement from the PC.
188 if (MI->getOperand(OpNo).isImm()) {
189 O << "$+" << MI->getOperand(OpNo).getImm()*4;
191 printOp(MI->getOperand(OpNo));
194 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
195 const MachineOperand &MO = MI->getOperand(OpNo);
196 if (TM.getRelocationModel() != Reloc::Static) {
197 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
198 GlobalValue *GV = MO.getGlobal();
199 if (GV->isDeclaration() || GV->isWeakForLinker()) {
200 // Dynamically-resolved functions need a stub for the function.
201 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
202 MachineModuleInfoImpl::StubValueTy &StubSym =
203 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
204 if (StubSym.getPointer() == 0)
205 StubSym = MachineModuleInfoImpl::
206 StubValueTy(GetGlobalValueSymbol(GV),!GV->hasInternalLinkage());
211 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
212 SmallString<128> TempNameStr;
213 TempNameStr += StringRef(MO.getSymbolName());
214 TempNameStr += StringRef("$stub");
216 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
217 MachineModuleInfoImpl::StubValueTy &StubSym =
218 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
219 if (StubSym.getPointer() == 0)
220 StubSym = MachineModuleInfoImpl::
221 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
227 printOp(MI->getOperand(OpNo));
229 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
230 O << (int)MI->getOperand(OpNo).getImm()*4;
232 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
233 O << "\"L" << getFunctionNumber() << "$pb\"\n";
234 O << "\"L" << getFunctionNumber() << "$pb\":";
236 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
237 if (MI->getOperand(OpNo).isImm()) {
238 printS16ImmOperand(MI, OpNo);
240 if (Subtarget.isDarwin()) O << "ha16(";
241 printOp(MI->getOperand(OpNo));
242 if (TM.getRelocationModel() == Reloc::PIC_)
243 O << "-\"L" << getFunctionNumber() << "$pb\"";
244 if (Subtarget.isDarwin())
250 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
251 if (MI->getOperand(OpNo).isImm()) {
252 printS16ImmOperand(MI, OpNo);
254 if (Subtarget.isDarwin()) O << "lo16(";
255 printOp(MI->getOperand(OpNo));
256 if (TM.getRelocationModel() == Reloc::PIC_)
257 O << "-\"L" << getFunctionNumber() << "$pb\"";
258 if (Subtarget.isDarwin())
264 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
265 unsigned CCReg = MI->getOperand(OpNo).getReg();
266 unsigned RegNo = enumRegToMachineReg(CCReg);
267 O << (0x80 >> RegNo);
269 // The new addressing mode printers.
270 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
271 printSymbolLo(MI, OpNo);
273 if (MI->getOperand(OpNo+1).isReg() &&
274 MI->getOperand(OpNo+1).getReg() == PPC::R0)
277 printOperand(MI, OpNo+1);
280 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
281 if (MI->getOperand(OpNo).isImm())
282 printS16X4ImmOperand(MI, OpNo);
284 printSymbolLo(MI, OpNo);
286 if (MI->getOperand(OpNo+1).isReg() &&
287 MI->getOperand(OpNo+1).getReg() == PPC::R0)
290 printOperand(MI, OpNo+1);
294 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
295 // When used as the base register, r0 reads constant zero rather than
296 // the value contained in the register. For this reason, the darwin
297 // assembler requires that we print r0 as 0 (no r) when used as the base.
298 const MachineOperand &MO = MI->getOperand(OpNo);
299 printRegister(MO, true);
301 printOperand(MI, OpNo+1);
304 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
305 const MachineOperand &MO = MI->getOperand(OpNo);
307 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
309 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
311 // Map symbol -> label of TOC entry.
312 const MCSymbol *&TOCEntry = TOC[Sym];
314 TOCEntry = OutContext.
315 GetOrCreateTemporarySymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
316 "C" + Twine(LabelID++));
318 O << *TOCEntry << "@toc";
321 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
322 const char *Modifier);
325 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
326 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
328 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
329 MCContext &Ctx, MCStreamer &Streamer,
331 : PPCAsmPrinter(O, TM, Ctx, Streamer, T) {}
333 virtual const char *getPassName() const {
334 return "Linux PPC Assembly Printer";
337 bool doFinalization(Module &M);
339 virtual void EmitFunctionEntryLabel();
341 void getAnalysisUsage(AnalysisUsage &AU) const {
342 AU.setPreservesAll();
343 AU.addRequired<MachineModuleInfo>();
344 AU.addRequired<DwarfWriter>();
345 PPCAsmPrinter::getAnalysisUsage(AU);
349 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
351 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
352 formatted_raw_ostream &OS;
354 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
355 MCContext &Ctx, MCStreamer &Streamer,
357 : PPCAsmPrinter(O, TM, Ctx, Streamer, T), OS(O) {}
359 virtual const char *getPassName() const {
360 return "Darwin PPC Assembly Printer";
363 bool doFinalization(Module &M);
364 void EmitStartOfAsmFile(Module &M);
366 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
368 void getAnalysisUsage(AnalysisUsage &AU) const {
369 AU.setPreservesAll();
370 AU.addRequired<MachineModuleInfo>();
371 AU.addRequired<DwarfWriter>();
372 PPCAsmPrinter::getAnalysisUsage(AU);
375 } // end of anonymous namespace
377 // Include the auto-generated portion of the assembly writer
378 #include "PPCGenAsmWriter.inc"
380 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
381 switch (MO.getType()) {
382 case MachineOperand::MO_Immediate:
383 llvm_unreachable("printOp() does not handle immediate values");
385 case MachineOperand::MO_MachineBasicBlock:
386 O << *MO.getMBB()->getSymbol(OutContext);
388 case MachineOperand::MO_JumpTableIndex:
389 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
390 << '_' << MO.getIndex();
391 // FIXME: PIC relocation model
393 case MachineOperand::MO_ConstantPoolIndex:
394 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
395 << '_' << MO.getIndex();
397 case MachineOperand::MO_BlockAddress:
398 O << *GetBlockAddressSymbol(MO.getBlockAddress());
400 case MachineOperand::MO_ExternalSymbol: {
401 // Computing the address of an external symbol, not calling it.
402 if (TM.getRelocationModel() == Reloc::Static) {
403 O << *GetExternalSymbolSymbol(MO.getSymbolName());
408 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
409 MO.getSymbolName()+"$non_lazy_ptr");
410 MachineModuleInfoImpl::StubValueTy &StubSym =
411 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
412 if (StubSym.getPointer() == 0)
413 StubSym = MachineModuleInfoImpl::
414 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
419 case MachineOperand::MO_GlobalAddress: {
420 // Computing the address of a global symbol, not calling it.
421 GlobalValue *GV = MO.getGlobal();
422 MCSymbol *SymToPrint;
424 // External or weakly linked global variables need non-lazily-resolved stubs
425 if (TM.getRelocationModel() != Reloc::Static &&
426 (GV->isDeclaration() || GV->isWeakForLinker())) {
427 if (!GV->hasHiddenVisibility()) {
428 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
429 MachineModuleInfoImpl::StubValueTy &StubSym =
430 MMI->getObjFileInfo<MachineModuleInfoMachO>()
431 .getGVStubEntry(SymToPrint);
432 if (StubSym.getPointer() == 0)
433 StubSym = MachineModuleInfoImpl::
434 StubValueTy(GetGlobalValueSymbol(GV), !GV->hasInternalLinkage());
435 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
436 GV->hasAvailableExternallyLinkage()) {
437 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
439 MachineModuleInfoImpl::StubValueTy &StubSym =
440 MMI->getObjFileInfo<MachineModuleInfoMachO>().
441 getHiddenGVStubEntry(SymToPrint);
442 if (StubSym.getPointer() == 0)
443 StubSym = MachineModuleInfoImpl::
444 StubValueTy(GetGlobalValueSymbol(GV),
445 !GV->hasInternalLinkage());
447 SymToPrint = GetGlobalValueSymbol(GV);
450 SymToPrint = GetGlobalValueSymbol(GV);
455 printOffset(MO.getOffset());
460 O << "<unknown operand type: " << MO.getType() << ">";
465 /// PrintAsmOperand - Print out an operand for an inline asm expression.
467 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
469 const char *ExtraCode) {
470 // Does this asm operand have a single letter operand modifier?
471 if (ExtraCode && ExtraCode[0]) {
472 if (ExtraCode[1] != 0) return true; // Unknown modifier.
474 switch (ExtraCode[0]) {
475 default: return true; // Unknown modifier.
476 case 'c': // Don't print "$" before a global var name or constant.
477 // PPC never has a prefix.
478 printOperand(MI, OpNo);
480 case 'L': // Write second word of DImode reference.
481 // Verify that this operand has two consecutive registers.
482 if (!MI->getOperand(OpNo).isReg() ||
483 OpNo+1 == MI->getNumOperands() ||
484 !MI->getOperand(OpNo+1).isReg())
486 ++OpNo; // Return the high-part.
489 // Write 'i' if an integer constant, otherwise nothing. Used to print
491 if (MI->getOperand(OpNo).isImm())
497 printOperand(MI, OpNo);
501 // At the moment, all inline asm memory operands are a single register.
502 // In any case, the output of this routine should always be just one
503 // assembler operand.
505 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
507 const char *ExtraCode) {
508 if (ExtraCode && ExtraCode[0])
509 return true; // Unknown modifier.
510 assert (MI->getOperand(OpNo).isReg());
512 printOperand(MI, OpNo);
517 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
518 const char *Modifier) {
519 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
520 unsigned Code = MI->getOperand(OpNo).getImm();
521 if (!strcmp(Modifier, "cc")) {
522 switch ((PPC::Predicate)Code) {
523 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
524 case PPC::PRED_LT: O << "lt"; return;
525 case PPC::PRED_LE: O << "le"; return;
526 case PPC::PRED_EQ: O << "eq"; return;
527 case PPC::PRED_GE: O << "ge"; return;
528 case PPC::PRED_GT: O << "gt"; return;
529 case PPC::PRED_NE: O << "ne"; return;
530 case PPC::PRED_UN: O << "un"; return;
531 case PPC::PRED_NU: O << "nu"; return;
535 assert(!strcmp(Modifier, "reg") &&
536 "Need to specify 'cc' or 'reg' as predicate op modifier!");
537 // Don't print the register for 'always'.
538 if (Code == PPC::PRED_ALWAYS) return;
539 printOperand(MI, OpNo+1);
544 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
545 /// the current output stream.
547 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
548 // Check for slwi/srwi mnemonics.
549 if (MI->getOpcode() == PPC::RLWINM) {
550 unsigned char SH = MI->getOperand(2).getImm();
551 unsigned char MB = MI->getOperand(3).getImm();
552 unsigned char ME = MI->getOperand(4).getImm();
553 bool useSubstituteMnemonic = false;
554 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
555 O << "\tslwi "; useSubstituteMnemonic = true;
557 if (SH <= 31 && MB == (32-SH) && ME == 31) {
558 O << "\tsrwi "; useSubstituteMnemonic = true;
561 if (useSubstituteMnemonic) {
565 O << ", " << (unsigned int)SH;
566 OutStreamer.AddBlankLine();
571 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
572 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
577 OutStreamer.AddBlankLine();
581 if (MI->getOpcode() == PPC::RLDICR) {
582 unsigned char SH = MI->getOperand(2).getImm();
583 unsigned char ME = MI->getOperand(3).getImm();
584 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
590 O << ", " << (unsigned int)SH;
591 OutStreamer.AddBlankLine();
596 printInstruction(MI);
597 OutStreamer.AddBlankLine();
600 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
601 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
602 return AsmPrinter::EmitFunctionEntryLabel();
604 // Emit an official procedure descriptor.
605 // FIXME 64-bit SVR4: Use MCSection here!
606 O << "\t.section\t\".opd\",\"aw\"\n";
608 OutStreamer.EmitLabel(CurrentFnSym);
609 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
610 O << "\t.previous\n";
611 O << ".L." << *CurrentFnSym << ":\n";
615 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
616 const TargetData *TD = TM.getTargetData();
618 bool isPPC64 = TD->getPointerSizeInBits() == 64;
620 if (isPPC64 && !TOC.empty()) {
621 // FIXME 64-bit SVR4: Use MCSection here?
622 O << "\t.section\t\".toc\",\"aw\"\n";
624 // FIXME: This is nondeterminstic!
625 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
626 E = TOC.end(); I != E; ++I) {
627 O << *I->second << ":\n";
628 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
632 return AsmPrinter::doFinalization(M);
635 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
636 static const char *const CPUDirectives[] = {
648 unsigned Directive = Subtarget.getDarwinDirective();
649 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
650 Directive = PPC::DIR_970;
651 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
652 Directive = PPC::DIR_7400;
653 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
654 Directive = PPC::DIR_64;
655 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
656 O << "\t.machine " << CPUDirectives[Directive] << '\n';
658 // Prime text sections so they are adjacent. This reduces the likelihood a
659 // large data or debug section causes a branch to exceed 16M limit.
660 TargetLoweringObjectFileMachO &TLOFMacho =
661 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
662 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
663 if (TM.getRelocationModel() == Reloc::PIC_) {
664 OutStreamer.SwitchSection(
665 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
666 MCSectionMachO::S_SYMBOL_STUBS |
667 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
668 32, SectionKind::getText()));
669 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
670 OutStreamer.SwitchSection(
671 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
672 MCSectionMachO::S_SYMBOL_STUBS |
673 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
674 16, SectionKind::getText()));
676 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
679 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
680 // Remove $stub suffix, add $lazy_ptr.
681 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
682 TmpStr += "$lazy_ptr";
683 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
686 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
687 // Add $tmp suffix to $stub, yielding $stub$tmp.
688 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
690 return Ctx.GetOrCreateTemporarySymbol(TmpStr.str());
693 void PPCDarwinAsmPrinter::
694 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
695 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
697 TargetLoweringObjectFileMachO &TLOFMacho =
698 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
700 // .lazy_symbol_pointer
701 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
703 // Output stubs for dynamically-linked functions
704 if (TM.getRelocationModel() == Reloc::PIC_) {
705 const MCSection *StubSection =
706 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
707 MCSectionMachO::S_SYMBOL_STUBS |
708 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
709 32, SectionKind::getText());
710 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
711 OutStreamer.SwitchSection(StubSection);
714 const MCSymbol *Stub = Stubs[i].first;
715 const MCSymbol *RawSym = Stubs[i].second.getPointer();
716 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
717 const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
720 O << "\t.indirect_symbol " << *RawSym << '\n';
722 O << "\tbcl 20,31," << *AnonSymbol << '\n';
723 O << *AnonSymbol << ":\n";
725 O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
728 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
729 << '-' << *AnonSymbol << ")(r11)\n";
730 O << "\tmtctr r12\n";
733 OutStreamer.SwitchSection(LSPSection);
734 O << *LazyPtr << ":\n";
735 O << "\t.indirect_symbol " << *RawSym << '\n';
736 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
742 const MCSection *StubSection =
743 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
744 MCSectionMachO::S_SYMBOL_STUBS |
745 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
746 16, SectionKind::getText());
747 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
748 const MCSymbol *Stub = Stubs[i].first;
749 const MCSymbol *RawSym = Stubs[i].second.getPointer();
750 const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
752 OutStreamer.SwitchSection(StubSection);
755 O << "\t.indirect_symbol " << *RawSym << '\n';
756 O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
757 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
759 O << "\tmtctr r12\n";
761 OutStreamer.SwitchSection(LSPSection);
762 O << *LazyPtr << ":\n";
763 O << "\t.indirect_symbol " << *RawSym << '\n';
764 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
771 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
772 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
774 // Darwin/PPC always uses mach-o.
775 TargetLoweringObjectFileMachO &TLOFMacho =
776 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
777 MachineModuleInfoMachO &MMIMacho =
778 MMI->getObjFileInfo<MachineModuleInfoMachO>();
780 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
782 EmitFunctionStubs(Stubs);
784 if (MAI->doesSupportExceptionHandling() && MMI) {
785 // Add the (possibly multiple) personalities to the set of global values.
786 // Only referenced functions get into the Personalities list.
787 const std::vector<Function *> &Personalities = MMI->getPersonalities();
788 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
789 E = Personalities.end(); I != E; ++I) {
791 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
792 MachineModuleInfoImpl::StubValueTy &StubSym =
793 MMIMacho.getGVStubEntry(NLPSym);
794 StubSym = MachineModuleInfoImpl::
795 StubValueTy(GetGlobalValueSymbol(*I), true);
800 // Output stubs for dynamically-linked functions.
801 Stubs = MMIMacho.GetGVStubList();
803 // Output macho stubs for external and common global variables.
804 if (!Stubs.empty()) {
805 // Switch with ".non_lazy_symbol_pointer" directive.
806 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
807 EmitAlignment(isPPC64 ? 3 : 2);
809 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
811 OutStreamer.EmitLabel(Stubs[i].first);
812 // .indirect_symbol _foo
813 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
814 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
817 // External to current translation unit.
818 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
820 // Internal to current translation unit.
821 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
823 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
827 OutStreamer.AddBlankLine();
830 Stubs = MMIMacho.GetHiddenGVStubList();
831 if (!Stubs.empty()) {
832 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
833 EmitAlignment(isPPC64 ? 3 : 2);
835 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
837 OutStreamer.EmitLabel(Stubs[i].first);
839 OutStreamer.EmitValue(MCSymbolRefExpr::
840 Create(Stubs[i].second.getPointer(),
842 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
846 OutStreamer.AddBlankLine();
849 // Funny Darwin hack: This flag tells the linker that no global symbols
850 // contain code that falls through to other global symbols (e.g. the obvious
851 // implementation of multiple entry points). If this doesn't occur, the
852 // linker can safely perform dead code stripping. Since LLVM never generates
853 // code that does this, it is always safe to set.
854 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
856 return AsmPrinter::doFinalization(M);
859 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
860 /// for a MachineFunction to the given output stream, in a format that the
861 /// Darwin assembler can deal with.
863 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
865 MCContext &Ctx, MCStreamer &Streamer,
866 const MCAsmInfo *tai) {
867 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
869 if (Subtarget->isDarwin())
870 return new PPCDarwinAsmPrinter(o, tm, Ctx, Streamer, tai);
871 return new PPCLinuxAsmPrinter(o, tm, Ctx, Streamer, tai);
874 // Force static initialization.
875 extern "C" void LLVMInitializePowerPCAsmPrinter() {
876 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
877 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);