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/Analysis/DebugInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Module.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.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/Debug.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/ADT/StringSet.h"
52 #include "llvm/ADT/SmallString.h"
56 class PPCAsmPrinter : public AsmPrinter {
58 DenseMap<MCSymbol*, MCSymbol*> TOC;
59 const PPCSubtarget &Subtarget;
62 explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
63 : AsmPrinter(TM, Streamer),
64 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
66 virtual const char *getPassName() const {
67 return "PowerPC Assembly Printer";
70 PPCTargetMachine &getTM() {
71 return static_cast<PPCTargetMachine&>(TM);
74 unsigned enumRegToMachineReg(unsigned enumReg) {
76 default: llvm_unreachable("Unhandled register!");
77 case PPC::CR0: return 0;
78 case PPC::CR1: return 1;
79 case PPC::CR2: return 2;
80 case PPC::CR3: return 3;
81 case PPC::CR4: return 4;
82 case PPC::CR5: return 5;
83 case PPC::CR6: return 6;
84 case PPC::CR7: return 7;
89 /// printInstruction - This method is automatically generated by tablegen
90 /// from the instruction set description. This method returns true if the
91 /// machine instruction was sufficiently described to print it, otherwise it
93 void printInstruction(const MachineInstr *MI, raw_ostream &O);
94 static const char *getRegisterName(unsigned RegNo);
97 virtual void EmitInstruction(const MachineInstr *MI);
98 void printOp(const MachineOperand &MO, raw_ostream &O);
100 /// stripRegisterPrefix - This method strips the character prefix from a
101 /// register name so that only the number is left. Used by for linux asm.
102 const char *stripRegisterPrefix(const char *RegName) {
103 switch (RegName[0]) {
106 case 'v': return RegName + 1;
107 case 'c': if (RegName[1] == 'r') return RegName + 2;
113 /// printRegister - Print register according to target requirements.
115 void printRegister(const MachineOperand &MO, bool R0AsZero, raw_ostream &O){
116 unsigned RegNo = MO.getReg();
117 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
119 // If we should use 0 for R0.
120 if (R0AsZero && RegNo == PPC::R0) {
125 const char *RegName = getRegisterName(RegNo);
126 // Linux assembler (Others?) does not take register mnemonics.
127 // FIXME - What about special registers used in mfspr/mtspr?
128 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
132 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
133 const MachineOperand &MO = MI->getOperand(OpNo);
135 printRegister(MO, false, O);
136 } else if (MO.isImm()) {
143 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
144 unsigned AsmVariant, const char *ExtraCode,
146 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
147 unsigned AsmVariant, const char *ExtraCode,
151 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,
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,
165 unsigned char value = MI->getOperand(OpNo).getImm();
166 assert(value <= 63 && "Invalid u6imm argument!");
167 O << (unsigned int)value;
169 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
171 O << (short)MI->getOperand(OpNo).getImm();
173 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
175 O << (unsigned short)MI->getOperand(OpNo).getImm();
177 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
179 if (MI->getOperand(OpNo).isImm()) {
180 O << (short)(MI->getOperand(OpNo).getImm()*4);
183 printOp(MI->getOperand(OpNo), O);
184 if (TM.getRelocationModel() == Reloc::PIC_)
185 O << "-\"L" << getFunctionNumber() << "$pb\")";
190 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
192 // Branches can take an immediate operand. This is used by the branch
193 // selection pass to print $+8, an eight byte displacement from the PC.
194 if (MI->getOperand(OpNo).isImm()) {
195 O << "$+" << MI->getOperand(OpNo).getImm()*4;
197 printOp(MI->getOperand(OpNo), O);
200 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
202 const MachineOperand &MO = MI->getOperand(OpNo);
203 if (TM.getRelocationModel() != Reloc::Static) {
205 const GlobalValue *GV = MO.getGlobal();
206 if (GV->isDeclaration() || GV->isWeakForLinker()) {
207 // Dynamically-resolved functions need a stub for the function.
208 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
209 MachineModuleInfoImpl::StubValueTy &StubSym =
210 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
211 if (StubSym.getPointer() == 0)
212 StubSym = MachineModuleInfoImpl::
213 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
219 SmallString<128> TempNameStr;
220 TempNameStr += StringRef(MO.getSymbolName());
221 TempNameStr += StringRef("$stub");
223 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
224 MachineModuleInfoImpl::StubValueTy &StubSym =
225 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
226 if (StubSym.getPointer() == 0)
227 StubSym = MachineModuleInfoImpl::
228 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
234 printOp(MI->getOperand(OpNo), O);
236 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
238 O << (int)MI->getOperand(OpNo).getImm()*4;
240 void printPICLabel(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
241 O << "\"L" << getFunctionNumber() << "$pb\"\n";
242 O << "\"L" << getFunctionNumber() << "$pb\":";
244 void printSymbolHi(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
245 if (MI->getOperand(OpNo).isImm()) {
246 printS16ImmOperand(MI, OpNo, O);
248 if (Subtarget.isDarwin()) O << "ha16(";
249 printOp(MI->getOperand(OpNo), O);
250 if (TM.getRelocationModel() == Reloc::PIC_)
251 O << "-\"L" << getFunctionNumber() << "$pb\"";
252 if (Subtarget.isDarwin())
258 void printSymbolLo(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
259 if (MI->getOperand(OpNo).isImm()) {
260 printS16ImmOperand(MI, OpNo, O);
262 if (Subtarget.isDarwin()) O << "lo16(";
263 printOp(MI->getOperand(OpNo), O);
264 if (TM.getRelocationModel() == Reloc::PIC_)
265 O << "-\"L" << getFunctionNumber() << "$pb\"";
266 if (Subtarget.isDarwin())
272 void printcrbitm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
273 unsigned CCReg = MI->getOperand(OpNo).getReg();
274 unsigned RegNo = enumRegToMachineReg(CCReg);
275 O << (0x80 >> RegNo);
277 // The new addressing mode printers.
278 void printMemRegImm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
279 printSymbolLo(MI, OpNo, O);
281 if (MI->getOperand(OpNo+1).isReg() &&
282 MI->getOperand(OpNo+1).getReg() == PPC::R0)
285 printOperand(MI, OpNo+1, O);
288 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo,
290 if (MI->getOperand(OpNo).isImm())
291 printS16X4ImmOperand(MI, OpNo, O);
293 printSymbolLo(MI, OpNo, O);
295 if (MI->getOperand(OpNo+1).isReg() &&
296 MI->getOperand(OpNo+1).getReg() == PPC::R0)
299 printOperand(MI, OpNo+1, O);
303 void printMemRegReg(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
304 // When used as the base register, r0 reads constant zero rather than
305 // the value contained in the register. For this reason, the darwin
306 // assembler requires that we print r0 as 0 (no r) when used as the base.
307 const MachineOperand &MO = MI->getOperand(OpNo);
308 printRegister(MO, true, O);
310 printOperand(MI, OpNo+1, O);
313 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo,
315 const MachineOperand &MO = MI->getOperand(OpNo);
316 assert(MO.isGlobal());
317 MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
319 // Map symbol -> label of TOC entry.
320 MCSymbol *&TOCEntry = TOC[Sym];
322 TOCEntry = OutContext.
323 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
324 "C" + Twine(LabelID++));
326 O << *TOCEntry << "@toc";
329 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
330 raw_ostream &O, const char *Modifier);
332 MachineLocation getDebugValueLocation(const MachineInstr *MI) const {
334 MachineLocation Location;
335 assert (MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
336 // Frame address. Currently handles register +- offset only.
337 if (MI->getOperand(0).isReg() && MI->getOperand(2).isImm())
338 Location.set(MI->getOperand(0).getReg(), MI->getOperand(2).getImm());
340 DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
346 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
347 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
349 explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
350 : PPCAsmPrinter(TM, Streamer) {}
352 virtual const char *getPassName() const {
353 return "Linux PPC Assembly Printer";
356 bool doFinalization(Module &M);
358 virtual void EmitFunctionEntryLabel();
361 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
363 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
365 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
366 : PPCAsmPrinter(TM, Streamer) {}
368 virtual const char *getPassName() const {
369 return "Darwin PPC Assembly Printer";
372 bool doFinalization(Module &M);
373 void EmitStartOfAsmFile(Module &M);
375 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
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 const 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 if (MI->getOpcode() == TargetOpcode::DBG_VALUE) {
554 unsigned NOps = MI->getNumOperands();
556 O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
557 // cast away const; DIetc do not take const operands for some reason.
558 DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
561 // Frame address. Currently handles register +- offset only.
562 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
563 O << '['; printOperand(MI, 0, O); O << '+'; printOperand(MI, 1, O);
566 printOperand(MI, NOps-2, O);
567 OutStreamer.EmitRawText(O.str());
570 // Check for slwi/srwi mnemonics.
571 if (MI->getOpcode() == PPC::RLWINM) {
572 unsigned char SH = MI->getOperand(2).getImm();
573 unsigned char MB = MI->getOperand(3).getImm();
574 unsigned char ME = MI->getOperand(4).getImm();
575 bool useSubstituteMnemonic = false;
576 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
577 O << "\tslwi "; useSubstituteMnemonic = true;
579 if (SH <= 31 && MB == (32-SH) && ME == 31) {
580 O << "\tsrwi "; useSubstituteMnemonic = true;
583 if (useSubstituteMnemonic) {
584 printOperand(MI, 0, O);
586 printOperand(MI, 1, O);
587 O << ", " << (unsigned int)SH;
588 OutStreamer.EmitRawText(O.str());
593 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
594 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
596 printOperand(MI, 0, O);
598 printOperand(MI, 1, O);
599 OutStreamer.EmitRawText(O.str());
603 if (MI->getOpcode() == PPC::RLDICR) {
604 unsigned char SH = MI->getOperand(2).getImm();
605 unsigned char ME = MI->getOperand(3).getImm();
606 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
609 printOperand(MI, 0, O);
611 printOperand(MI, 1, O);
612 O << ", " << (unsigned int)SH;
613 OutStreamer.EmitRawText(O.str());
618 printInstruction(MI, O);
619 OutStreamer.EmitRawText(O.str());
622 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
623 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
624 return AsmPrinter::EmitFunctionEntryLabel();
626 // Emit an official procedure descriptor.
627 // FIXME 64-bit SVR4: Use MCSection here!
628 OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
629 OutStreamer.EmitRawText(StringRef("\t.align 3"));
630 OutStreamer.EmitLabel(CurrentFnSym);
631 OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
633 OutStreamer.EmitRawText(StringRef("\t.previous"));
634 OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
638 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
639 const TargetData *TD = TM.getTargetData();
641 bool isPPC64 = TD->getPointerSizeInBits() == 64;
643 if (isPPC64 && !TOC.empty()) {
644 // FIXME 64-bit SVR4: Use MCSection here?
645 OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
647 // FIXME: This is nondeterminstic!
648 for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
649 E = TOC.end(); I != E; ++I) {
650 OutStreamer.EmitLabel(I->second);
651 OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
652 "[TC]," + I->first->getName());
656 return AsmPrinter::doFinalization(M);
659 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
660 static const char *const CPUDirectives[] = {
672 unsigned Directive = Subtarget.getDarwinDirective();
673 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
674 Directive = PPC::DIR_970;
675 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
676 Directive = PPC::DIR_7400;
677 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
678 Directive = PPC::DIR_64;
679 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
680 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
682 // Prime text sections so they are adjacent. This reduces the likelihood a
683 // large data or debug section causes a branch to exceed 16M limit.
684 const TargetLoweringObjectFileMachO &TLOFMacho =
685 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
686 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
687 if (TM.getRelocationModel() == Reloc::PIC_) {
688 OutStreamer.SwitchSection(
689 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
690 MCSectionMachO::S_SYMBOL_STUBS |
691 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
692 32, SectionKind::getText()));
693 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
694 OutStreamer.SwitchSection(
695 OutContext.getMachOSection("__TEXT","__symbol_stub1",
696 MCSectionMachO::S_SYMBOL_STUBS |
697 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
698 16, SectionKind::getText()));
700 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
703 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
704 // Remove $stub suffix, add $lazy_ptr.
705 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
706 TmpStr += "$lazy_ptr";
707 return Ctx.GetOrCreateSymbol(TmpStr.str());
710 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
711 // Add $tmp suffix to $stub, yielding $stub$tmp.
712 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
714 return Ctx.GetOrCreateSymbol(TmpStr.str());
717 void PPCDarwinAsmPrinter::
718 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
719 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
721 const TargetLoweringObjectFileMachO &TLOFMacho =
722 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
724 // .lazy_symbol_pointer
725 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
727 // Output stubs for dynamically-linked functions
728 if (TM.getRelocationModel() == Reloc::PIC_) {
729 const MCSection *StubSection =
730 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
731 MCSectionMachO::S_SYMBOL_STUBS |
732 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
733 32, SectionKind::getText());
734 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
735 OutStreamer.SwitchSection(StubSection);
738 MCSymbol *Stub = Stubs[i].first;
739 MCSymbol *RawSym = Stubs[i].second.getPointer();
740 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
741 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
743 OutStreamer.EmitLabel(Stub);
744 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
745 // FIXME: MCize this.
746 OutStreamer.EmitRawText(StringRef("\tmflr r0"));
747 OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
748 OutStreamer.EmitLabel(AnonSymbol);
749 OutStreamer.EmitRawText(StringRef("\tmflr r11"));
750 OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
751 "-" + AnonSymbol->getName() + ")");
752 OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
755 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
756 "-" + AnonSymbol->getName() + ")(r11)");
758 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
759 "-" + AnonSymbol->getName() + ")(r11)");
760 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
761 OutStreamer.EmitRawText(StringRef("\tbctr"));
763 OutStreamer.SwitchSection(LSPSection);
764 OutStreamer.EmitLabel(LazyPtr);
765 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
768 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
770 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
772 OutStreamer.AddBlankLine();
776 const MCSection *StubSection =
777 OutContext.getMachOSection("__TEXT","__symbol_stub1",
778 MCSectionMachO::S_SYMBOL_STUBS |
779 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
780 16, SectionKind::getText());
781 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
782 MCSymbol *Stub = Stubs[i].first;
783 MCSymbol *RawSym = Stubs[i].second.getPointer();
784 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
786 OutStreamer.SwitchSection(StubSection);
788 OutStreamer.EmitLabel(Stub);
789 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
790 OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
792 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
795 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
797 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
798 OutStreamer.EmitRawText(StringRef("\tbctr"));
799 OutStreamer.SwitchSection(LSPSection);
800 OutStreamer.EmitLabel(LazyPtr);
801 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
804 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
806 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
809 OutStreamer.AddBlankLine();
813 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
814 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
816 // Darwin/PPC always uses mach-o.
817 const TargetLoweringObjectFileMachO &TLOFMacho =
818 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
819 MachineModuleInfoMachO &MMIMacho =
820 MMI->getObjFileInfo<MachineModuleInfoMachO>();
822 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
824 EmitFunctionStubs(Stubs);
826 if (MAI->doesSupportExceptionHandling() && MMI) {
827 // Add the (possibly multiple) personalities to the set of global values.
828 // Only referenced functions get into the Personalities list.
829 const std::vector<const Function*> &Personalities = MMI->getPersonalities();
830 for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
831 E = Personalities.end(); I != E; ++I) {
833 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
834 MachineModuleInfoImpl::StubValueTy &StubSym =
835 MMIMacho.getGVStubEntry(NLPSym);
836 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
841 // Output stubs for dynamically-linked functions.
842 Stubs = MMIMacho.GetGVStubList();
844 // Output macho stubs for external and common global variables.
845 if (!Stubs.empty()) {
846 // Switch with ".non_lazy_symbol_pointer" directive.
847 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
848 EmitAlignment(isPPC64 ? 3 : 2);
850 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
852 OutStreamer.EmitLabel(Stubs[i].first);
853 // .indirect_symbol _foo
854 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
855 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
858 // External to current translation unit.
859 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
861 // Internal to current translation unit.
863 // When we place the LSDA into the TEXT section, the type info pointers
864 // need to be indirect and pc-rel. We accomplish this by using NLPs.
865 // However, sometimes the types are local to the file. So we need to
866 // fill in the value for the NLP in those cases.
867 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
869 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
873 OutStreamer.AddBlankLine();
876 Stubs = MMIMacho.GetHiddenGVStubList();
877 if (!Stubs.empty()) {
878 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
879 EmitAlignment(isPPC64 ? 3 : 2);
881 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
883 OutStreamer.EmitLabel(Stubs[i].first);
885 OutStreamer.EmitValue(MCSymbolRefExpr::
886 Create(Stubs[i].second.getPointer(),
888 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
892 OutStreamer.AddBlankLine();
895 // Funny Darwin hack: This flag tells the linker that no global symbols
896 // contain code that falls through to other global symbols (e.g. the obvious
897 // implementation of multiple entry points). If this doesn't occur, the
898 // linker can safely perform dead code stripping. Since LLVM never generates
899 // code that does this, it is always safe to set.
900 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
902 return AsmPrinter::doFinalization(M);
905 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
906 /// for a MachineFunction to the given output stream, in a format that the
907 /// Darwin assembler can deal with.
909 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
910 MCStreamer &Streamer) {
911 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
913 if (Subtarget->isDarwin())
914 return new PPCDarwinAsmPrinter(tm, Streamer);
915 return new PPCLinuxAsmPrinter(tm, Streamer);
918 // Force static initialization.
919 extern "C" void LLVMInitializePowerPCAsmPrinter() {
920 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
921 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);