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 unsigned enumRegToMachineReg(unsigned enumReg) {
72 default: llvm_unreachable("Unhandled register!");
73 case PPC::CR0: return 0;
74 case PPC::CR1: return 1;
75 case PPC::CR2: return 2;
76 case PPC::CR3: return 3;
77 case PPC::CR4: return 4;
78 case PPC::CR5: return 5;
79 case PPC::CR6: return 6;
80 case PPC::CR7: return 7;
85 /// printInstruction - This method is automatically generated by tablegen
86 /// from the instruction set description. This method returns true if the
87 /// machine instruction was sufficiently described to print it, otherwise it
89 void printInstruction(const MachineInstr *MI, raw_ostream &O);
90 static const char *getRegisterName(unsigned RegNo);
93 virtual void EmitInstruction(const MachineInstr *MI);
94 void printOp(const MachineOperand &MO, raw_ostream &O);
96 /// stripRegisterPrefix - This method strips the character prefix from a
97 /// register name so that only the number is left. Used by for linux asm.
98 const char *stripRegisterPrefix(const char *RegName) {
102 case 'v': return RegName + 1;
103 case 'c': if (RegName[1] == 'r') return RegName + 2;
109 /// printRegister - Print register according to target requirements.
111 void printRegister(const MachineOperand &MO, bool R0AsZero, raw_ostream &O){
112 unsigned RegNo = MO.getReg();
113 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
115 // If we should use 0 for R0.
116 if (R0AsZero && RegNo == PPC::R0) {
121 const char *RegName = getRegisterName(RegNo);
122 // Linux assembler (Others?) does not take register mnemonics.
123 // FIXME - What about special registers used in mfspr/mtspr?
124 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
128 void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
129 const MachineOperand &MO = MI->getOperand(OpNo);
131 printRegister(MO, false, O);
132 } else if (MO.isImm()) {
139 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
140 unsigned AsmVariant, const char *ExtraCode,
142 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
143 unsigned AsmVariant, const char *ExtraCode,
147 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo,
149 char value = MI->getOperand(OpNo).getImm();
150 value = (value << (32-5)) >> (32-5);
153 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
155 unsigned char value = MI->getOperand(OpNo).getImm();
156 assert(value <= 31 && "Invalid u5imm argument!");
157 O << (unsigned int)value;
159 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
161 unsigned char value = MI->getOperand(OpNo).getImm();
162 assert(value <= 63 && "Invalid u6imm argument!");
163 O << (unsigned int)value;
165 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
167 O << (short)MI->getOperand(OpNo).getImm();
169 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
171 O << (unsigned short)MI->getOperand(OpNo).getImm();
173 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), O);
180 if (TM.getRelocationModel() == Reloc::PIC_)
181 O << "-\"L" << getFunctionNumber() << "$pb\")";
186 void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
188 // Branches can take an immediate operand. This is used by the branch
189 // selection pass to print $+8, an eight byte displacement from the PC.
190 if (MI->getOperand(OpNo).isImm()) {
191 O << "$+" << MI->getOperand(OpNo).getImm()*4;
193 printOp(MI->getOperand(OpNo), O);
196 void printCallOperand(const MachineInstr *MI, unsigned OpNo,
198 const MachineOperand &MO = MI->getOperand(OpNo);
199 if (TM.getRelocationModel() != Reloc::Static) {
201 const GlobalValue *GV = MO.getGlobal();
202 if (GV->isDeclaration() || GV->isWeakForLinker()) {
203 // Dynamically-resolved functions need a stub for the function.
204 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
205 MachineModuleInfoImpl::StubValueTy &StubSym =
206 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
207 if (StubSym.getPointer() == 0)
208 StubSym = MachineModuleInfoImpl::
209 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
215 SmallString<128> TempNameStr;
216 TempNameStr += StringRef(MO.getSymbolName());
217 TempNameStr += StringRef("$stub");
219 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
220 MachineModuleInfoImpl::StubValueTy &StubSym =
221 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
222 if (StubSym.getPointer() == 0)
223 StubSym = MachineModuleInfoImpl::
224 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
230 printOp(MI->getOperand(OpNo), O);
232 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
234 O << (int)MI->getOperand(OpNo).getImm()*4;
236 void printPICLabel(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
237 O << "\"L" << getFunctionNumber() << "$pb\"\n";
238 O << "\"L" << getFunctionNumber() << "$pb\":";
240 void printSymbolHi(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
241 if (MI->getOperand(OpNo).isImm()) {
242 printS16ImmOperand(MI, OpNo, O);
244 if (Subtarget.isDarwin()) O << "ha16(";
245 printOp(MI->getOperand(OpNo), O);
246 if (TM.getRelocationModel() == Reloc::PIC_)
247 O << "-\"L" << getFunctionNumber() << "$pb\"";
248 if (Subtarget.isDarwin())
254 void printSymbolLo(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
255 if (MI->getOperand(OpNo).isImm()) {
256 printS16ImmOperand(MI, OpNo, O);
258 if (Subtarget.isDarwin()) O << "lo16(";
259 printOp(MI->getOperand(OpNo), O);
260 if (TM.getRelocationModel() == Reloc::PIC_)
261 O << "-\"L" << getFunctionNumber() << "$pb\"";
262 if (Subtarget.isDarwin())
268 void printcrbitm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
269 unsigned CCReg = MI->getOperand(OpNo).getReg();
270 unsigned RegNo = enumRegToMachineReg(CCReg);
271 O << (0x80 >> RegNo);
273 // The new addressing mode printers.
274 void printMemRegImm(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
275 printSymbolLo(MI, OpNo, O);
277 if (MI->getOperand(OpNo+1).isReg() &&
278 MI->getOperand(OpNo+1).getReg() == PPC::R0)
281 printOperand(MI, OpNo+1, O);
284 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo,
286 if (MI->getOperand(OpNo).isImm())
287 printS16X4ImmOperand(MI, OpNo, O);
289 printSymbolLo(MI, OpNo, O);
291 if (MI->getOperand(OpNo+1).isReg() &&
292 MI->getOperand(OpNo+1).getReg() == PPC::R0)
295 printOperand(MI, OpNo+1, O);
299 void printMemRegReg(const MachineInstr *MI, unsigned OpNo, raw_ostream &O) {
300 // When used as the base register, r0 reads constant zero rather than
301 // the value contained in the register. For this reason, the darwin
302 // assembler requires that we print r0 as 0 (no r) when used as the base.
303 const MachineOperand &MO = MI->getOperand(OpNo);
304 printRegister(MO, true, O);
306 printOperand(MI, OpNo+1, O);
309 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo,
311 const MachineOperand &MO = MI->getOperand(OpNo);
312 assert(MO.isGlobal());
313 MCSymbol *Sym = Mang->getSymbol(MO.getGlobal());
315 // Map symbol -> label of TOC entry.
316 MCSymbol *&TOCEntry = TOC[Sym];
318 TOCEntry = OutContext.
319 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) +
320 "C" + Twine(LabelID++));
322 O << *TOCEntry << "@toc";
325 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
326 raw_ostream &O, const char *Modifier);
328 MachineLocation getDebugValueLocation(const MachineInstr *MI) const {
330 MachineLocation Location;
331 assert (MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
332 // Frame address. Currently handles register +- offset only.
333 if (MI->getOperand(0).isReg() && MI->getOperand(2).isImm())
334 Location.set(MI->getOperand(0).getReg(), MI->getOperand(2).getImm());
336 DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
342 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
343 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
345 explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
346 : PPCAsmPrinter(TM, Streamer) {}
348 virtual const char *getPassName() const {
349 return "Linux PPC Assembly Printer";
352 bool doFinalization(Module &M);
354 virtual void EmitFunctionEntryLabel();
357 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
359 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
361 explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
362 : PPCAsmPrinter(TM, Streamer) {}
364 virtual const char *getPassName() const {
365 return "Darwin PPC Assembly Printer";
368 bool doFinalization(Module &M);
369 void EmitStartOfAsmFile(Module &M);
371 void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
373 } // end of anonymous namespace
375 // Include the auto-generated portion of the assembly writer
376 #include "PPCGenAsmWriter.inc"
378 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
379 switch (MO.getType()) {
380 case MachineOperand::MO_Immediate:
381 llvm_unreachable("printOp() does not handle immediate values");
383 case MachineOperand::MO_MachineBasicBlock:
384 O << *MO.getMBB()->getSymbol();
386 case MachineOperand::MO_JumpTableIndex:
387 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
388 << '_' << MO.getIndex();
389 // FIXME: PIC relocation model
391 case MachineOperand::MO_ConstantPoolIndex:
392 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
393 << '_' << MO.getIndex();
395 case MachineOperand::MO_BlockAddress:
396 O << *GetBlockAddressSymbol(MO.getBlockAddress());
398 case MachineOperand::MO_ExternalSymbol: {
399 // Computing the address of an external symbol, not calling it.
400 if (TM.getRelocationModel() == Reloc::Static) {
401 O << *GetExternalSymbolSymbol(MO.getSymbolName());
406 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
407 MO.getSymbolName()+"$non_lazy_ptr");
408 MachineModuleInfoImpl::StubValueTy &StubSym =
409 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
410 if (StubSym.getPointer() == 0)
411 StubSym = MachineModuleInfoImpl::
412 StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
417 case MachineOperand::MO_GlobalAddress: {
418 // Computing the address of a global symbol, not calling it.
419 const 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 MachineModuleInfoImpl::StubValueTy &StubSym =
428 MMI->getObjFileInfo<MachineModuleInfoMachO>()
429 .getGVStubEntry(SymToPrint);
430 if (StubSym.getPointer() == 0)
431 StubSym = MachineModuleInfoImpl::
432 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
433 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
434 GV->hasAvailableExternallyLinkage()) {
435 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
437 MachineModuleInfoImpl::StubValueTy &StubSym =
438 MMI->getObjFileInfo<MachineModuleInfoMachO>().
439 getHiddenGVStubEntry(SymToPrint);
440 if (StubSym.getPointer() == 0)
441 StubSym = MachineModuleInfoImpl::
442 StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
444 SymToPrint = Mang->getSymbol(GV);
447 SymToPrint = Mang->getSymbol(GV);
452 printOffset(MO.getOffset(), O);
457 O << "<unknown operand type: " << MO.getType() << ">";
462 /// PrintAsmOperand - Print out an operand for an inline asm expression.
464 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
466 const char *ExtraCode, raw_ostream &O) {
467 // Does this asm operand have a single letter operand modifier?
468 if (ExtraCode && ExtraCode[0]) {
469 if (ExtraCode[1] != 0) return true; // Unknown modifier.
471 switch (ExtraCode[0]) {
472 default: return true; // Unknown modifier.
473 case 'c': // Don't print "$" before a global var name or constant.
474 // PPC never has a prefix.
475 printOperand(MI, OpNo, O);
477 case 'L': // Write second word of DImode reference.
478 // Verify that this operand has two consecutive registers.
479 if (!MI->getOperand(OpNo).isReg() ||
480 OpNo+1 == MI->getNumOperands() ||
481 !MI->getOperand(OpNo+1).isReg())
483 ++OpNo; // Return the high-part.
486 // Write 'i' if an integer constant, otherwise nothing. Used to print
488 if (MI->getOperand(OpNo).isImm())
494 printOperand(MI, OpNo, O);
498 // At the moment, all inline asm memory operands are a single register.
499 // In any case, the output of this routine should always be just one
500 // assembler operand.
502 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
504 const char *ExtraCode,
506 if (ExtraCode && ExtraCode[0])
507 return true; // Unknown modifier.
508 assert (MI->getOperand(OpNo).isReg());
510 printOperand(MI, OpNo, O);
515 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
516 raw_ostream &O, const char *Modifier){
517 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
518 unsigned Code = MI->getOperand(OpNo).getImm();
519 if (!strcmp(Modifier, "cc")) {
520 switch ((PPC::Predicate)Code) {
521 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
522 case PPC::PRED_LT: O << "lt"; return;
523 case PPC::PRED_LE: O << "le"; return;
524 case PPC::PRED_EQ: O << "eq"; return;
525 case PPC::PRED_GE: O << "ge"; return;
526 case PPC::PRED_GT: O << "gt"; return;
527 case PPC::PRED_NE: O << "ne"; return;
528 case PPC::PRED_UN: O << "un"; return;
529 case PPC::PRED_NU: O << "nu"; return;
533 assert(!strcmp(Modifier, "reg") &&
534 "Need to specify 'cc' or 'reg' as predicate op modifier!");
535 // Don't print the register for 'always'.
536 if (Code == PPC::PRED_ALWAYS) return;
537 printOperand(MI, OpNo+1, O);
542 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
543 /// the current output stream.
545 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
546 SmallString<128> Str;
547 raw_svector_ostream O(Str);
549 if (MI->getOpcode() == TargetOpcode::DBG_VALUE) {
550 unsigned NOps = MI->getNumOperands();
552 O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
553 // cast away const; DIetc do not take const operands for some reason.
554 DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
557 // Frame address. Currently handles register +- offset only.
558 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
559 O << '['; printOperand(MI, 0, O); O << '+'; printOperand(MI, 1, O);
562 printOperand(MI, NOps-2, O);
563 OutStreamer.EmitRawText(O.str());
566 // Check for slwi/srwi mnemonics.
567 if (MI->getOpcode() == PPC::RLWINM) {
568 unsigned char SH = MI->getOperand(2).getImm();
569 unsigned char MB = MI->getOperand(3).getImm();
570 unsigned char ME = MI->getOperand(4).getImm();
571 bool useSubstituteMnemonic = false;
572 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
573 O << "\tslwi "; useSubstituteMnemonic = true;
575 if (SH <= 31 && MB == (32-SH) && ME == 31) {
576 O << "\tsrwi "; useSubstituteMnemonic = true;
579 if (useSubstituteMnemonic) {
580 printOperand(MI, 0, O);
582 printOperand(MI, 1, O);
583 O << ", " << (unsigned int)SH;
584 OutStreamer.EmitRawText(O.str());
589 if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
590 MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
592 printOperand(MI, 0, O);
594 printOperand(MI, 1, O);
595 OutStreamer.EmitRawText(O.str());
599 if (MI->getOpcode() == PPC::RLDICR) {
600 unsigned char SH = MI->getOperand(2).getImm();
601 unsigned char ME = MI->getOperand(3).getImm();
602 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
605 printOperand(MI, 0, O);
607 printOperand(MI, 1, O);
608 O << ", " << (unsigned int)SH;
609 OutStreamer.EmitRawText(O.str());
614 printInstruction(MI, O);
615 OutStreamer.EmitRawText(O.str());
618 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
619 if (!Subtarget.isPPC64()) // linux/ppc32 - Normal entry label.
620 return AsmPrinter::EmitFunctionEntryLabel();
622 // Emit an official procedure descriptor.
623 // FIXME 64-bit SVR4: Use MCSection here!
624 OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
625 OutStreamer.EmitRawText(StringRef("\t.align 3"));
626 OutStreamer.EmitLabel(CurrentFnSym);
627 OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
629 OutStreamer.EmitRawText(StringRef("\t.previous"));
630 OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
634 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
635 const TargetData *TD = TM.getTargetData();
637 bool isPPC64 = TD->getPointerSizeInBits() == 64;
639 if (isPPC64 && !TOC.empty()) {
640 // FIXME 64-bit SVR4: Use MCSection here?
641 OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
643 // FIXME: This is nondeterminstic!
644 for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
645 E = TOC.end(); I != E; ++I) {
646 OutStreamer.EmitLabel(I->second);
647 OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
648 "[TC]," + I->first->getName());
652 return AsmPrinter::doFinalization(M);
655 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
656 static const char *const CPUDirectives[] = {
668 unsigned Directive = Subtarget.getDarwinDirective();
669 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
670 Directive = PPC::DIR_970;
671 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
672 Directive = PPC::DIR_7400;
673 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
674 Directive = PPC::DIR_64;
675 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
676 OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
678 // Prime text sections so they are adjacent. This reduces the likelihood a
679 // large data or debug section causes a branch to exceed 16M limit.
680 const TargetLoweringObjectFileMachO &TLOFMacho =
681 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
682 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
683 if (TM.getRelocationModel() == Reloc::PIC_) {
684 OutStreamer.SwitchSection(
685 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
686 MCSectionMachO::S_SYMBOL_STUBS |
687 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
688 32, SectionKind::getText()));
689 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
690 OutStreamer.SwitchSection(
691 OutContext.getMachOSection("__TEXT","__symbol_stub1",
692 MCSectionMachO::S_SYMBOL_STUBS |
693 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
694 16, SectionKind::getText()));
696 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
699 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
700 // Remove $stub suffix, add $lazy_ptr.
701 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
702 TmpStr += "$lazy_ptr";
703 return Ctx.GetOrCreateSymbol(TmpStr.str());
706 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
707 // Add $tmp suffix to $stub, yielding $stub$tmp.
708 SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
710 return Ctx.GetOrCreateSymbol(TmpStr.str());
713 void PPCDarwinAsmPrinter::
714 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
715 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
717 const TargetLoweringObjectFileMachO &TLOFMacho =
718 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
720 // .lazy_symbol_pointer
721 const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
723 // Output stubs for dynamically-linked functions
724 if (TM.getRelocationModel() == Reloc::PIC_) {
725 const MCSection *StubSection =
726 OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
727 MCSectionMachO::S_SYMBOL_STUBS |
728 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
729 32, SectionKind::getText());
730 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
731 OutStreamer.SwitchSection(StubSection);
734 MCSymbol *Stub = Stubs[i].first;
735 MCSymbol *RawSym = Stubs[i].second.getPointer();
736 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
737 MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
739 OutStreamer.EmitLabel(Stub);
740 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
741 // FIXME: MCize this.
742 OutStreamer.EmitRawText(StringRef("\tmflr r0"));
743 OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
744 OutStreamer.EmitLabel(AnonSymbol);
745 OutStreamer.EmitRawText(StringRef("\tmflr r11"));
746 OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
747 "-" + AnonSymbol->getName() + ")");
748 OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
751 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
752 "-" + AnonSymbol->getName() + ")(r11)");
754 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
755 "-" + AnonSymbol->getName() + ")(r11)");
756 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
757 OutStreamer.EmitRawText(StringRef("\tbctr"));
759 OutStreamer.SwitchSection(LSPSection);
760 OutStreamer.EmitLabel(LazyPtr);
761 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
764 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
766 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
768 OutStreamer.AddBlankLine();
772 const MCSection *StubSection =
773 OutContext.getMachOSection("__TEXT","__symbol_stub1",
774 MCSectionMachO::S_SYMBOL_STUBS |
775 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
776 16, SectionKind::getText());
777 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
778 MCSymbol *Stub = Stubs[i].first;
779 MCSymbol *RawSym = Stubs[i].second.getPointer();
780 MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
782 OutStreamer.SwitchSection(StubSection);
784 OutStreamer.EmitLabel(Stub);
785 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
786 OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
788 OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
791 OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
793 OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
794 OutStreamer.EmitRawText(StringRef("\tbctr"));
795 OutStreamer.SwitchSection(LSPSection);
796 OutStreamer.EmitLabel(LazyPtr);
797 OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
800 OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
802 OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
805 OutStreamer.AddBlankLine();
809 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
810 bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
812 // Darwin/PPC always uses mach-o.
813 const TargetLoweringObjectFileMachO &TLOFMacho =
814 static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
815 MachineModuleInfoMachO &MMIMacho =
816 MMI->getObjFileInfo<MachineModuleInfoMachO>();
818 MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
820 EmitFunctionStubs(Stubs);
822 if (MAI->doesSupportExceptionHandling() && MMI) {
823 // Add the (possibly multiple) personalities to the set of global values.
824 // Only referenced functions get into the Personalities list.
825 const std::vector<const Function*> &Personalities = MMI->getPersonalities();
826 for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
827 E = Personalities.end(); I != E; ++I) {
829 MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
830 MachineModuleInfoImpl::StubValueTy &StubSym =
831 MMIMacho.getGVStubEntry(NLPSym);
832 StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
837 // Output stubs for dynamically-linked functions.
838 Stubs = MMIMacho.GetGVStubList();
840 // Output macho stubs for external and common global variables.
841 if (!Stubs.empty()) {
842 // Switch with ".non_lazy_symbol_pointer" directive.
843 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
844 EmitAlignment(isPPC64 ? 3 : 2);
846 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
848 OutStreamer.EmitLabel(Stubs[i].first);
849 // .indirect_symbol _foo
850 MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
851 OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
854 // External to current translation unit.
855 OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
857 // Internal to current translation unit.
859 // When we place the LSDA into the TEXT section, the type info pointers
860 // need to be indirect and pc-rel. We accomplish this by using NLPs.
861 // However, sometimes the types are local to the file. So we need to
862 // fill in the value for the NLP in those cases.
863 OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
865 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
869 OutStreamer.AddBlankLine();
872 Stubs = MMIMacho.GetHiddenGVStubList();
873 if (!Stubs.empty()) {
874 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
875 EmitAlignment(isPPC64 ? 3 : 2);
877 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
879 OutStreamer.EmitLabel(Stubs[i].first);
881 OutStreamer.EmitValue(MCSymbolRefExpr::
882 Create(Stubs[i].second.getPointer(),
884 isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
888 OutStreamer.AddBlankLine();
891 // Funny Darwin hack: This flag tells the linker that no global symbols
892 // contain code that falls through to other global symbols (e.g. the obvious
893 // implementation of multiple entry points). If this doesn't occur, the
894 // linker can safely perform dead code stripping. Since LLVM never generates
895 // code that does this, it is always safe to set.
896 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
898 return AsmPrinter::doFinalization(M);
901 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
902 /// for a MachineFunction to the given output stream, in a format that the
903 /// Darwin assembler can deal with.
905 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
906 MCStreamer &Streamer) {
907 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
909 if (Subtarget->isDarwin())
910 return new PPCDarwinAsmPrinter(tm, Streamer);
911 return new PPCLinuxAsmPrinter(tm, Streamer);
914 // Force static initialization.
915 extern "C" void LLVMInitializePowerPCAsmPrinter() {
916 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
917 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);