241bb900cfb4a0e2c23b03fbf661e8b4cd207bc2
[oota-llvm.git] / lib / Target / PowerPC / AsmPrinter / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "asmprinter"
20 #include "PPC.h"
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/StringExtras.h"
51 #include "llvm/ADT/StringSet.h"
52 #include "llvm/ADT/SmallString.h"
53 using namespace llvm;
54
55 namespace {
56   class PPCAsmPrinter : public AsmPrinter {
57   protected:
58     DenseMap<const MCSymbol*, const MCSymbol*> TOC;
59     const PPCSubtarget &Subtarget;
60     uint64_t LabelID;
61   public:
62     explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
63                            MCContext &Ctx, MCStreamer &Streamer,
64                            const MCAsmInfo *T)
65       : AsmPrinter(O, TM, Ctx, Streamer, T),
66         Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
67
68     virtual const char *getPassName() const {
69       return "PowerPC Assembly Printer";
70     }
71
72     PPCTargetMachine &getTM() {
73       return static_cast<PPCTargetMachine&>(TM);
74     }
75
76     unsigned enumRegToMachineReg(unsigned enumReg) {
77       switch (enumReg) {
78       default: llvm_unreachable("Unhandled register!");
79       case PPC::CR0:  return  0;
80       case PPC::CR1:  return  1;
81       case PPC::CR2:  return  2;
82       case PPC::CR3:  return  3;
83       case PPC::CR4:  return  4;
84       case PPC::CR5:  return  5;
85       case PPC::CR6:  return  6;
86       case PPC::CR7:  return  7;
87       }
88       llvm_unreachable(0);
89     }
90
91     /// printInstruction - This method is automatically generated by tablegen
92     /// from the instruction set description.  This method returns true if the
93     /// machine instruction was sufficiently described to print it, otherwise it
94     /// returns false.
95     void printInstruction(const MachineInstr *MI);
96     static const char *getRegisterName(unsigned RegNo);
97
98
99     virtual void EmitInstruction(const MachineInstr *MI);
100     void printOp(const MachineOperand &MO);
101
102     /// stripRegisterPrefix - This method strips the character prefix from a
103     /// register name so that only the number is left.  Used by for linux asm.
104     const char *stripRegisterPrefix(const char *RegName) {
105       switch (RegName[0]) {
106       case 'r':
107       case 'f':
108       case 'v': return RegName + 1;
109       case 'c': if (RegName[1] == 'r') return RegName + 2;
110       }
111
112       return RegName;
113     }
114
115     /// printRegister - Print register according to target requirements.
116     ///
117     void printRegister(const MachineOperand &MO, bool R0AsZero) {
118       unsigned RegNo = MO.getReg();
119       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
120
121       // If we should use 0 for R0.
122       if (R0AsZero && RegNo == PPC::R0) {
123         O << "0";
124         return;
125       }
126
127       const char *RegName = getRegisterName(RegNo);
128       // Linux assembler (Others?) does not take register mnemonics.
129       // FIXME - What about special registers used in mfspr/mtspr?
130       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
131       O << RegName;
132     }
133
134     void printOperand(const MachineInstr *MI, unsigned OpNo) {
135       const MachineOperand &MO = MI->getOperand(OpNo);
136       if (MO.isReg()) {
137         printRegister(MO, false);
138       } else if (MO.isImm()) {
139         O << MO.getImm();
140       } else {
141         printOp(MO);
142       }
143     }
144
145     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
146                          unsigned AsmVariant, const char *ExtraCode);
147     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
148                                unsigned AsmVariant, const char *ExtraCode);
149
150
151     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
152       char value = MI->getOperand(OpNo).getImm();
153       value = (value << (32-5)) >> (32-5);
154       O << (int)value;
155     }
156     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
157       unsigned char value = MI->getOperand(OpNo).getImm();
158       assert(value <= 31 && "Invalid u5imm argument!");
159       O << (unsigned int)value;
160     }
161     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
162       unsigned char value = MI->getOperand(OpNo).getImm();
163       assert(value <= 63 && "Invalid u6imm argument!");
164       O << (unsigned int)value;
165     }
166     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
167       O << (short)MI->getOperand(OpNo).getImm();
168     }
169     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
170       O << (unsigned short)MI->getOperand(OpNo).getImm();
171     }
172     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
173       if (MI->getOperand(OpNo).isImm()) {
174         O << (short)(MI->getOperand(OpNo).getImm()*4);
175       } else {
176         O << "lo16(";
177         printOp(MI->getOperand(OpNo));
178         if (TM.getRelocationModel() == Reloc::PIC_)
179           O << "-\"L" << getFunctionNumber() << "$pb\")";
180         else
181           O << ')';
182       }
183     }
184     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
185       // Branches can take an immediate operand.  This is used by the branch
186       // selection pass to print $+8, an eight byte displacement from the PC.
187       if (MI->getOperand(OpNo).isImm()) {
188         O << "$+" << MI->getOperand(OpNo).getImm()*4;
189       } else {
190         printOp(MI->getOperand(OpNo));
191       }
192     }
193     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
194       const MachineOperand &MO = MI->getOperand(OpNo);
195       if (TM.getRelocationModel() != Reloc::Static) {
196         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
197           GlobalValue *GV = MO.getGlobal();
198           if (GV->isDeclaration() || GV->isWeakForLinker()) {
199             // Dynamically-resolved functions need a stub for the function.
200             MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
201             const MCSymbol *&StubSym =
202               MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
203             if (StubSym == 0)
204               StubSym = GetGlobalValueSymbol(GV);
205             O << *Sym;
206             return;
207           }
208         }
209         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
210           SmallString<128> TempNameStr;
211           TempNameStr += StringRef(MO.getSymbolName());
212           TempNameStr += StringRef("$stub");
213           
214           const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
215           const MCSymbol *&StubSym =
216             MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
217           if (StubSym == 0)
218             StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
219           O << *Sym;
220           return;
221         }
222       }
223
224       printOp(MI->getOperand(OpNo));
225     }
226     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
227      O << (int)MI->getOperand(OpNo).getImm()*4;
228     }
229     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
230       O << "\"L" << getFunctionNumber() << "$pb\"\n";
231       O << "\"L" << getFunctionNumber() << "$pb\":";
232     }
233     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
234       if (MI->getOperand(OpNo).isImm()) {
235         printS16ImmOperand(MI, OpNo);
236       } else {
237         if (Subtarget.isDarwin()) O << "ha16(";
238         printOp(MI->getOperand(OpNo));
239         if (TM.getRelocationModel() == Reloc::PIC_)
240           O << "-\"L" << getFunctionNumber() << "$pb\"";
241         if (Subtarget.isDarwin())
242           O << ')';
243         else
244           O << "@ha";
245       }
246     }
247     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
248       if (MI->getOperand(OpNo).isImm()) {
249         printS16ImmOperand(MI, OpNo);
250       } else {
251         if (Subtarget.isDarwin()) O << "lo16(";
252         printOp(MI->getOperand(OpNo));
253         if (TM.getRelocationModel() == Reloc::PIC_)
254           O << "-\"L" << getFunctionNumber() << "$pb\"";
255         if (Subtarget.isDarwin())
256           O << ')';
257         else
258           O << "@l";
259       }
260     }
261     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
262       unsigned CCReg = MI->getOperand(OpNo).getReg();
263       unsigned RegNo = enumRegToMachineReg(CCReg);
264       O << (0x80 >> RegNo);
265     }
266     // The new addressing mode printers.
267     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
268       printSymbolLo(MI, OpNo);
269       O << '(';
270       if (MI->getOperand(OpNo+1).isReg() &&
271           MI->getOperand(OpNo+1).getReg() == PPC::R0)
272         O << "0";
273       else
274         printOperand(MI, OpNo+1);
275       O << ')';
276     }
277     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
278       if (MI->getOperand(OpNo).isImm())
279         printS16X4ImmOperand(MI, OpNo);
280       else
281         printSymbolLo(MI, OpNo);
282       O << '(';
283       if (MI->getOperand(OpNo+1).isReg() &&
284           MI->getOperand(OpNo+1).getReg() == PPC::R0)
285         O << "0";
286       else
287         printOperand(MI, OpNo+1);
288       O << ')';
289     }
290
291     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
292       // When used as the base register, r0 reads constant zero rather than
293       // the value contained in the register.  For this reason, the darwin
294       // assembler requires that we print r0 as 0 (no r) when used as the base.
295       const MachineOperand &MO = MI->getOperand(OpNo);
296       printRegister(MO, true);
297       O << ", ";
298       printOperand(MI, OpNo+1);
299     }
300
301     void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
302       const MachineOperand &MO = MI->getOperand(OpNo);
303
304       assert(MO.getType() == MachineOperand::MO_GlobalAddress);
305
306       const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
307
308       // Map symbol -> label of TOC entry.
309       const MCSymbol *&TOCEntry = TOC[Sym];
310       if (TOCEntry == 0)
311         TOCEntry = OutContext.
312           GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
313                             Twine(LabelID++));
314
315       O << *TOCEntry << "@toc";
316     }
317
318     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
319                                const char *Modifier);
320   };
321
322   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
323   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
324   public:
325     explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
326                                 MCContext &Ctx, MCStreamer &Streamer,
327                                 const MCAsmInfo *T)
328       : PPCAsmPrinter(O, TM, Ctx, Streamer, T) {}
329
330     virtual const char *getPassName() const {
331       return "Linux PPC Assembly Printer";
332     }
333
334     bool doFinalization(Module &M);
335
336     virtual void EmitFunctionEntryLabel();
337
338     void getAnalysisUsage(AnalysisUsage &AU) const {
339       AU.setPreservesAll();
340       AU.addRequired<MachineModuleInfo>();
341       AU.addRequired<DwarfWriter>();
342       PPCAsmPrinter::getAnalysisUsage(AU);
343     }
344   };
345
346   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
347   /// OS X
348   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
349     formatted_raw_ostream &OS;
350   public:
351     explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
352                                  MCContext &Ctx, MCStreamer &Streamer,
353                                  const MCAsmInfo *T)
354       : PPCAsmPrinter(O, TM, Ctx, Streamer, T), OS(O) {}
355
356     virtual const char *getPassName() const {
357       return "Darwin PPC Assembly Printer";
358     }
359
360     bool doFinalization(Module &M);
361     void EmitStartOfAsmFile(Module &M);
362
363     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
364     
365     void getAnalysisUsage(AnalysisUsage &AU) const {
366       AU.setPreservesAll();
367       AU.addRequired<MachineModuleInfo>();
368       AU.addRequired<DwarfWriter>();
369       PPCAsmPrinter::getAnalysisUsage(AU);
370     }
371   };
372 } // end of anonymous namespace
373
374 // Include the auto-generated portion of the assembly writer
375 #include "PPCGenAsmWriter.inc"
376
377 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
378   switch (MO.getType()) {
379   case MachineOperand::MO_Immediate:
380     llvm_unreachable("printOp() does not handle immediate values");
381
382   case MachineOperand::MO_MachineBasicBlock:
383     O << *MO.getMBB()->getSymbol(OutContext);
384     return;
385   case MachineOperand::MO_JumpTableIndex:
386     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
387       << '_' << MO.getIndex();
388     // FIXME: PIC relocation model
389     return;
390   case MachineOperand::MO_ConstantPoolIndex:
391     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
392       << '_' << MO.getIndex();
393     return;
394   case MachineOperand::MO_BlockAddress:
395     O << *GetBlockAddressSymbol(MO.getBlockAddress());
396     return;
397   case MachineOperand::MO_ExternalSymbol: {
398     // Computing the address of an external symbol, not calling it.
399     if (TM.getRelocationModel() == Reloc::Static) {
400       O << *GetExternalSymbolSymbol(MO.getSymbolName());
401       return;
402     }
403
404     const MCSymbol *NLPSym = 
405       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
406                                    MO.getSymbolName()+"$non_lazy_ptr");
407     const MCSymbol *&StubSym = 
408       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
409     if (StubSym == 0)
410       StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
411     
412     O << *NLPSym;
413     return;
414   }
415   case MachineOperand::MO_GlobalAddress: {
416     // Computing the address of a global symbol, not calling it.
417     GlobalValue *GV = MO.getGlobal();
418     MCSymbol *SymToPrint;
419
420     // External or weakly linked global variables need non-lazily-resolved stubs
421     if (TM.getRelocationModel() != Reloc::Static &&
422         (GV->isDeclaration() || GV->isWeakForLinker())) {
423       if (!GV->hasHiddenVisibility()) {
424         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
425         const MCSymbol *&StubSym = 
426        MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(SymToPrint);
427         if (StubSym == 0)
428           StubSym = GetGlobalValueSymbol(GV);
429       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
430                  GV->hasAvailableExternallyLinkage()) {
431         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
432         
433         const MCSymbol *&StubSym = 
434           MMI->getObjFileInfo<MachineModuleInfoMachO>().
435                     getHiddenGVStubEntry(SymToPrint);
436         if (StubSym == 0)
437           StubSym = GetGlobalValueSymbol(GV);
438       } else {
439         SymToPrint = GetGlobalValueSymbol(GV);
440       }
441     } else {
442       SymToPrint = GetGlobalValueSymbol(GV);
443     }
444     
445     O << *SymToPrint;
446
447     printOffset(MO.getOffset());
448     return;
449   }
450
451   default:
452     O << "<unknown operand type: " << MO.getType() << ">";
453     return;
454   }
455 }
456
457 /// PrintAsmOperand - Print out an operand for an inline asm expression.
458 ///
459 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
460                                     unsigned AsmVariant,
461                                     const char *ExtraCode) {
462   // Does this asm operand have a single letter operand modifier?
463   if (ExtraCode && ExtraCode[0]) {
464     if (ExtraCode[1] != 0) return true; // Unknown modifier.
465
466     switch (ExtraCode[0]) {
467     default: return true;  // Unknown modifier.
468     case 'c': // Don't print "$" before a global var name or constant.
469       // PPC never has a prefix.
470       printOperand(MI, OpNo);
471       return false;
472     case 'L': // Write second word of DImode reference.
473       // Verify that this operand has two consecutive registers.
474       if (!MI->getOperand(OpNo).isReg() ||
475           OpNo+1 == MI->getNumOperands() ||
476           !MI->getOperand(OpNo+1).isReg())
477         return true;
478       ++OpNo;   // Return the high-part.
479       break;
480     case 'I':
481       // Write 'i' if an integer constant, otherwise nothing.  Used to print
482       // addi vs add, etc.
483       if (MI->getOperand(OpNo).isImm())
484         O << "i";
485       return false;
486     }
487   }
488
489   printOperand(MI, OpNo);
490   return false;
491 }
492
493 // At the moment, all inline asm memory operands are a single register.
494 // In any case, the output of this routine should always be just one
495 // assembler operand.
496
497 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
498                                           unsigned AsmVariant,
499                                           const char *ExtraCode) {
500   if (ExtraCode && ExtraCode[0])
501     return true; // Unknown modifier.
502   assert (MI->getOperand(OpNo).isReg());
503   O << "0(";
504   printOperand(MI, OpNo);
505   O << ")";
506   return false;
507 }
508
509 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
510                                           const char *Modifier) {
511   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
512   unsigned Code = MI->getOperand(OpNo).getImm();
513   if (!strcmp(Modifier, "cc")) {
514     switch ((PPC::Predicate)Code) {
515     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
516     case PPC::PRED_LT: O << "lt"; return;
517     case PPC::PRED_LE: O << "le"; return;
518     case PPC::PRED_EQ: O << "eq"; return;
519     case PPC::PRED_GE: O << "ge"; return;
520     case PPC::PRED_GT: O << "gt"; return;
521     case PPC::PRED_NE: O << "ne"; return;
522     case PPC::PRED_UN: O << "un"; return;
523     case PPC::PRED_NU: O << "nu"; return;
524     }
525
526   } else {
527     assert(!strcmp(Modifier, "reg") &&
528            "Need to specify 'cc' or 'reg' as predicate op modifier!");
529     // Don't print the register for 'always'.
530     if (Code == PPC::PRED_ALWAYS) return;
531     printOperand(MI, OpNo+1);
532   }
533 }
534
535
536 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
537 /// the current output stream.
538 ///
539 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
540   // Check for slwi/srwi mnemonics.
541   if (MI->getOpcode() == PPC::RLWINM) {
542     unsigned char SH = MI->getOperand(2).getImm();
543     unsigned char MB = MI->getOperand(3).getImm();
544     unsigned char ME = MI->getOperand(4).getImm();
545     bool useSubstituteMnemonic = false;
546     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
547       O << "\tslwi "; useSubstituteMnemonic = true;
548     }
549     if (SH <= 31 && MB == (32-SH) && ME == 31) {
550       O << "\tsrwi "; useSubstituteMnemonic = true;
551       SH = 32-SH;
552     }
553     if (useSubstituteMnemonic) {
554       printOperand(MI, 0);
555       O << ", ";
556       printOperand(MI, 1);
557       O << ", " << (unsigned int)SH;
558       return;
559     }
560   }
561   
562   if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
563       MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
564     O << "\tmr ";
565     printOperand(MI, 0);
566     O << ", ";
567     printOperand(MI, 1);
568     return;
569   }
570   
571   if (MI->getOpcode() == PPC::RLDICR) {
572     unsigned char SH = MI->getOperand(2).getImm();
573     unsigned char ME = MI->getOperand(3).getImm();
574     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
575     if (63-SH == ME) {
576       O << "\tsldi ";
577       printOperand(MI, 0);
578       O << ", ";
579       printOperand(MI, 1);
580       O << ", " << (unsigned int)SH;
581       return;
582     }
583   }
584
585   printInstruction(MI);
586 }
587
588 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
589   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
590     return AsmPrinter::EmitFunctionEntryLabel();
591     
592   // Emit an official procedure descriptor.
593   // FIXME 64-bit SVR4: Use MCSection here!
594   O << "\t.section\t\".opd\",\"aw\"\n";
595   O << "\t.align 3\n";
596   OutStreamer.EmitLabel(CurrentFnSym);
597   O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
598   O << "\t.previous\n";
599   O << ".L." << *CurrentFnSym << ":\n";
600 }
601
602
603 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
604   const TargetData *TD = TM.getTargetData();
605
606   bool isPPC64 = TD->getPointerSizeInBits() == 64;
607
608   if (isPPC64 && !TOC.empty()) {
609     // FIXME 64-bit SVR4: Use MCSection here?
610     O << "\t.section\t\".toc\",\"aw\"\n";
611
612     // FIXME: This is nondeterminstic!
613     for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
614          E = TOC.end(); I != E; ++I) {
615       O << *I->second << ":\n";
616       O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
617     }
618   }
619
620   return AsmPrinter::doFinalization(M);
621 }
622
623 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
624   static const char *const CPUDirectives[] = {
625     "",
626     "ppc",
627     "ppc601",
628     "ppc602",
629     "ppc603",
630     "ppc7400",
631     "ppc750",
632     "ppc970",
633     "ppc64"
634   };
635
636   unsigned Directive = Subtarget.getDarwinDirective();
637   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
638     Directive = PPC::DIR_970;
639   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
640     Directive = PPC::DIR_7400;
641   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
642     Directive = PPC::DIR_64;
643   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
644   O << "\t.machine " << CPUDirectives[Directive] << '\n';
645
646   // Prime text sections so they are adjacent.  This reduces the likelihood a
647   // large data or debug section causes a branch to exceed 16M limit.
648   TargetLoweringObjectFileMachO &TLOFMacho = 
649     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
650   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
651   if (TM.getRelocationModel() == Reloc::PIC_) {
652     OutStreamer.SwitchSection(
653             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
654                                       MCSectionMachO::S_SYMBOL_STUBS |
655                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
656                                       32, SectionKind::getText()));
657   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
658     OutStreamer.SwitchSection(
659             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
660                                       MCSectionMachO::S_SYMBOL_STUBS |
661                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
662                                       16, SectionKind::getText()));
663   }
664   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
665 }
666
667 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
668   // Remove $stub suffix, add $lazy_ptr.
669   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
670   TmpStr += "$lazy_ptr";
671   return Ctx.GetOrCreateSymbol(TmpStr.str());
672 }
673
674 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
675   // Add $tmp suffix to $stub, yielding $stub$tmp.
676   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
677   TmpStr += "$tmp";
678   return Ctx.GetOrCreateSymbol(TmpStr.str());
679 }
680
681 void PPCDarwinAsmPrinter::
682 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
683   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
684   
685   TargetLoweringObjectFileMachO &TLOFMacho = 
686     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
687
688   // .lazy_symbol_pointer
689   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
690   
691   // Output stubs for dynamically-linked functions
692   if (TM.getRelocationModel() == Reloc::PIC_) {
693     const MCSection *StubSection = 
694     TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
695                               MCSectionMachO::S_SYMBOL_STUBS |
696                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
697                               32, SectionKind::getText());
698     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
699       OutStreamer.SwitchSection(StubSection);
700       EmitAlignment(4);
701       
702       const MCSymbol *Stub = Stubs[i].first;
703       const MCSymbol *RawSym = Stubs[i].second;
704       const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
705       const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
706                                            
707       O << *Stub << ":\n";
708       O << "\t.indirect_symbol " << *RawSym << '\n';
709       O << "\tmflr r0\n";
710       O << "\tbcl 20,31," << *AnonSymbol << '\n';
711       O << *AnonSymbol << ":\n";
712       O << "\tmflr r11\n";
713       O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
714       << ")\n";
715       O << "\tmtlr r0\n";
716       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
717       << '-' << *AnonSymbol << ")(r11)\n";
718       O << "\tmtctr r12\n";
719       O << "\tbctr\n";
720       
721       OutStreamer.SwitchSection(LSPSection);
722       O << *LazyPtr << ":\n";
723       O << "\t.indirect_symbol " << *RawSym << '\n';
724       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
725     }
726     O << '\n';
727     return;
728   }
729   
730   const MCSection *StubSection =
731     TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
732                               MCSectionMachO::S_SYMBOL_STUBS |
733                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
734                               16, SectionKind::getText());
735   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
736     const MCSymbol *Stub = Stubs[i].first;
737     const MCSymbol *RawSym = Stubs[i].second;
738     const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
739
740     OutStreamer.SwitchSection(StubSection);
741     EmitAlignment(4);
742     O << *Stub << ":\n";
743     O << "\t.indirect_symbol " << *RawSym << '\n';
744     O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
745     O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(" << *LazyPtr
746     << ")(r11)\n";
747     O << "\tmtctr r12\n";
748     O << "\tbctr\n";
749     OutStreamer.SwitchSection(LSPSection);
750     O << *LazyPtr << ":\n";
751     O << "\t.indirect_symbol " << *RawSym << '\n';
752     O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
753   }
754   
755   O << '\n';
756 }
757
758
759 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
760   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
761
762   // Darwin/PPC always uses mach-o.
763   TargetLoweringObjectFileMachO &TLOFMacho = 
764     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
765   MachineModuleInfoMachO &MMIMacho =
766     MMI->getObjFileInfo<MachineModuleInfoMachO>();
767   
768   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
769   if (!Stubs.empty())
770     EmitFunctionStubs(Stubs);
771
772   if (MAI->doesSupportExceptionHandling() && MMI) {
773     // Add the (possibly multiple) personalities to the set of global values.
774     // Only referenced functions get into the Personalities list.
775     const std::vector<Function *> &Personalities = MMI->getPersonalities();
776     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
777          E = Personalities.end(); I != E; ++I) {
778       if (*I) {
779         const MCSymbol *NLPSym = 
780           GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
781         const MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
782         StubSym = GetGlobalValueSymbol(*I);
783       }
784     }
785   }
786
787   // Output stubs for dynamically-linked functions.
788   Stubs = MMIMacho.GetGVStubList();
789   
790   // Output macho stubs for external and common global variables.
791   if (!Stubs.empty()) {
792     // Switch with ".non_lazy_symbol_pointer" directive.
793     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
794     EmitAlignment(isPPC64 ? 3 : 2);
795     
796     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
797       O << *Stubs[i].first << ":\n";
798       O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
799       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
800     }
801   }
802
803   Stubs = MMIMacho.GetHiddenGVStubList();
804   if (!Stubs.empty()) {
805     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
806     EmitAlignment(isPPC64 ? 3 : 2);
807     
808     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
809       O << *Stubs[i].first << ":\n";
810       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
811     }
812   }
813
814   // Funny Darwin hack: This flag tells the linker that no global symbols
815   // contain code that falls through to other global symbols (e.g. the obvious
816   // implementation of multiple entry points).  If this doesn't occur, the
817   // linker can safely perform dead code stripping.  Since LLVM never generates
818   // code that does this, it is always safe to set.
819   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
820
821   return AsmPrinter::doFinalization(M);
822 }
823
824
825
826 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
827 /// for a MachineFunction to the given output stream, in a format that the
828 /// Darwin assembler can deal with.
829 ///
830 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
831                                            TargetMachine &tm,
832                                            MCContext &Ctx, MCStreamer &Streamer,
833                                            const MCAsmInfo *tai) {
834   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
835
836   if (Subtarget->isDarwin())
837     return new PPCDarwinAsmPrinter(o, tm, Ctx, Streamer, tai);
838   return new PPCLinuxAsmPrinter(o, tm, Ctx, Streamer, tai);
839 }
840
841 // Force static initialization.
842 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
843   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
844   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
845 }