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/ErrorHandling.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSet.h"
51 #include "llvm/ADT/SmallString.h"
55 class PPCAsmPrinter : public AsmPrinter {
57 DenseMap<MCSymbol*, MCSymbol*> TOC;
58 const PPCSubtarget &Subtarget;
61 explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
62 : AsmPrinter(TM, Streamer),
63 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
65 virtual const char *getPassName() const {
66 return "PowerPC Assembly Printer";
69 PPCTargetMachine &getTM() {
70 return static_cast<PPCTargetMachine&>(TM);
73 unsigned enumRegToMachineReg(unsigned enumReg) {
75 default: llvm_unreachable("Unhandled register!");
76 case PPC::CR0: return 0;
77 case PPC::CR1: return 1;
78 case PPC::CR2: return 2;
79 case PPC::CR3: return 3;
80 case PPC::CR4: return 4;
81 case PPC::CR5: return 5;
82 case PPC::CR6: return 6;
83 case PPC::CR7: return 7;
88 /// printInstruction - This method is automatically generated by tablegen
89 /// from the instruction set description. This method returns true if the
90 /// machine instruction was sufficiently described to print it, otherwise it
92 void printInstruction(const MachineInstr *MI, raw_ostream &O);
93 static const char *getRegisterName(unsigned RegNo);
96 virtual void EmitInstruction(const MachineInstr *MI);
97 void printOp(const MachineOperand &MO, raw_ostream &O);
99 /// stripRegisterPrefix - This method strips the character prefix from a
100 /// register name so that only the number is left. Used by for linux asm.
101 const char *stripRegisterPrefix(const char *RegName) {
102 switch (RegName[0]) {
105 case 'v': return RegName + 1;
106 case 'c': if (RegName[1] == 'r') return RegName + 2;
112 /// printRegister - Print register according to target requirements.
114 void printRegister(const MachineOperand &MO, bool R0AsZero, raw_ostream &O){
115 unsigned RegNo = MO.getReg();
116 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
118 // If we should use 0 for R0.
119 if (R0AsZero && RegNo == PPC::R0) {
124 const char *RegName = getRegisterName(RegNo);
125 // Linux assembler (Others?) does not take register mnemonics.
126 // FIXME - What about special registers used in mfspr/mtspr?
127 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
131 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
132 const MachineOperand &MO = MI->getOperand(OpNo);
134 printRegister(MO, false, O);
135 } else if (MO.isImm()) {
142 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
143 unsigned AsmVariant, const char *ExtraCode,
145 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
146 unsigned AsmVariant, const char *ExtraCode,
150 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo,
152 char value = MI->getOperand(OpNo).getImm();
153 value = (value << (32-5)) >> (32-5);
156 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,
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,
170 O << (short)MI->getOperand(OpNo).getImm();
172 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
174 O << (unsigned short)MI->getOperand(OpNo).getImm();
176 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
178 if (MI->getOperand(OpNo).isImm()) {
179 O << (short)(MI->getOperand(OpNo).getImm()*4);
182 printOp(MI->getOperand(OpNo), O);
183 if (TM.getRelocationModel() == Reloc::PIC_)
184 O << "-\"L" << getFunctionNumber() << "$pb\")";
189 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
191 // Branches can take an immediate operand. This is used by the branch
192 // selection pass to print $+8, an eight byte displacement from the PC.
193 if (MI->getOperand(OpNo).isImm()) {
194 O << "$+" << MI->getOperand(OpNo).getImm()*4;
196 printOp(MI->getOperand(OpNo), O);
199 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
201 const MachineOperand &MO = MI->getOperand(OpNo);
202 if (TM.getRelocationModel() != Reloc::Static) {
203 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
204 GlobalValue *GV = MO.getGlobal();
205 if (GV->isDeclaration() || GV->isWeakForLinker()) {
206 // Dynamically-resolved functions need a stub for the function.
207 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
208 MachineModuleInfoImpl::StubValueTy &StubSym =
209 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
210 if (StubSym.getPointer() == 0)
211 StubSym = MachineModuleInfoImpl::
212 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
217 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
218 SmallString<128> TempNameStr;
219 TempNameStr += StringRef(MO.getSymbolName());
220 TempNameStr += StringRef("$stub");
222 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
223 MachineModuleInfoImpl::StubValueTy &StubSym =
224 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
225 if (StubSym.getPointer() == 0)
226 StubSym = MachineModuleInfoImpl::
227 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
233 printOp(MI->getOperand(OpNo), O);
235 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
237 O << (int)MI->getOperand(OpNo).getImm()*4;
239 void printPICLabel(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
240 O << "\"L" << getFunctionNumber() << "$pb\"\n";
241 O << "\"L" << getFunctionNumber() << "$pb\":";
243 void printSymbolHi(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
244 if (MI->getOperand(OpNo).isImm()) {
245 printS16ImmOperand(MI, OpNo, O);
247 if (Subtarget.isDarwin()) O << "ha16(";
248 printOp(MI->getOperand(OpNo), O);
249 if (TM.getRelocationModel() == Reloc::PIC_)
250 O << "-\"L" << getFunctionNumber() << "$pb\"";
251 if (Subtarget.isDarwin())
257 void printSymbolLo(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
258 if (MI->getOperand(OpNo).isImm()) {
259 printS16ImmOperand(MI, OpNo, O);
261 if (Subtarget.isDarwin()) O << "lo16(";
262 printOp(MI->getOperand(OpNo), O);
263 if (TM.getRelocationModel() == Reloc::PIC_)
264 O << "-\"L" << getFunctionNumber() << "$pb\"";
265 if (Subtarget.isDarwin())
271 void printcrbitm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
272 unsigned CCReg = MI->getOperand(OpNo).getReg();
273 unsigned RegNo = enumRegToMachineReg(CCReg);
274 O << (0x80 >> RegNo);
276 // The new addressing mode printers.
277 void printMemRegImm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
278 printSymbolLo(MI, OpNo, O);
280 if (MI->getOperand(OpNo+1).isReg() &&
281 MI->getOperand(OpNo+1).getReg() == PPC::R0)
284 printOperand(MI, OpNo+1, O);
287 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo,
289 if (MI->getOperand(OpNo).isImm())
290 printS16X4ImmOperand(MI, OpNo, O);
292 printSymbolLo(MI, OpNo, O);
294 if (MI->getOperand(OpNo+1).isReg() &&
295 MI->getOperand(OpNo+1).getReg() == PPC::R0)
298 printOperand(MI, OpNo+1, O);
302 void printMemRegReg(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
303 // When used as the base register, r0 reads constant zero rather than
304 // the value contained in the register. For this reason, the darwin
305 // assembler requires that we print r0 as 0 (no r) when used as the base.
306 const MachineOperand &MO = MI->getOperand(OpNo);
307 printRegister(MO, true, O);
309 printOperand(MI, OpNo+1, O);
312 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo,
314 const MachineOperand &MO = MI->getOperand(OpNo);
315 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
316 MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
318 // Map symbol -> label of TOC entry.
319 MCSymbol *&TOCEntry = TOC[Sym];
321 TOCEntry = OutContext.
322 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
323 "C" + Twine(LabelID++));
325 O << *TOCEntry << "@toc";
328 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
329 raw_ostream &O, const char *Modifier);
332 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
333 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
335 explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
336 : PPCAsmPrinter(TM, Streamer) {}
338 virtual const char *getPassName() const {
339 return "Linux PPC Assembly Printer";
342 bool doFinalization(Module &M);
344 virtual void EmitFunctionEntryLabel();
346 void getAnalysisUsage(AnalysisUsage &AU) const {
347 AU.setPreservesAll();
348 AU.addRequired<MachineModuleInfo>();
349 AU.addRequired<DwarfWriter>();
350 PPCAsmPrinter::getAnalysisUsage(AU);
354 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
356 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
358 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
359 : PPCAsmPrinter(TM, Streamer) {}
361 virtual const char *getPassName() const {
362 return "Darwin PPC Assembly Printer";
365 bool doFinalization(Module &M);
366 void EmitStartOfAsmFile(Module &M);
368 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
370 void getAnalysisUsage(AnalysisUsage &AU) const {
371 AU.setPreservesAll();
372 AU.addRequired<MachineModuleInfo>();
373 AU.addRequired<DwarfWriter>();
374 PPCAsmPrinter::getAnalysisUsage(AU);
377 } // end of anonymous namespace
379 // Include the auto-generated portion of the assembly writer
380 #include "PPCGenAsmWriter.inc"
382 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
383 switch (MO.getType()) {
384 case MachineOperand::MO_Immediate:
385 llvm_unreachable("printOp() does not handle immediate values");
387 case MachineOperand::MO_MachineBasicBlock:
388 O << *MO.getMBB()->getSymbol();
390 case MachineOperand::MO_JumpTableIndex:
391 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
392 << '_' << MO.getIndex();
393 // FIXME: PIC relocation model
395 case MachineOperand::MO_ConstantPoolIndex:
396 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
397 << '_' << MO.getIndex();
399 case MachineOperand::MO_BlockAddress:
400 O << *GetBlockAddressSymbol(MO.getBlockAddress());
402 case MachineOperand::MO_ExternalSymbol: {
403 // Computing the address of an external symbol, not calling it.
404 if (TM.getRelocationModel() == Reloc::Static) {
405 O << *GetExternalSymbolSymbol(MO.getSymbolName());
410 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
411 MO.getSymbolName()+"$non_lazy_ptr");
412 MachineModuleInfoImpl::StubValueTy &StubSym =
413 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
414 if (StubSym.getPointer() == 0)
415 StubSym = MachineModuleInfoImpl::
416 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
421 case MachineOperand::MO_GlobalAddress: {
422 // Computing the address of a global symbol, not calling it.
423 GlobalValue *GV = MO.getGlobal();
424 MCSymbol *SymToPrint;
426 // External or weakly linked global variables need non-lazily-resolved stubs
427 if (TM.getRelocationModel() != Reloc::Static &&
428 (GV->isDeclaration() || GV->isWeakForLinker())) {
429 if (!GV->hasHiddenVisibility()) {
430 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
431 MachineModuleInfoImpl::StubValueTy &StubSym =
432 MMI->getObjFileInfo<MachineModuleInfoMachO>()
433 .getGVStubEntry(SymToPrint);
434 if (StubSym.getPointer() == 0)
435 StubSym = MachineModuleInfoImpl::
436 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
437 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
438 GV->hasAvailableExternallyLinkage()) {
439 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
441 MachineModuleInfoImpl::StubValueTy &StubSym =
442 MMI->getObjFileInfo<MachineModuleInfoMachO>().
443 getHiddenGVStubEntry(SymToPrint);
444 if (StubSym.getPointer() == 0)
445 StubSym = MachineModuleInfoImpl::
446 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
448 SymToPrint = Mang->getSymbol(GV);
451 SymToPrint = Mang->getSymbol(GV);
456 printOffset(MO.getOffset(), O);
461 O << "<unknown operand type: " << MO.getType() << ">";
466 /// PrintAsmOperand - Print out an operand for an inline asm expression.
468 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
470 const char *ExtraCode, raw_ostream &O) {
471 // Does this asm operand have a single letter operand modifier?
472 if (ExtraCode && ExtraCode[0]) {
473 if (ExtraCode[1] != 0) return true; // Unknown modifier.
475 switch (ExtraCode[0]) {
476 default: return true; // Unknown modifier.
477 case 'c': // Don't print "$" before a global var name or constant.
478 // PPC never has a prefix.
479 printOperand(MI, OpNo, O);
481 case 'L': // Write second word of DImode reference.
482 // Verify that this operand has two consecutive registers.
483 if (!MI->getOperand(OpNo).isReg() ||
484 OpNo+1 == MI->getNumOperands() ||
485 !MI->getOperand(OpNo+1).isReg())
487 ++OpNo; // Return the high-part.
490 // Write 'i' if an integer constant, otherwise nothing. Used to print
492 if (MI->getOperand(OpNo).isImm())
498 printOperand(MI, OpNo, O);
502 // At the moment, all inline asm memory operands are a single register.
503 // In any case, the output of this routine should always be just one
504 // assembler operand.
506 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
508 const char *ExtraCode,
510 if (ExtraCode && ExtraCode[0])
511 return true; // Unknown modifier.
512 assert (MI->getOperand(OpNo).isReg());
514 printOperand(MI, OpNo, O);
519 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
520 raw_ostream &O, const char *Modifier){
521 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
522 unsigned Code = MI->getOperand(OpNo).getImm();
523 if (!strcmp(Modifier, "cc")) {
524 switch ((PPC::Predicate)Code) {
525 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
526 case PPC::PRED_LT: O << "lt"; return;
527 case PPC::PRED_LE: O << "le"; return;
528 case PPC::PRED_EQ: O << "eq"; return;
529 case PPC::PRED_GE: O << "ge"; return;
530 case PPC::PRED_GT: O << "gt"; return;
531 case PPC::PRED_NE: O << "ne"; return;
532 case PPC::PRED_UN: O << "un"; return;
533 case PPC::PRED_NU: O << "nu"; return;
537 assert(!strcmp(Modifier, "reg") &&
538 "Need to specify 'cc' or 'reg' as predicate op modifier!");
539 // Don't print the register for 'always'.
540 if (Code == PPC::PRED_ALWAYS) return;
541 printOperand(MI, OpNo+1, O);
546 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
547 /// the current output stream.
549 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
550 SmallString<128> Str;
551 raw_svector_ostream O(Str);
553 // Check for slwi/srwi mnemonics.
554 if (MI->getOpcode() == PPC::RLWINM) {
555 unsigned char SH = MI->getOperand(2).getImm();
556 unsigned char MB = MI->getOperand(3).getImm();
557 unsigned char ME = MI->getOperand(4).getImm();
558 bool useSubstituteMnemonic = false;
559 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
560 O << "\tslwi "; useSubstituteMnemonic = true;
562 if (SH <= 31 && MB == (32-SH) && ME == 31) {
563 O << "\tsrwi "; useSubstituteMnemonic = true;
566 if (useSubstituteMnemonic) {
567 printOperand(MI, 0, O);
569 printOperand(MI, 1, O);
570 O << ", " << (unsigned int)SH;
571 OutStreamer.EmitRawText(O.str());
576 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
577 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
579 printOperand(MI, 0, O);
581 printOperand(MI, 1, O);
582 OutStreamer.EmitRawText(O.str());
586 if (MI->getOpcode() == PPC::RLDICR) {
587 unsigned char SH = MI->getOperand(2).getImm();
588 unsigned char ME = MI->getOperand(3).getImm();
589 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
592 printOperand(MI, 0, O);
594 printOperand(MI, 1, O);
595 O << ", " << (unsigned int)SH;
596 OutStreamer.EmitRawText(O.str());
601 printInstruction(MI, O);
602 OutStreamer.EmitRawText(O.str());
605 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
606 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
607 return AsmPrinter::EmitFunctionEntryLabel();
609 // Emit an official procedure descriptor.
610 // FIXME 64-bit SVR4: Use MCSection here!
611 OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
612 OutStreamer.EmitRawText(StringRef("\t.align 3"));
613 OutStreamer.EmitLabel(CurrentFnSym);
614 OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
616 OutStreamer.EmitRawText(StringRef("\t.previous"));
617 OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
621 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
622 const TargetData *TD = TM.getTargetData();
624 bool isPPC64 = TD->getPointerSizeInBits() == 64;
626 if (isPPC64 && !TOC.empty()) {
627 // FIXME 64-bit SVR4: Use MCSection here?
628 OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
630 // FIXME: This is nondeterminstic!
631 for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
632 E = TOC.end(); I != E; ++I) {
633 OutStreamer.EmitLabel(I->second);
634 OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
635 "[TC]," + I->first->getName());
639 return AsmPrinter::doFinalization(M);
642 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
643 static const char *const CPUDirectives[] = {
655 unsigned Directive = Subtarget.getDarwinDirective();
656 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
657 Directive = PPC::DIR_970;
658 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
659 Directive = PPC::DIR_7400;
660 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
661 Directive = PPC::DIR_64;
662 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
663 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
665 // Prime text sections so they are adjacent. This reduces the likelihood a
666 // large data or debug section causes a branch to exceed 16M limit.
667 TargetLoweringObjectFileMachO &TLOFMacho =
668 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
669 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
670 if (TM.getRelocationModel() == Reloc::PIC_) {
671 OutStreamer.SwitchSection(
672 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
673 MCSectionMachO::S_SYMBOL_STUBS |
674 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
675 32, SectionKind::getText()));
676 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
677 OutStreamer.SwitchSection(
678 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
679 MCSectionMachO::S_SYMBOL_STUBS |
680 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
681 16, SectionKind::getText()));
683 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
686 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
687 // Remove $stub suffix, add $lazy_ptr.
688 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
689 TmpStr += "$lazy_ptr";
690 return Ctx.GetOrCreateSymbol(TmpStr.str());
693 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
694 // Add $tmp suffix to $stub, yielding $stub$tmp.
695 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
697 return Ctx.GetOrCreateSymbol(TmpStr.str());
700 void PPCDarwinAsmPrinter::
701 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
702 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
704 TargetLoweringObjectFileMachO &TLOFMacho =
705 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
707 // .lazy_symbol_pointer
708 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
710 // Output stubs for dynamically-linked functions
711 if (TM.getRelocationModel() == Reloc::PIC_) {
712 const MCSection *StubSection =
713 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
714 MCSectionMachO::S_SYMBOL_STUBS |
715 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
716 32, SectionKind::getText());
717 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
718 OutStreamer.SwitchSection(StubSection);
721 MCSymbol *Stub = Stubs[i].first;
722 MCSymbol *RawSym = Stubs[i].second.getPointer();
723 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
724 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
726 OutStreamer.EmitLabel(Stub);
727 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
728 // FIXME: MCize this.
729 OutStreamer.EmitRawText(StringRef("\tmflr r0"));
730 OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
731 OutStreamer.EmitLabel(AnonSymbol);
732 OutStreamer.EmitRawText(StringRef("\tmflr r11"));
733 OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
734 "-" + AnonSymbol->getName() + ")");
735 OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
738 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
739 "-" + AnonSymbol->getName() + ")(r11)");
741 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
742 "-" + AnonSymbol->getName() + ")(r11)");
743 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
744 OutStreamer.EmitRawText(StringRef("\tbctr"));
746 OutStreamer.SwitchSection(LSPSection);
747 OutStreamer.EmitLabel(LazyPtr);
748 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
751 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
753 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
755 OutStreamer.AddBlankLine();
759 const MCSection *StubSection =
760 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
761 MCSectionMachO::S_SYMBOL_STUBS |
762 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
763 16, SectionKind::getText());
764 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
765 MCSymbol *Stub = Stubs[i].first;
766 MCSymbol *RawSym = Stubs[i].second.getPointer();
767 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
769 OutStreamer.SwitchSection(StubSection);
771 OutStreamer.EmitLabel(Stub);
772 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
773 OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
775 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
778 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
780 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
781 OutStreamer.EmitRawText(StringRef("\tbctr"));
782 OutStreamer.SwitchSection(LSPSection);
783 OutStreamer.EmitLabel(LazyPtr);
784 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
787 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
789 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
792 OutStreamer.AddBlankLine();
796 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
797 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
799 // Darwin/PPC always uses mach-o.
800 TargetLoweringObjectFileMachO &TLOFMacho =
801 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
802 MachineModuleInfoMachO &MMIMacho =
803 MMI->getObjFileInfo<MachineModuleInfoMachO>();
805 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
807 EmitFunctionStubs(Stubs);
809 if (MAI->doesSupportExceptionHandling() && MMI) {
810 // Add the (possibly multiple) personalities to the set of global values.
811 // Only referenced functions get into the Personalities list.
812 const std::vector<Function *> &Personalities = MMI->getPersonalities();
813 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
814 E = Personalities.end(); I != E; ++I) {
816 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
817 MachineModuleInfoImpl::StubValueTy &StubSym =
818 MMIMacho.getGVStubEntry(NLPSym);
819 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
824 // Output stubs for dynamically-linked functions.
825 Stubs = MMIMacho.GetGVStubList();
827 // Output macho stubs for external and common global variables.
828 if (!Stubs.empty()) {
829 // Switch with ".non_lazy_symbol_pointer" directive.
830 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
831 EmitAlignment(isPPC64 ? 3 : 2);
833 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
835 OutStreamer.EmitLabel(Stubs[i].first);
836 // .indirect_symbol _foo
837 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
838 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
841 // External to current translation unit.
842 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
844 // Internal to current translation unit.
846 // When we place the LSDA into the TEXT section, the type info pointers
847 // need to be indirect and pc-rel. We accomplish this by using NLPs.
848 // However, sometimes the types are local to the file. So we need to
849 // fill in the value for the NLP in those cases.
850 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
852 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
856 OutStreamer.AddBlankLine();
859 Stubs = MMIMacho.GetHiddenGVStubList();
860 if (!Stubs.empty()) {
861 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
862 EmitAlignment(isPPC64 ? 3 : 2);
864 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
866 OutStreamer.EmitLabel(Stubs[i].first);
868 OutStreamer.EmitValue(MCSymbolRefExpr::
869 Create(Stubs[i].second.getPointer(),
871 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
875 OutStreamer.AddBlankLine();
878 // Funny Darwin hack: This flag tells the linker that no global symbols
879 // contain code that falls through to other global symbols (e.g. the obvious
880 // implementation of multiple entry points). If this doesn't occur, the
881 // linker can safely perform dead code stripping. Since LLVM never generates
882 // code that does this, it is always safe to set.
883 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
885 return AsmPrinter::doFinalization(M);
888 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
889 /// for a MachineFunction to the given output stream, in a format that the
890 /// Darwin assembler can deal with.
892 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
893 MCStreamer &Streamer) {
894 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
896 if (Subtarget->isDarwin())
897 return new PPCDarwinAsmPrinter(tm, Streamer);
898 return new PPCLinuxAsmPrinter(tm, Streamer);
901 // Force static initialization.
902 extern "C" void LLVMInitializePowerPCAsmPrinter() {
903 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
904 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);