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