[PowerPC] Remove VK_PPC_TLSGD and VK_PPC_TLSLD
[oota-llvm.git] / lib / Target / PowerPC / 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 "InstPrinter/PPCInstPrinter.h"
22 #include "MCTargetDesc/PPCPredicates.h"
23 #include "MCTargetDesc/PPCMCExpr.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "llvm/CodeGen/AsmPrinter.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
36 #include "llvm/DebugInfo.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/MCExpr.h"
43 #include "llvm/MC/MCInst.h"
44 #include "llvm/MC/MCInstBuilder.h"
45 #include "llvm/MC/MCSectionELF.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/MC/MCStreamer.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ELF.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/Mangler.h"
57 #include "llvm/Target/TargetInstrInfo.h"
58 #include "llvm/Target/TargetOptions.h"
59 #include "llvm/Target/TargetRegisterInfo.h"
60 using namespace llvm;
61
62 namespace {
63   class PPCAsmPrinter : public AsmPrinter {
64   protected:
65     MapVector<MCSymbol*, MCSymbol*> TOC;
66     const PPCSubtarget &Subtarget;
67     uint64_t TOCLabelID;
68   public:
69     explicit PPCAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
70       : AsmPrinter(TM, Streamer),
71         Subtarget(TM.getSubtarget<PPCSubtarget>()), TOCLabelID(0) {}
72
73     virtual const char *getPassName() const {
74       return "PowerPC Assembly Printer";
75     }
76
77     MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
78
79     virtual void EmitInstruction(const MachineInstr *MI);
80
81     void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
82
83     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
84                          unsigned AsmVariant, const char *ExtraCode,
85                          raw_ostream &O);
86     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
87                                unsigned AsmVariant, const char *ExtraCode,
88                                raw_ostream &O);
89   };
90
91   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
92   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
93   public:
94     explicit PPCLinuxAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
95       : PPCAsmPrinter(TM, Streamer) {}
96
97     virtual const char *getPassName() const {
98       return "Linux PPC Assembly Printer";
99     }
100
101     bool doFinalization(Module &M);
102
103     virtual void EmitFunctionEntryLabel();
104
105     void EmitFunctionBodyEnd();
106   };
107
108   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
109   /// OS X
110   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
111   public:
112     explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
113       : PPCAsmPrinter(TM, Streamer) {}
114
115     virtual const char *getPassName() const {
116       return "Darwin PPC Assembly Printer";
117     }
118
119     bool doFinalization(Module &M);
120     void EmitStartOfAsmFile(Module &M);
121
122     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
123   };
124 } // end of anonymous namespace
125
126 /// stripRegisterPrefix - This method strips the character prefix from a
127 /// register name so that only the number is left.  Used by for linux asm.
128 static const char *stripRegisterPrefix(const char *RegName) {
129   switch (RegName[0]) {
130     case 'r':
131     case 'f':
132     case 'v': return RegName + 1;
133     case 'c': if (RegName[1] == 'r') return RegName + 2;
134   }
135   
136   return RegName;
137 }
138
139 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
140                                  raw_ostream &O) {
141   const MachineOperand &MO = MI->getOperand(OpNo);
142   
143   switch (MO.getType()) {
144   case MachineOperand::MO_Register: {
145     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
146     // Linux assembler (Others?) does not take register mnemonics.
147     // FIXME - What about special registers used in mfspr/mtspr?
148     if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
149     O << RegName;
150     return;
151   }
152   case MachineOperand::MO_Immediate:
153     O << MO.getImm();
154     return;
155
156   case MachineOperand::MO_MachineBasicBlock:
157     O << *MO.getMBB()->getSymbol();
158     return;
159   case MachineOperand::MO_JumpTableIndex:
160     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
161       << '_' << MO.getIndex();
162     // FIXME: PIC relocation model
163     return;
164   case MachineOperand::MO_ConstantPoolIndex:
165     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
166       << '_' << MO.getIndex();
167     return;
168   case MachineOperand::MO_BlockAddress:
169     O << *GetBlockAddressSymbol(MO.getBlockAddress());
170     return;
171   case MachineOperand::MO_ExternalSymbol: {
172     // Computing the address of an external symbol, not calling it.
173     if (TM.getRelocationModel() == Reloc::Static) {
174       O << *GetExternalSymbolSymbol(MO.getSymbolName());
175       return;
176     }
177
178     MCSymbol *NLPSym = 
179       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
180                                    MO.getSymbolName()+"$non_lazy_ptr");
181     MachineModuleInfoImpl::StubValueTy &StubSym = 
182       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
183     if (StubSym.getPointer() == 0)
184       StubSym = MachineModuleInfoImpl::
185         StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
186     
187     O << *NLPSym;
188     return;
189   }
190   case MachineOperand::MO_GlobalAddress: {
191     // Computing the address of a global symbol, not calling it.
192     const GlobalValue *GV = MO.getGlobal();
193     MCSymbol *SymToPrint;
194
195     // External or weakly linked global variables need non-lazily-resolved stubs
196     if (TM.getRelocationModel() != Reloc::Static &&
197         (GV->isDeclaration() || GV->isWeakForLinker())) {
198       if (!GV->hasHiddenVisibility()) {
199         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
200         MachineModuleInfoImpl::StubValueTy &StubSym = 
201           MMI->getObjFileInfo<MachineModuleInfoMachO>()
202             .getGVStubEntry(SymToPrint);
203         if (StubSym.getPointer() == 0)
204           StubSym = MachineModuleInfoImpl::
205             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
206       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
207                  GV->hasAvailableExternallyLinkage()) {
208         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
209         
210         MachineModuleInfoImpl::StubValueTy &StubSym = 
211           MMI->getObjFileInfo<MachineModuleInfoMachO>().
212                     getHiddenGVStubEntry(SymToPrint);
213         if (StubSym.getPointer() == 0)
214           StubSym = MachineModuleInfoImpl::
215             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
216       } else {
217         SymToPrint = Mang->getSymbol(GV);
218       }
219     } else {
220       SymToPrint = Mang->getSymbol(GV);
221     }
222     
223     O << *SymToPrint;
224
225     printOffset(MO.getOffset(), O);
226     return;
227   }
228
229   default:
230     O << "<unknown operand type: " << MO.getType() << ">";
231     return;
232   }
233 }
234
235 /// PrintAsmOperand - Print out an operand for an inline asm expression.
236 ///
237 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
238                                     unsigned AsmVariant,
239                                     const char *ExtraCode, raw_ostream &O) {
240   // Does this asm operand have a single letter operand modifier?
241   if (ExtraCode && ExtraCode[0]) {
242     if (ExtraCode[1] != 0) return true; // Unknown modifier.
243
244     switch (ExtraCode[0]) {
245     default:
246       // See if this is a generic print operand
247       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
248     case 'c': // Don't print "$" before a global var name or constant.
249       break; // PPC never has a prefix.
250     case 'L': // Write second word of DImode reference.
251       // Verify that this operand has two consecutive registers.
252       if (!MI->getOperand(OpNo).isReg() ||
253           OpNo+1 == MI->getNumOperands() ||
254           !MI->getOperand(OpNo+1).isReg())
255         return true;
256       ++OpNo;   // Return the high-part.
257       break;
258     case 'I':
259       // Write 'i' if an integer constant, otherwise nothing.  Used to print
260       // addi vs add, etc.
261       if (MI->getOperand(OpNo).isImm())
262         O << "i";
263       return false;
264     }
265   }
266
267   printOperand(MI, OpNo, O);
268   return false;
269 }
270
271 // At the moment, all inline asm memory operands are a single register.
272 // In any case, the output of this routine should always be just one
273 // assembler operand.
274
275 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
276                                           unsigned AsmVariant,
277                                           const char *ExtraCode,
278                                           raw_ostream &O) {
279   if (ExtraCode && ExtraCode[0]) {
280     if (ExtraCode[1] != 0) return true; // Unknown modifier.
281
282     switch (ExtraCode[0]) {
283     default: return true;  // Unknown modifier.
284     case 'y': // A memory reference for an X-form instruction
285       {
286         const char *RegName = "r0";
287         if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
288         O << RegName << ", ";
289         printOperand(MI, OpNo, O);
290         return false;
291       }
292     }
293   }
294
295   assert(MI->getOperand(OpNo).isReg());
296   O << "0(";
297   printOperand(MI, OpNo, O);
298   O << ")";
299   return false;
300 }
301
302
303 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
304 /// exists for it.  If not, create one.  Then return a symbol that references
305 /// the TOC entry.
306 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
307
308   MCSymbol *&TOCEntry = TOC[Sym];
309
310   // To avoid name clash check if the name already exists.
311   while (TOCEntry == 0) {
312     if (OutContext.LookupSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
313                                 "C" + Twine(TOCLabelID++)) == 0) {
314       TOCEntry = GetTempSymbol("C", TOCLabelID);
315     }
316   }
317
318   return TOCEntry;
319 }
320
321
322 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
323 /// the current output stream.
324 ///
325 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
326   MCInst TmpInst;
327   
328   // Lower multi-instruction pseudo operations.
329   switch (MI->getOpcode()) {
330   default: break;
331   case TargetOpcode::DBG_VALUE:
332     llvm_unreachable("Should be handled target independently");
333   case PPC::MovePCtoLR:
334   case PPC::MovePCtoLR8: {
335     // Transform %LR = MovePCtoLR
336     // Into this, where the label is the PIC base: 
337     //     bl L1$pb
338     // L1$pb:
339     MCSymbol *PICBase = MF->getPICBaseSymbol();
340     
341     // Emit the 'bl'.
342     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL)
343       // FIXME: We would like an efficient form for this, so we don't have to do
344       // a lot of extra uniquing.
345       .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
346     
347     // Emit the label.
348     OutStreamer.EmitLabel(PICBase);
349     return;
350   }
351   case PPC::LDtocJTI:
352   case PPC::LDtocCPT:
353   case PPC::LDtoc: {
354     // Transform %X3 = LDtoc <ga:@min1>, %X2
355     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
356
357     // Change the opcode to LD, and the global address operand to be a
358     // reference to the TOC entry we will synthesize later.
359     TmpInst.setOpcode(PPC::LD);
360     const MachineOperand &MO = MI->getOperand(1);
361
362     // Map symbol -> label of TOC entry
363     assert(MO.isGlobal() || MO.isCPI() || MO.isJTI());
364     MCSymbol *MOSymbol = 0;
365     if (MO.isGlobal())
366       MOSymbol = Mang->getSymbol(MO.getGlobal());
367     else if (MO.isCPI())
368       MOSymbol = GetCPISymbol(MO.getIndex());
369     else if (MO.isJTI())
370       MOSymbol = GetJTISymbol(MO.getIndex());
371
372     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
373
374     const MCExpr *Exp =
375       MCSymbolRefExpr::Create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC,
376                               OutContext);
377     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
378     OutStreamer.EmitInstruction(TmpInst);
379     return;
380   }
381       
382   case PPC::ADDIStocHA: {
383     // Transform %Xd = ADDIStocHA %X2, <ga:@sym>
384     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
385
386     // Change the opcode to ADDIS8.  If the global address is external,
387     // has common linkage, is a function address, or is a jump table
388     // address, then generate a TOC entry and reference that.  Otherwise
389     // reference the symbol directly.
390     TmpInst.setOpcode(PPC::ADDIS8);
391     const MachineOperand &MO = MI->getOperand(2);
392     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI()) &&
393            "Invalid operand for ADDIStocHA!");
394     MCSymbol *MOSymbol = 0;
395     bool IsExternal = false;
396     bool IsFunction = false;
397     bool IsCommon = false;
398     bool IsAvailExt = false;
399
400     if (MO.isGlobal()) {
401       const GlobalValue *GValue = MO.getGlobal();
402       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
403       const GlobalValue *RealGValue = GAlias ?
404         GAlias->resolveAliasedGlobal(false) : GValue;
405       MOSymbol = Mang->getSymbol(RealGValue);
406       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
407       IsExternal = GVar && !GVar->hasInitializer();
408       IsCommon = GVar && RealGValue->hasCommonLinkage();
409       IsFunction = !GVar;
410       IsAvailExt = GVar && RealGValue->hasAvailableExternallyLinkage();
411     } else if (MO.isCPI())
412       MOSymbol = GetCPISymbol(MO.getIndex());
413     else if (MO.isJTI())
414       MOSymbol = GetJTISymbol(MO.getIndex());
415
416     if (IsExternal || IsFunction || IsCommon || IsAvailExt || MO.isJTI())
417       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
418
419     const MCExpr *Exp =
420       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_HA,
421                               OutContext);
422     TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
423     OutStreamer.EmitInstruction(TmpInst);
424     return;
425   }
426   case PPC::LDtocL: {
427     // Transform %Xd = LDtocL <ga:@sym>, %Xs
428     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
429
430     // Change the opcode to LD.  If the global address is external, has
431     // common linkage, or is a jump table address, then reference the
432     // associated TOC entry.  Otherwise reference the symbol directly.
433     TmpInst.setOpcode(PPC::LD);
434     const MachineOperand &MO = MI->getOperand(1);
435     assert((MO.isGlobal() || MO.isJTI() || MO.isCPI()) &&
436            "Invalid operand for LDtocL!");
437     MCSymbol *MOSymbol = 0;
438
439     if (MO.isJTI())
440       MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
441     else if (MO.isCPI())
442       MOSymbol = GetCPISymbol(MO.getIndex());
443     else if (MO.isGlobal()) {
444       const GlobalValue *GValue = MO.getGlobal();
445       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
446       const GlobalValue *RealGValue = GAlias ?
447         GAlias->resolveAliasedGlobal(false) : GValue;
448       MOSymbol = Mang->getSymbol(RealGValue);
449       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
450     
451       if (!GVar || !GVar->hasInitializer() || RealGValue->hasCommonLinkage() ||
452           RealGValue->hasAvailableExternallyLinkage())
453         MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
454     }
455
456     const MCExpr *Exp =
457       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
458                               OutContext);
459     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
460     OutStreamer.EmitInstruction(TmpInst);
461     return;
462   }
463   case PPC::ADDItocL: {
464     // Transform %Xd = ADDItocL %Xs, <ga:@sym>
465     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
466
467     // Change the opcode to ADDI8.  If the global address is external, then
468     // generate a TOC entry and reference that.  Otherwise reference the
469     // symbol directly.
470     TmpInst.setOpcode(PPC::ADDI8);
471     const MachineOperand &MO = MI->getOperand(2);
472     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
473     MCSymbol *MOSymbol = 0;
474     bool IsExternal = false;
475     bool IsFunction = false;
476
477     if (MO.isGlobal()) {
478       const GlobalValue *GValue = MO.getGlobal();
479       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
480       const GlobalValue *RealGValue = GAlias ?
481         GAlias->resolveAliasedGlobal(false) : GValue;
482       MOSymbol = Mang->getSymbol(RealGValue);
483       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
484       IsExternal = GVar && !GVar->hasInitializer();
485       IsFunction = !GVar;
486     } else if (MO.isCPI())
487       MOSymbol = GetCPISymbol(MO.getIndex());
488
489     if (IsFunction || IsExternal)
490       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
491
492     const MCExpr *Exp =
493       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
494                               OutContext);
495     TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
496     OutStreamer.EmitInstruction(TmpInst);
497     return;
498   }
499   case PPC::ADDISgotTprelHA: {
500     // Transform: %Xd = ADDISgotTprelHA %X2, <ga:@sym>
501     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
502     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
503     const MachineOperand &MO = MI->getOperand(2);
504     const GlobalValue *GValue = MO.getGlobal();
505     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
506     const MCExpr *SymGotTprel =
507       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
508                               OutContext);
509     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
510                                 .addReg(MI->getOperand(0).getReg())
511                                 .addReg(PPC::X2)
512                                 .addExpr(SymGotTprel));
513     return;
514   }
515   case PPC::LDgotTprelL: {
516     // Transform %Xd = LDgotTprelL <ga:@sym>, %Xs
517     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
518
519     // Change the opcode to LD.
520     TmpInst.setOpcode(PPC::LD);
521     const MachineOperand &MO = MI->getOperand(1);
522     const GlobalValue *GValue = MO.getGlobal();
523     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
524     const MCExpr *Exp =
525       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO,
526                               OutContext);
527     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
528     OutStreamer.EmitInstruction(TmpInst);
529     return;
530   }
531   case PPC::ADDIStlsgdHA: {
532     // Transform: %Xd = ADDIStlsgdHA %X2, <ga:@sym>
533     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
534     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
535     const MachineOperand &MO = MI->getOperand(2);
536     const GlobalValue *GValue = MO.getGlobal();
537     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
538     const MCExpr *SymGotTlsGD =
539       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
540                               OutContext);
541     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
542                                 .addReg(MI->getOperand(0).getReg())
543                                 .addReg(PPC::X2)
544                                 .addExpr(SymGotTlsGD));
545     return;
546   }
547   case PPC::ADDItlsgdL: {
548     // Transform: %Xd = ADDItlsgdL %Xs, <ga:@sym>
549     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsgd@l
550     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
551     const MachineOperand &MO = MI->getOperand(2);
552     const GlobalValue *GValue = MO.getGlobal();
553     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
554     const MCExpr *SymGotTlsGD =
555       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO,
556                               OutContext);
557     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8)
558                                 .addReg(MI->getOperand(0).getReg())
559                                 .addReg(MI->getOperand(1).getReg())
560                                 .addExpr(SymGotTlsGD));
561     return;
562   }
563   case PPC::GETtlsADDR: {
564     // Transform: %X3 = GETtlsADDR %X3, <ga:@sym>
565     // Into:      BL8_NOP_TLSGD __tls_get_addr(sym@tlsgd)
566     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
567
568     StringRef Name = "__tls_get_addr";
569     MCSymbol *TlsGetAddr = OutContext.GetOrCreateSymbol(Name);
570     const MCSymbolRefExpr *TlsRef = 
571       MCSymbolRefExpr::Create(TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
572     const MachineOperand &MO = MI->getOperand(2);
573     const GlobalValue *GValue = MO.getGlobal();
574     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
575     const MCExpr *SymVar =
576       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_TLSGD, OutContext);
577     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL8_NOP_TLSGD)
578                                 .addExpr(TlsRef)
579                                 .addExpr(SymVar));
580     return;
581   }
582   case PPC::ADDIStlsldHA: {
583     // Transform: %Xd = ADDIStlsldHA %X2, <ga:@sym>
584     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsld@ha
585     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
586     const MachineOperand &MO = MI->getOperand(2);
587     const GlobalValue *GValue = MO.getGlobal();
588     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
589     const MCExpr *SymGotTlsLD =
590       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
591                               OutContext);
592     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
593                                 .addReg(MI->getOperand(0).getReg())
594                                 .addReg(PPC::X2)
595                                 .addExpr(SymGotTlsLD));
596     return;
597   }
598   case PPC::ADDItlsldL: {
599     // Transform: %Xd = ADDItlsldL %Xs, <ga:@sym>
600     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsld@l
601     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
602     const MachineOperand &MO = MI->getOperand(2);
603     const GlobalValue *GValue = MO.getGlobal();
604     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
605     const MCExpr *SymGotTlsLD =
606       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO,
607                               OutContext);
608     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8)
609                                 .addReg(MI->getOperand(0).getReg())
610                                 .addReg(MI->getOperand(1).getReg())
611                                 .addExpr(SymGotTlsLD));
612     return;
613   }
614   case PPC::GETtlsldADDR: {
615     // Transform: %X3 = GETtlsldADDR %X3, <ga:@sym>
616     // Into:      BL8_NOP_TLSLD __tls_get_addr(sym@tlsld)
617     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
618
619     StringRef Name = "__tls_get_addr";
620     MCSymbol *TlsGetAddr = OutContext.GetOrCreateSymbol(Name);
621     const MCSymbolRefExpr *TlsRef = 
622       MCSymbolRefExpr::Create(TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
623     const MachineOperand &MO = MI->getOperand(2);
624     const GlobalValue *GValue = MO.getGlobal();
625     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
626     const MCExpr *SymVar =
627       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_TLSLD, OutContext);
628     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL8_NOP_TLSLD)
629                                 .addExpr(TlsRef)
630                                 .addExpr(SymVar));
631     return;
632   }
633   case PPC::ADDISdtprelHA: {
634     // Transform: %Xd = ADDISdtprelHA %X3, <ga:@sym>
635     // Into:      %Xd = ADDIS8 %X3, sym@dtprel@ha
636     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
637     const MachineOperand &MO = MI->getOperand(2);
638     const GlobalValue *GValue = MO.getGlobal();
639     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
640     const MCExpr *SymDtprel =
641       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
642                               OutContext);
643     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
644                                 .addReg(MI->getOperand(0).getReg())
645                                 .addReg(PPC::X3)
646                                 .addExpr(SymDtprel));
647     return;
648   }
649   case PPC::ADDIdtprelL: {
650     // Transform: %Xd = ADDIdtprelL %Xs, <ga:@sym>
651     // Into:      %Xd = ADDI8 %Xs, sym@dtprel@l
652     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
653     const MachineOperand &MO = MI->getOperand(2);
654     const GlobalValue *GValue = MO.getGlobal();
655     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
656     const MCExpr *SymDtprel =
657       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
658                               OutContext);
659     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8)
660                                 .addReg(MI->getOperand(0).getReg())
661                                 .addReg(MI->getOperand(1).getReg())
662                                 .addExpr(SymDtprel));
663     return;
664   }
665   case PPC::MFCRpseud:
666   case PPC::MFCR8pseud:
667     // Transform: %R3 = MFCRpseud %CR7
668     // Into:      %R3 = MFCR      ;; cr7
669     OutStreamer.AddComment(PPCInstPrinter::
670                            getRegisterName(MI->getOperand(1).getReg()));
671     OutStreamer.EmitInstruction(MCInstBuilder(Subtarget.isPPC64() ? PPC::MFCR8 : PPC::MFCR)
672       .addReg(MI->getOperand(0).getReg()));
673     return;
674   case PPC::SYNC:
675     // In Book E sync is called msync, handle this special case here...
676     if (Subtarget.isBookE()) {
677       OutStreamer.EmitRawText(StringRef("\tmsync"));
678       return;
679     }
680     break;
681   case PPC::LD:
682   case PPC::STD:
683   case PPC::LWA: {
684     // Verify alignment is legal, so we don't create relocations
685     // that can't be supported.
686     // FIXME:  This test is currently disabled for Darwin.  The test
687     // suite shows a handful of test cases that fail this check for
688     // Darwin.  Those need to be investigated before this sanity test
689     // can be enabled for those subtargets.
690     if (!Subtarget.isDarwin()) {
691       unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
692       const MachineOperand &MO = MI->getOperand(OpNum);
693       if (MO.isGlobal() && MO.getGlobal()->getAlignment() < 4)
694         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
695     }
696     // Now process the instruction normally.
697     break;
698   }
699   }
700
701   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
702   OutStreamer.EmitInstruction(TmpInst);
703 }
704
705 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
706   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
707     return AsmPrinter::EmitFunctionEntryLabel();
708     
709   // Emit an official procedure descriptor.
710   MCSectionSubPair Current = OutStreamer.getCurrentSection();
711   const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".opd",
712       ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
713       SectionKind::getReadOnly());
714   OutStreamer.SwitchSection(Section);
715   OutStreamer.EmitLabel(CurrentFnSym);
716   OutStreamer.EmitValueToAlignment(8);
717   MCSymbol *Symbol1 = 
718     OutContext.GetOrCreateSymbol(".L." + Twine(CurrentFnSym->getName()));
719   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
720   // entry point.
721   OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol1, OutContext),
722                         8 /*size*/);
723   MCSymbol *Symbol2 = OutContext.GetOrCreateSymbol(StringRef(".TOC."));
724   // Generates a R_PPC64_TOC relocation for TOC base insertion.
725   OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol2,
726                         MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
727                         8/*size*/);
728   // Emit a null environment pointer.
729   OutStreamer.EmitIntValue(0, 8 /* size */);
730   OutStreamer.SwitchSection(Current.first, Current.second);
731
732   MCSymbol *RealFnSym = OutContext.GetOrCreateSymbol(
733                           ".L." + Twine(CurrentFnSym->getName()));
734   OutStreamer.EmitLabel(RealFnSym);
735   CurrentFnSymForSize = RealFnSym;
736 }
737
738
739 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
740   const DataLayout *TD = TM.getDataLayout();
741
742   bool isPPC64 = TD->getPointerSizeInBits() == 64;
743
744   if (isPPC64 && !TOC.empty()) {
745     const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".toc",
746         ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
747         SectionKind::getReadOnly());
748     OutStreamer.SwitchSection(Section);
749
750     for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
751          E = TOC.end(); I != E; ++I) {
752       OutStreamer.EmitLabel(I->second);
753       MCSymbol *S = OutContext.GetOrCreateSymbol(I->first->getName());
754       OutStreamer.EmitTCEntry(*S);
755     }
756   }
757
758   MachineModuleInfoELF &MMIELF =
759     MMI->getObjFileInfo<MachineModuleInfoELF>();
760
761   MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
762   if (!Stubs.empty()) {
763     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
764     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
765       // L_foo$stub:
766       OutStreamer.EmitLabel(Stubs[i].first);
767       //   .long _foo
768       OutStreamer.EmitValue(MCSymbolRefExpr::Create(Stubs[i].second.getPointer(),
769                                                     OutContext),
770                             isPPC64 ? 8 : 4/*size*/);
771     }
772
773     Stubs.clear();
774     OutStreamer.AddBlankLine();
775   }
776
777   return AsmPrinter::doFinalization(M);
778 }
779
780 /// EmitFunctionBodyEnd - Print the traceback table before the .size
781 /// directive.
782 ///
783 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
784   // Only the 64-bit target requires a traceback table.  For now,
785   // we only emit the word of zeroes that GDB requires to find
786   // the end of the function, and zeroes for the eight-byte
787   // mandatory fields.
788   // FIXME: We should fill in the eight-byte mandatory fields as described in
789   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
790   // currently make use of these fields).
791   if (Subtarget.isPPC64()) {
792     OutStreamer.EmitIntValue(0, 4/*size*/);
793     OutStreamer.EmitIntValue(0, 8/*size*/);
794   }
795 }
796
797 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
798   static const char *const CPUDirectives[] = {
799     "",
800     "ppc",
801     "ppc440",
802     "ppc601",
803     "ppc602",
804     "ppc603",
805     "ppc7400",
806     "ppc750",
807     "ppc970",
808     "ppcA2",
809     "ppce500mc",
810     "ppce5500",
811     "power3",
812     "power4",
813     "power5",
814     "power5x",
815     "power6",
816     "power6x",
817     "power7",
818     "ppc64"
819   };
820
821   unsigned Directive = Subtarget.getDarwinDirective();
822   if (Subtarget.hasMFOCRF() && Directive < PPC::DIR_970)
823     Directive = PPC::DIR_970;
824   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
825     Directive = PPC::DIR_7400;
826   if (Subtarget.isPPC64() && Directive < PPC::DIR_64)
827     Directive = PPC::DIR_64;
828   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
829   
830   // FIXME: This is a total hack, finish mc'izing the PPC backend.
831   if (OutStreamer.hasRawTextSupport()) {
832     assert(Directive < sizeof(CPUDirectives) / sizeof(*CPUDirectives) &&
833            "CPUDirectives[] might not be up-to-date!");
834     OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
835   }
836
837   // Prime text sections so they are adjacent.  This reduces the likelihood a
838   // large data or debug section causes a branch to exceed 16M limit.
839   const TargetLoweringObjectFileMachO &TLOFMacho = 
840     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
841   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
842   if (TM.getRelocationModel() == Reloc::PIC_) {
843     OutStreamer.SwitchSection(
844            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
845                                       MCSectionMachO::S_SYMBOL_STUBS |
846                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
847                                       32, SectionKind::getText()));
848   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
849     OutStreamer.SwitchSection(
850            OutContext.getMachOSection("__TEXT","__symbol_stub1",
851                                       MCSectionMachO::S_SYMBOL_STUBS |
852                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
853                                       16, SectionKind::getText()));
854   }
855   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
856 }
857
858 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
859   // Remove $stub suffix, add $lazy_ptr.
860   StringRef NoStub = Sym->getName().substr(0, Sym->getName().size()-5);
861   return Ctx.GetOrCreateSymbol(NoStub + "$lazy_ptr");
862 }
863
864 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
865   // Add $tmp suffix to $stub, yielding $stub$tmp.
866   return Ctx.GetOrCreateSymbol(Sym->getName() + "$tmp");
867 }
868
869 void PPCDarwinAsmPrinter::
870 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
871   bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
872   
873   const TargetLoweringObjectFileMachO &TLOFMacho = 
874     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
875
876   // .lazy_symbol_pointer
877   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
878   
879   // Output stubs for dynamically-linked functions
880   if (TM.getRelocationModel() == Reloc::PIC_) {
881     const MCSection *StubSection = 
882     OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
883                                MCSectionMachO::S_SYMBOL_STUBS |
884                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
885                                32, SectionKind::getText());
886     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
887       OutStreamer.SwitchSection(StubSection);
888       EmitAlignment(4);
889       
890       MCSymbol *Stub = Stubs[i].first;
891       MCSymbol *RawSym = Stubs[i].second.getPointer();
892       MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
893       MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
894                                            
895       OutStreamer.EmitLabel(Stub);
896       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
897
898       const MCExpr *Anon = MCSymbolRefExpr::Create(AnonSymbol, OutContext);
899       const MCExpr *LazyPtrExpr = MCSymbolRefExpr::Create(LazyPtr, OutContext);
900       const MCExpr *Sub =
901         MCBinaryExpr::CreateSub(LazyPtrExpr, Anon, OutContext);
902
903       // mflr r0
904       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R0));
905       // bcl 20, 31, AnonSymbol
906       OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCLalways).addExpr(Anon));
907       OutStreamer.EmitLabel(AnonSymbol);
908       // mflr r11
909       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R11));
910       // addis r11, r11, ha16(LazyPtr - AnonSymbol)
911       const MCExpr *SubHa16 = PPCMCExpr::CreateHa(Sub, OutContext);
912       OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS)
913         .addReg(PPC::R11)
914         .addReg(PPC::R11)
915         .addExpr(SubHa16));
916       // mtlr r0
917       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTLR).addReg(PPC::R0));
918
919       // ldu r12, lo16(LazyPtr - AnonSymbol)(r11)
920       // lwzu r12, lo16(LazyPtr - AnonSymbol)(r11)
921       const MCExpr *SubLo16 = PPCMCExpr::CreateLo(Sub, OutContext);
922       OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
923         .addReg(PPC::R12)
924         .addExpr(SubLo16).addExpr(SubLo16)
925         .addReg(PPC::R11));
926       // mtctr r12
927       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
928       // bctr
929       OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
930
931       OutStreamer.SwitchSection(LSPSection);
932       OutStreamer.EmitLabel(LazyPtr);
933       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
934
935       MCSymbol *DyldStubBindingHelper =
936         OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
937       if (isPPC64) {
938         // .quad dyld_stub_binding_helper
939         OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
940       } else {
941         // .long dyld_stub_binding_helper
942         OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
943       }
944     }
945     OutStreamer.AddBlankLine();
946     return;
947   }
948   
949   const MCSection *StubSection =
950     OutContext.getMachOSection("__TEXT","__symbol_stub1",
951                                MCSectionMachO::S_SYMBOL_STUBS |
952                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
953                                16, SectionKind::getText());
954   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
955     MCSymbol *Stub = Stubs[i].first;
956     MCSymbol *RawSym = Stubs[i].second.getPointer();
957     MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
958     const MCExpr *LazyPtrExpr = MCSymbolRefExpr::Create(LazyPtr, OutContext);
959
960     OutStreamer.SwitchSection(StubSection);
961     EmitAlignment(4);
962     OutStreamer.EmitLabel(Stub);
963     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
964
965     // lis r11, ha16(LazyPtr)
966     const MCExpr *LazyPtrHa16 = PPCMCExpr::CreateHa(LazyPtrExpr, OutContext);
967     OutStreamer.EmitInstruction(MCInstBuilder(PPC::LIS)
968       .addReg(PPC::R11)
969       .addExpr(LazyPtrHa16));
970
971     // ldu r12, lo16(LazyPtr)(r11)
972     // lwzu r12, lo16(LazyPtr)(r11)
973     const MCExpr *LazyPtrLo16 = PPCMCExpr::CreateLo(LazyPtrExpr, OutContext);
974     OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
975       .addReg(PPC::R12)
976       .addExpr(LazyPtrLo16).addExpr(LazyPtrLo16)
977       .addReg(PPC::R11));
978
979     // mtctr r12
980     OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
981     // bctr
982     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
983
984     OutStreamer.SwitchSection(LSPSection);
985     OutStreamer.EmitLabel(LazyPtr);
986     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
987
988     MCSymbol *DyldStubBindingHelper =
989       OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
990     if (isPPC64) {
991       // .quad dyld_stub_binding_helper
992       OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
993     } else {
994       // .long dyld_stub_binding_helper
995       OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
996     }
997   }
998   
999   OutStreamer.AddBlankLine();
1000 }
1001
1002
1003 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1004   bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
1005
1006   // Darwin/PPC always uses mach-o.
1007   const TargetLoweringObjectFileMachO &TLOFMacho = 
1008     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1009   MachineModuleInfoMachO &MMIMacho =
1010     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1011   
1012   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
1013   if (!Stubs.empty())
1014     EmitFunctionStubs(Stubs);
1015
1016   if (MAI->doesSupportExceptionHandling() && MMI) {
1017     // Add the (possibly multiple) personalities to the set of global values.
1018     // Only referenced functions get into the Personalities list.
1019     const std::vector<const Function*> &Personalities = MMI->getPersonalities();
1020     for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
1021          E = Personalities.end(); I != E; ++I) {
1022       if (*I) {
1023         MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
1024         MachineModuleInfoImpl::StubValueTy &StubSym =
1025           MMIMacho.getGVStubEntry(NLPSym);
1026         StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
1027       }
1028     }
1029   }
1030
1031   // Output stubs for dynamically-linked functions.
1032   Stubs = MMIMacho.GetGVStubList();
1033   
1034   // Output macho stubs for external and common global variables.
1035   if (!Stubs.empty()) {
1036     // Switch with ".non_lazy_symbol_pointer" directive.
1037     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1038     EmitAlignment(isPPC64 ? 3 : 2);
1039     
1040     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1041       // L_foo$stub:
1042       OutStreamer.EmitLabel(Stubs[i].first);
1043       //   .indirect_symbol _foo
1044       MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1045       OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
1046
1047       if (MCSym.getInt())
1048         // External to current translation unit.
1049         OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/);
1050       else
1051         // Internal to current translation unit.
1052         //
1053         // When we place the LSDA into the TEXT section, the type info pointers
1054         // need to be indirect and pc-rel. We accomplish this by using NLPs.
1055         // However, sometimes the types are local to the file. So we need to
1056         // fill in the value for the NLP in those cases.
1057         OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
1058                                                       OutContext),
1059                               isPPC64 ? 8 : 4/*size*/);
1060     }
1061
1062     Stubs.clear();
1063     OutStreamer.AddBlankLine();
1064   }
1065
1066   Stubs = MMIMacho.GetHiddenGVStubList();
1067   if (!Stubs.empty()) {
1068     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1069     EmitAlignment(isPPC64 ? 3 : 2);
1070     
1071     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1072       // L_foo$stub:
1073       OutStreamer.EmitLabel(Stubs[i].first);
1074       //   .long _foo
1075       OutStreamer.EmitValue(MCSymbolRefExpr::
1076                             Create(Stubs[i].second.getPointer(),
1077                                    OutContext),
1078                             isPPC64 ? 8 : 4/*size*/);
1079     }
1080
1081     Stubs.clear();
1082     OutStreamer.AddBlankLine();
1083   }
1084
1085   // Funny Darwin hack: This flag tells the linker that no global symbols
1086   // contain code that falls through to other global symbols (e.g. the obvious
1087   // implementation of multiple entry points).  If this doesn't occur, the
1088   // linker can safely perform dead code stripping.  Since LLVM never generates
1089   // code that does this, it is always safe to set.
1090   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1091
1092   return AsmPrinter::doFinalization(M);
1093 }
1094
1095 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1096 /// for a MachineFunction to the given output stream, in a format that the
1097 /// Darwin assembler can deal with.
1098 ///
1099 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
1100                                            MCStreamer &Streamer) {
1101   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1102
1103   if (Subtarget->isDarwin())
1104     return new PPCDarwinAsmPrinter(tm, Streamer);
1105   return new PPCLinuxAsmPrinter(tm, Streamer);
1106 }
1107
1108 // Force static initialization.
1109 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1110   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1111   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1112 }