bf2e693e89db1ab42872db2cbbfe64e7ca7dab53
[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             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           MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
215           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     MCSymbol *NLPSym = 
405       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
406                                    MO.getSymbolName()+"$non_lazy_ptr");
407     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         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         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       O << '\n';
559       return;
560     }
561   }
562   
563   if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
564       MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
565     O << "\tmr ";
566     printOperand(MI, 0);
567     O << ", ";
568     printOperand(MI, 1);
569     O << '\n';
570     return;
571   }
572   
573   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
577     if (63-SH == ME) {
578       O << "\tsldi ";
579       printOperand(MI, 0);
580       O << ", ";
581       printOperand(MI, 1);
582       O << ", " << (unsigned int)SH;
583       O << '\n';
584       return;
585     }
586   }
587
588   printInstruction(MI);
589   O << '\n';
590 }
591
592 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
593   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
594     return AsmPrinter::EmitFunctionEntryLabel();
595     
596   // Emit an official procedure descriptor.
597   // FIXME 64-bit SVR4: Use MCSection here!
598   O << "\t.section\t\".opd\",\"aw\"\n";
599   O << "\t.align 3\n";
600   OutStreamer.EmitLabel(CurrentFnSym);
601   O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
602   O << "\t.previous\n";
603   O << ".L." << *CurrentFnSym << ":\n";
604 }
605
606
607 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
608   const TargetData *TD = TM.getTargetData();
609
610   bool isPPC64 = TD->getPointerSizeInBits() == 64;
611
612   if (isPPC64 && !TOC.empty()) {
613     // FIXME 64-bit SVR4: Use MCSection here?
614     O << "\t.section\t\".toc\",\"aw\"\n";
615
616     // FIXME: This is nondeterminstic!
617     for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
618          E = TOC.end(); I != E; ++I) {
619       O << *I->second << ":\n";
620       O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
621     }
622   }
623
624   return AsmPrinter::doFinalization(M);
625 }
626
627 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
628   static const char *const CPUDirectives[] = {
629     "",
630     "ppc",
631     "ppc601",
632     "ppc602",
633     "ppc603",
634     "ppc7400",
635     "ppc750",
636     "ppc970",
637     "ppc64"
638   };
639
640   unsigned Directive = Subtarget.getDarwinDirective();
641   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
642     Directive = PPC::DIR_970;
643   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
644     Directive = PPC::DIR_7400;
645   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
646     Directive = PPC::DIR_64;
647   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
648   O << "\t.machine " << CPUDirectives[Directive] << '\n';
649
650   // Prime text sections so they are adjacent.  This reduces the likelihood a
651   // large data or debug section causes a branch to exceed 16M limit.
652   TargetLoweringObjectFileMachO &TLOFMacho = 
653     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
654   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
655   if (TM.getRelocationModel() == Reloc::PIC_) {
656     OutStreamer.SwitchSection(
657             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
658                                       MCSectionMachO::S_SYMBOL_STUBS |
659                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
660                                       32, SectionKind::getText()));
661   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
662     OutStreamer.SwitchSection(
663             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
664                                       MCSectionMachO::S_SYMBOL_STUBS |
665                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
666                                       16, SectionKind::getText()));
667   }
668   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
669 }
670
671 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
672   // Remove $stub suffix, add $lazy_ptr.
673   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
674   TmpStr += "$lazy_ptr";
675   return Ctx.GetOrCreateSymbol(TmpStr.str());
676 }
677
678 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
679   // Add $tmp suffix to $stub, yielding $stub$tmp.
680   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
681   TmpStr += "$tmp";
682   return Ctx.GetOrCreateSymbol(TmpStr.str());
683 }
684
685 void PPCDarwinAsmPrinter::
686 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
687   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
688   
689   TargetLoweringObjectFileMachO &TLOFMacho = 
690     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
691
692   // .lazy_symbol_pointer
693   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
694   
695   // Output stubs for dynamically-linked functions
696   if (TM.getRelocationModel() == Reloc::PIC_) {
697     const MCSection *StubSection = 
698     TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
699                               MCSectionMachO::S_SYMBOL_STUBS |
700                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
701                               32, SectionKind::getText());
702     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
703       OutStreamer.SwitchSection(StubSection);
704       EmitAlignment(4);
705       
706       const MCSymbol *Stub = Stubs[i].first;
707       const MCSymbol *RawSym = Stubs[i].second;
708       const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
709       const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
710                                            
711       O << *Stub << ":\n";
712       O << "\t.indirect_symbol " << *RawSym << '\n';
713       O << "\tmflr r0\n";
714       O << "\tbcl 20,31," << *AnonSymbol << '\n';
715       O << *AnonSymbol << ":\n";
716       O << "\tmflr r11\n";
717       O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
718       << ")\n";
719       O << "\tmtlr r0\n";
720       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
721       << '-' << *AnonSymbol << ")(r11)\n";
722       O << "\tmtctr r12\n";
723       O << "\tbctr\n";
724       
725       OutStreamer.SwitchSection(LSPSection);
726       O << *LazyPtr << ":\n";
727       O << "\t.indirect_symbol " << *RawSym << '\n';
728       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
729     }
730     O << '\n';
731     return;
732   }
733   
734   const MCSection *StubSection =
735     TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
736                               MCSectionMachO::S_SYMBOL_STUBS |
737                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
738                               16, SectionKind::getText());
739   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
740     const MCSymbol *Stub = Stubs[i].first;
741     const MCSymbol *RawSym = Stubs[i].second;
742     const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
743
744     OutStreamer.SwitchSection(StubSection);
745     EmitAlignment(4);
746     O << *Stub << ":\n";
747     O << "\t.indirect_symbol " << *RawSym << '\n';
748     O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
749     O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(" << *LazyPtr
750     << ")(r11)\n";
751     O << "\tmtctr r12\n";
752     O << "\tbctr\n";
753     OutStreamer.SwitchSection(LSPSection);
754     O << *LazyPtr << ":\n";
755     O << "\t.indirect_symbol " << *RawSym << '\n';
756     O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
757   }
758   
759   O << '\n';
760 }
761
762
763 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
764   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
765
766   // Darwin/PPC always uses mach-o.
767   TargetLoweringObjectFileMachO &TLOFMacho = 
768     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
769   MachineModuleInfoMachO &MMIMacho =
770     MMI->getObjFileInfo<MachineModuleInfoMachO>();
771   
772   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
773   if (!Stubs.empty())
774     EmitFunctionStubs(Stubs);
775
776   if (MAI->doesSupportExceptionHandling() && MMI) {
777     // Add the (possibly multiple) personalities to the set of global values.
778     // Only referenced functions get into the Personalities list.
779     const std::vector<Function *> &Personalities = MMI->getPersonalities();
780     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
781          E = Personalities.end(); I != E; ++I) {
782       if (*I) {
783         MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
784         MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
785         StubSym = GetGlobalValueSymbol(*I);
786       }
787     }
788   }
789
790   // Output stubs for dynamically-linked functions.
791   Stubs = MMIMacho.GetGVStubList();
792   
793   // Output macho stubs for external and common global variables.
794   if (!Stubs.empty()) {
795     // Switch with ".non_lazy_symbol_pointer" directive.
796     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
797     EmitAlignment(isPPC64 ? 3 : 2);
798     
799     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
800       O << *Stubs[i].first << ":\n";
801       O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
802       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
803     }
804   }
805
806   Stubs = MMIMacho.GetHiddenGVStubList();
807   if (!Stubs.empty()) {
808     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
809     EmitAlignment(isPPC64 ? 3 : 2);
810     
811     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
812       O << *Stubs[i].first << ":\n";
813       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
814     }
815   }
816
817   // Funny Darwin hack: This flag tells the linker that no global symbols
818   // contain code that falls through to other global symbols (e.g. the obvious
819   // implementation of multiple entry points).  If this doesn't occur, the
820   // linker can safely perform dead code stripping.  Since LLVM never generates
821   // code that does this, it is always safe to set.
822   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
823
824   return AsmPrinter::doFinalization(M);
825 }
826
827
828
829 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
830 /// for a MachineFunction to the given output stream, in a format that the
831 /// Darwin assembler can deal with.
832 ///
833 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
834                                            TargetMachine &tm,
835                                            MCContext &Ctx, MCStreamer &Streamer,
836                                            const MCAsmInfo *tai) {
837   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
838
839   if (Subtarget->isDarwin())
840     return new PPCDarwinAsmPrinter(o, tm, Ctx, Streamer, tai);
841   return new PPCLinuxAsmPrinter(o, tm, Ctx, Streamer, tai);
842 }
843
844 // Force static initialization.
845 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
846   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
847   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
848 }