[PowerPC] Fix problems with large code model (PR17169).
[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, Subtarget.isDarwin());
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, Subtarget.isDarwin());
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         TM.getCodeModel() == CodeModel::Large)
418       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
419
420     const MCExpr *Exp =
421       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_HA,
422                               OutContext);
423     TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
424     OutStreamer.EmitInstruction(TmpInst);
425     return;
426   }
427   case PPC::LDtocL: {
428     // Transform %Xd = LDtocL <ga:@sym>, %Xs
429     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
430
431     // Change the opcode to LD.  If the global address is external, has
432     // common linkage, or is a jump table address, then reference the
433     // associated TOC entry.  Otherwise reference the symbol directly.
434     TmpInst.setOpcode(PPC::LD);
435     const MachineOperand &MO = MI->getOperand(1);
436     assert((MO.isGlobal() || MO.isJTI() || MO.isCPI()) &&
437            "Invalid operand for LDtocL!");
438     MCSymbol *MOSymbol = 0;
439
440     if (MO.isJTI())
441       MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
442     else if (MO.isCPI()) {
443       MOSymbol = GetCPISymbol(MO.getIndex());
444       if (TM.getCodeModel() == CodeModel::Large)
445         MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
446     }
447     else if (MO.isGlobal()) {
448       const GlobalValue *GValue = MO.getGlobal();
449       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
450       const GlobalValue *RealGValue = GAlias ?
451         GAlias->resolveAliasedGlobal(false) : GValue;
452       MOSymbol = Mang->getSymbol(RealGValue);
453       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
454     
455       if (!GVar || !GVar->hasInitializer() || RealGValue->hasCommonLinkage() ||
456           RealGValue->hasAvailableExternallyLinkage() ||
457           TM.getCodeModel() == CodeModel::Large)
458         MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
459     }
460
461     const MCExpr *Exp =
462       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
463                               OutContext);
464     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
465     OutStreamer.EmitInstruction(TmpInst);
466     return;
467   }
468   case PPC::ADDItocL: {
469     // Transform %Xd = ADDItocL %Xs, <ga:@sym>
470     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
471
472     // Change the opcode to ADDI8.  If the global address is external, then
473     // generate a TOC entry and reference that.  Otherwise reference the
474     // symbol directly.
475     TmpInst.setOpcode(PPC::ADDI8);
476     const MachineOperand &MO = MI->getOperand(2);
477     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
478     MCSymbol *MOSymbol = 0;
479     bool IsExternal = false;
480     bool IsFunction = false;
481
482     if (MO.isGlobal()) {
483       const GlobalValue *GValue = MO.getGlobal();
484       const GlobalAlias *GAlias = dyn_cast<GlobalAlias>(GValue);
485       const GlobalValue *RealGValue = GAlias ?
486         GAlias->resolveAliasedGlobal(false) : GValue;
487       MOSymbol = Mang->getSymbol(RealGValue);
488       const GlobalVariable *GVar = dyn_cast<GlobalVariable>(RealGValue);
489       IsExternal = GVar && !GVar->hasInitializer();
490       IsFunction = !GVar;
491     } else if (MO.isCPI())
492       MOSymbol = GetCPISymbol(MO.getIndex());
493
494     if (IsFunction || IsExternal || TM.getCodeModel() == CodeModel::Large)
495       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
496
497     const MCExpr *Exp =
498       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
499                               OutContext);
500     TmpInst.getOperand(2) = MCOperand::CreateExpr(Exp);
501     OutStreamer.EmitInstruction(TmpInst);
502     return;
503   }
504   case PPC::ADDISgotTprelHA: {
505     // Transform: %Xd = ADDISgotTprelHA %X2, <ga:@sym>
506     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
507     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
508     const MachineOperand &MO = MI->getOperand(2);
509     const GlobalValue *GValue = MO.getGlobal();
510     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
511     const MCExpr *SymGotTprel =
512       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
513                               OutContext);
514     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
515                                 .addReg(MI->getOperand(0).getReg())
516                                 .addReg(PPC::X2)
517                                 .addExpr(SymGotTprel));
518     return;
519   }
520   case PPC::LDgotTprelL: {
521     // Transform %Xd = LDgotTprelL <ga:@sym>, %Xs
522     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
523
524     // Change the opcode to LD.
525     TmpInst.setOpcode(PPC::LD);
526     const MachineOperand &MO = MI->getOperand(1);
527     const GlobalValue *GValue = MO.getGlobal();
528     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
529     const MCExpr *Exp =
530       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO,
531                               OutContext);
532     TmpInst.getOperand(1) = MCOperand::CreateExpr(Exp);
533     OutStreamer.EmitInstruction(TmpInst);
534     return;
535   }
536   case PPC::ADDIStlsgdHA: {
537     // Transform: %Xd = ADDIStlsgdHA %X2, <ga:@sym>
538     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
539     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
540     const MachineOperand &MO = MI->getOperand(2);
541     const GlobalValue *GValue = MO.getGlobal();
542     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
543     const MCExpr *SymGotTlsGD =
544       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
545                               OutContext);
546     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
547                                 .addReg(MI->getOperand(0).getReg())
548                                 .addReg(PPC::X2)
549                                 .addExpr(SymGotTlsGD));
550     return;
551   }
552   case PPC::ADDItlsgdL: {
553     // Transform: %Xd = ADDItlsgdL %Xs, <ga:@sym>
554     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsgd@l
555     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
556     const MachineOperand &MO = MI->getOperand(2);
557     const GlobalValue *GValue = MO.getGlobal();
558     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
559     const MCExpr *SymGotTlsGD =
560       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO,
561                               OutContext);
562     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8)
563                                 .addReg(MI->getOperand(0).getReg())
564                                 .addReg(MI->getOperand(1).getReg())
565                                 .addExpr(SymGotTlsGD));
566     return;
567   }
568   case PPC::GETtlsADDR: {
569     // Transform: %X3 = GETtlsADDR %X3, <ga:@sym>
570     // Into:      BL8_NOP_TLS __tls_get_addr(sym@tlsgd)
571     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
572
573     StringRef Name = "__tls_get_addr";
574     MCSymbol *TlsGetAddr = OutContext.GetOrCreateSymbol(Name);
575     const MCSymbolRefExpr *TlsRef = 
576       MCSymbolRefExpr::Create(TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
577     const MachineOperand &MO = MI->getOperand(2);
578     const GlobalValue *GValue = MO.getGlobal();
579     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
580     const MCExpr *SymVar =
581       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TLSGD,
582                               OutContext);
583     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL8_NOP_TLS)
584                                 .addExpr(TlsRef)
585                                 .addExpr(SymVar));
586     return;
587   }
588   case PPC::ADDIStlsldHA: {
589     // Transform: %Xd = ADDIStlsldHA %X2, <ga:@sym>
590     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsld@ha
591     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
592     const MachineOperand &MO = MI->getOperand(2);
593     const GlobalValue *GValue = MO.getGlobal();
594     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
595     const MCExpr *SymGotTlsLD =
596       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
597                               OutContext);
598     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
599                                 .addReg(MI->getOperand(0).getReg())
600                                 .addReg(PPC::X2)
601                                 .addExpr(SymGotTlsLD));
602     return;
603   }
604   case PPC::ADDItlsldL: {
605     // Transform: %Xd = ADDItlsldL %Xs, <ga:@sym>
606     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsld@l
607     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
608     const MachineOperand &MO = MI->getOperand(2);
609     const GlobalValue *GValue = MO.getGlobal();
610     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
611     const MCExpr *SymGotTlsLD =
612       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO,
613                               OutContext);
614     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8)
615                                 .addReg(MI->getOperand(0).getReg())
616                                 .addReg(MI->getOperand(1).getReg())
617                                 .addExpr(SymGotTlsLD));
618     return;
619   }
620   case PPC::GETtlsldADDR: {
621     // Transform: %X3 = GETtlsldADDR %X3, <ga:@sym>
622     // Into:      BL8_NOP_TLS __tls_get_addr(sym@tlsld)
623     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
624
625     StringRef Name = "__tls_get_addr";
626     MCSymbol *TlsGetAddr = OutContext.GetOrCreateSymbol(Name);
627     const MCSymbolRefExpr *TlsRef = 
628       MCSymbolRefExpr::Create(TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
629     const MachineOperand &MO = MI->getOperand(2);
630     const GlobalValue *GValue = MO.getGlobal();
631     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
632     const MCExpr *SymVar =
633       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_TLSLD,
634                               OutContext);
635     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BL8_NOP_TLS)
636                                 .addExpr(TlsRef)
637                                 .addExpr(SymVar));
638     return;
639   }
640   case PPC::ADDISdtprelHA: {
641     // Transform: %Xd = ADDISdtprelHA %X3, <ga:@sym>
642     // Into:      %Xd = ADDIS8 %X3, sym@dtprel@ha
643     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
644     const MachineOperand &MO = MI->getOperand(2);
645     const GlobalValue *GValue = MO.getGlobal();
646     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
647     const MCExpr *SymDtprel =
648       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
649                               OutContext);
650     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS8)
651                                 .addReg(MI->getOperand(0).getReg())
652                                 .addReg(PPC::X3)
653                                 .addExpr(SymDtprel));
654     return;
655   }
656   case PPC::ADDIdtprelL: {
657     // Transform: %Xd = ADDIdtprelL %Xs, <ga:@sym>
658     // Into:      %Xd = ADDI8 %Xs, sym@dtprel@l
659     assert(Subtarget.isPPC64() && "Not supported for 32-bit PowerPC");
660     const MachineOperand &MO = MI->getOperand(2);
661     const GlobalValue *GValue = MO.getGlobal();
662     MCSymbol *MOSymbol = Mang->getSymbol(GValue);
663     const MCExpr *SymDtprel =
664       MCSymbolRefExpr::Create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
665                               OutContext);
666     OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDI8)
667                                 .addReg(MI->getOperand(0).getReg())
668                                 .addReg(MI->getOperand(1).getReg())
669                                 .addExpr(SymDtprel));
670     return;
671   }
672   case PPC::MFOCRF:
673   case PPC::MFOCRF8:
674     if (!Subtarget.hasMFOCRF()) {
675       // Transform: %R3 = MFOCRF %CR7
676       // Into:      %R3 = MFCR   ;; cr7
677       unsigned NewOpcode =
678         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
679       OutStreamer.AddComment(PPCInstPrinter::
680                              getRegisterName(MI->getOperand(1).getReg()));
681       OutStreamer.EmitInstruction(MCInstBuilder(NewOpcode)
682                                   .addReg(MI->getOperand(0).getReg()));
683       return;
684     }
685     break;
686   case PPC::MTOCRF:
687   case PPC::MTOCRF8:
688     if (!Subtarget.hasMFOCRF()) {
689       // Transform: %CR7 = MTOCRF %R3
690       // Into:      MTCRF mask, %R3 ;; cr7
691       unsigned NewOpcode =
692         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
693       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
694                               ->getEncodingValue(MI->getOperand(0).getReg());
695       OutStreamer.AddComment(PPCInstPrinter::
696                              getRegisterName(MI->getOperand(0).getReg()));
697       OutStreamer.EmitInstruction(MCInstBuilder(NewOpcode)
698                                   .addImm(Mask)
699                                   .addReg(MI->getOperand(1).getReg()));
700       return;
701     }
702     break;
703   case PPC::SYNC:
704     // In Book E sync is called msync, handle this special case here...
705     if (Subtarget.isBookE()) {
706       OutStreamer.EmitRawText(StringRef("\tmsync"));
707       return;
708     }
709     break;
710   case PPC::LD:
711   case PPC::STD:
712   case PPC::LWA_32:
713   case PPC::LWA: {
714     // Verify alignment is legal, so we don't create relocations
715     // that can't be supported.
716     // FIXME:  This test is currently disabled for Darwin.  The test
717     // suite shows a handful of test cases that fail this check for
718     // Darwin.  Those need to be investigated before this sanity test
719     // can be enabled for those subtargets.
720     if (!Subtarget.isDarwin()) {
721       unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
722       const MachineOperand &MO = MI->getOperand(OpNum);
723       if (MO.isGlobal() && MO.getGlobal()->getAlignment() < 4)
724         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
725     }
726     // Now process the instruction normally.
727     break;
728   }
729   }
730
731   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
732   OutStreamer.EmitInstruction(TmpInst);
733 }
734
735 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
736   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
737     return AsmPrinter::EmitFunctionEntryLabel();
738     
739   // Emit an official procedure descriptor.
740   MCSectionSubPair Current = OutStreamer.getCurrentSection();
741   const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".opd",
742       ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
743       SectionKind::getReadOnly());
744   OutStreamer.SwitchSection(Section);
745   OutStreamer.EmitLabel(CurrentFnSym);
746   OutStreamer.EmitValueToAlignment(8);
747   MCSymbol *Symbol1 = 
748     OutContext.GetOrCreateSymbol(".L." + Twine(CurrentFnSym->getName()));
749   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
750   // entry point.
751   OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol1, OutContext),
752                         8 /*size*/);
753   MCSymbol *Symbol2 = OutContext.GetOrCreateSymbol(StringRef(".TOC."));
754   // Generates a R_PPC64_TOC relocation for TOC base insertion.
755   OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol2,
756                         MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
757                         8/*size*/);
758   // Emit a null environment pointer.
759   OutStreamer.EmitIntValue(0, 8 /* size */);
760   OutStreamer.SwitchSection(Current.first, Current.second);
761
762   MCSymbol *RealFnSym = OutContext.GetOrCreateSymbol(
763                           ".L." + Twine(CurrentFnSym->getName()));
764   OutStreamer.EmitLabel(RealFnSym);
765   CurrentFnSymForSize = RealFnSym;
766 }
767
768
769 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
770   const DataLayout *TD = TM.getDataLayout();
771
772   bool isPPC64 = TD->getPointerSizeInBits() == 64;
773
774   if (isPPC64 && !TOC.empty()) {
775     const MCSectionELF *Section = OutStreamer.getContext().getELFSection(".toc",
776         ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
777         SectionKind::getReadOnly());
778     OutStreamer.SwitchSection(Section);
779
780     for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
781          E = TOC.end(); I != E; ++I) {
782       OutStreamer.EmitLabel(I->second);
783       MCSymbol *S = OutContext.GetOrCreateSymbol(I->first->getName());
784       OutStreamer.EmitTCEntry(*S);
785     }
786   }
787
788   MachineModuleInfoELF &MMIELF =
789     MMI->getObjFileInfo<MachineModuleInfoELF>();
790
791   MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
792   if (!Stubs.empty()) {
793     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
794     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
795       // L_foo$stub:
796       OutStreamer.EmitLabel(Stubs[i].first);
797       //   .long _foo
798       OutStreamer.EmitValue(MCSymbolRefExpr::Create(Stubs[i].second.getPointer(),
799                                                     OutContext),
800                             isPPC64 ? 8 : 4/*size*/);
801     }
802
803     Stubs.clear();
804     OutStreamer.AddBlankLine();
805   }
806
807   return AsmPrinter::doFinalization(M);
808 }
809
810 /// EmitFunctionBodyEnd - Print the traceback table before the .size
811 /// directive.
812 ///
813 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
814   // Only the 64-bit target requires a traceback table.  For now,
815   // we only emit the word of zeroes that GDB requires to find
816   // the end of the function, and zeroes for the eight-byte
817   // mandatory fields.
818   // FIXME: We should fill in the eight-byte mandatory fields as described in
819   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
820   // currently make use of these fields).
821   if (Subtarget.isPPC64()) {
822     OutStreamer.EmitIntValue(0, 4/*size*/);
823     OutStreamer.EmitIntValue(0, 8/*size*/);
824   }
825 }
826
827 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
828   static const char *const CPUDirectives[] = {
829     "",
830     "ppc",
831     "ppc440",
832     "ppc601",
833     "ppc602",
834     "ppc603",
835     "ppc7400",
836     "ppc750",
837     "ppc970",
838     "ppcA2",
839     "ppce500mc",
840     "ppce5500",
841     "power3",
842     "power4",
843     "power5",
844     "power5x",
845     "power6",
846     "power6x",
847     "power7",
848     "ppc64",
849     "ppc64le"
850   };
851
852   unsigned Directive = Subtarget.getDarwinDirective();
853   if (Subtarget.hasMFOCRF() && Directive < PPC::DIR_970)
854     Directive = PPC::DIR_970;
855   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
856     Directive = PPC::DIR_7400;
857   if (Subtarget.isPPC64() && Directive < PPC::DIR_64)
858     Directive = PPC::DIR_64;
859   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
860   
861   // FIXME: This is a total hack, finish mc'izing the PPC backend.
862   if (OutStreamer.hasRawTextSupport()) {
863     assert(Directive < array_lengthof(CPUDirectives) &&
864            "CPUDirectives[] might not be up-to-date!");
865     OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
866   }
867
868   // Prime text sections so they are adjacent.  This reduces the likelihood a
869   // large data or debug section causes a branch to exceed 16M limit.
870   const TargetLoweringObjectFileMachO &TLOFMacho = 
871     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
872   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
873   if (TM.getRelocationModel() == Reloc::PIC_) {
874     OutStreamer.SwitchSection(
875            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
876                                       MCSectionMachO::S_SYMBOL_STUBS |
877                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
878                                       32, SectionKind::getText()));
879   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
880     OutStreamer.SwitchSection(
881            OutContext.getMachOSection("__TEXT","__symbol_stub1",
882                                       MCSectionMachO::S_SYMBOL_STUBS |
883                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
884                                       16, SectionKind::getText()));
885   }
886   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
887 }
888
889 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
890   // Remove $stub suffix, add $lazy_ptr.
891   StringRef NoStub = Sym->getName().substr(0, Sym->getName().size()-5);
892   return Ctx.GetOrCreateSymbol(NoStub + "$lazy_ptr");
893 }
894
895 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
896   // Add $tmp suffix to $stub, yielding $stub$tmp.
897   return Ctx.GetOrCreateSymbol(Sym->getName() + "$tmp");
898 }
899
900 void PPCDarwinAsmPrinter::
901 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
902   bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
903   bool isDarwin = Subtarget.isDarwin();
904   
905   const TargetLoweringObjectFileMachO &TLOFMacho = 
906     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
907
908   // .lazy_symbol_pointer
909   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
910   
911   // Output stubs for dynamically-linked functions
912   if (TM.getRelocationModel() == Reloc::PIC_) {
913     const MCSection *StubSection = 
914     OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
915                                MCSectionMachO::S_SYMBOL_STUBS |
916                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
917                                32, SectionKind::getText());
918     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
919       OutStreamer.SwitchSection(StubSection);
920       EmitAlignment(4);
921       
922       MCSymbol *Stub = Stubs[i].first;
923       MCSymbol *RawSym = Stubs[i].second.getPointer();
924       MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
925       MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
926                                            
927       OutStreamer.EmitLabel(Stub);
928       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
929
930       const MCExpr *Anon = MCSymbolRefExpr::Create(AnonSymbol, OutContext);
931       const MCExpr *LazyPtrExpr = MCSymbolRefExpr::Create(LazyPtr, OutContext);
932       const MCExpr *Sub =
933         MCBinaryExpr::CreateSub(LazyPtrExpr, Anon, OutContext);
934
935       // mflr r0
936       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R0));
937       // bcl 20, 31, AnonSymbol
938       OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCLalways).addExpr(Anon));
939       OutStreamer.EmitLabel(AnonSymbol);
940       // mflr r11
941       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MFLR).addReg(PPC::R11));
942       // addis r11, r11, ha16(LazyPtr - AnonSymbol)
943       const MCExpr *SubHa16 = PPCMCExpr::CreateHa(Sub, isDarwin, OutContext);
944       OutStreamer.EmitInstruction(MCInstBuilder(PPC::ADDIS)
945         .addReg(PPC::R11)
946         .addReg(PPC::R11)
947         .addExpr(SubHa16));
948       // mtlr r0
949       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTLR).addReg(PPC::R0));
950
951       // ldu r12, lo16(LazyPtr - AnonSymbol)(r11)
952       // lwzu r12, lo16(LazyPtr - AnonSymbol)(r11)
953       const MCExpr *SubLo16 = PPCMCExpr::CreateLo(Sub, isDarwin, OutContext);
954       OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
955         .addReg(PPC::R12)
956         .addExpr(SubLo16).addExpr(SubLo16)
957         .addReg(PPC::R11));
958       // mtctr r12
959       OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
960       // bctr
961       OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
962
963       OutStreamer.SwitchSection(LSPSection);
964       OutStreamer.EmitLabel(LazyPtr);
965       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
966
967       MCSymbol *DyldStubBindingHelper =
968         OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
969       if (isPPC64) {
970         // .quad dyld_stub_binding_helper
971         OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
972       } else {
973         // .long dyld_stub_binding_helper
974         OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
975       }
976     }
977     OutStreamer.AddBlankLine();
978     return;
979   }
980   
981   const MCSection *StubSection =
982     OutContext.getMachOSection("__TEXT","__symbol_stub1",
983                                MCSectionMachO::S_SYMBOL_STUBS |
984                                MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
985                                16, SectionKind::getText());
986   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
987     MCSymbol *Stub = Stubs[i].first;
988     MCSymbol *RawSym = Stubs[i].second.getPointer();
989     MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
990     const MCExpr *LazyPtrExpr = MCSymbolRefExpr::Create(LazyPtr, OutContext);
991
992     OutStreamer.SwitchSection(StubSection);
993     EmitAlignment(4);
994     OutStreamer.EmitLabel(Stub);
995     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
996
997     // lis r11, ha16(LazyPtr)
998     const MCExpr *LazyPtrHa16 =
999       PPCMCExpr::CreateHa(LazyPtrExpr, isDarwin, OutContext);
1000     OutStreamer.EmitInstruction(MCInstBuilder(PPC::LIS)
1001       .addReg(PPC::R11)
1002       .addExpr(LazyPtrHa16));
1003
1004     // ldu r12, lo16(LazyPtr)(r11)
1005     // lwzu r12, lo16(LazyPtr)(r11)
1006     const MCExpr *LazyPtrLo16 =
1007       PPCMCExpr::CreateLo(LazyPtrExpr, isDarwin, OutContext);
1008     OutStreamer.EmitInstruction(MCInstBuilder(isPPC64 ? PPC::LDU : PPC::LWZU)
1009       .addReg(PPC::R12)
1010       .addExpr(LazyPtrLo16).addExpr(LazyPtrLo16)
1011       .addReg(PPC::R11));
1012
1013     // mtctr r12
1014     OutStreamer.EmitInstruction(MCInstBuilder(PPC::MTCTR).addReg(PPC::R12));
1015     // bctr
1016     OutStreamer.EmitInstruction(MCInstBuilder(PPC::BCTR));
1017
1018     OutStreamer.SwitchSection(LSPSection);
1019     OutStreamer.EmitLabel(LazyPtr);
1020     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
1021
1022     MCSymbol *DyldStubBindingHelper =
1023       OutContext.GetOrCreateSymbol(StringRef("dyld_stub_binding_helper"));
1024     if (isPPC64) {
1025       // .quad dyld_stub_binding_helper
1026       OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 8);
1027     } else {
1028       // .long dyld_stub_binding_helper
1029       OutStreamer.EmitSymbolValue(DyldStubBindingHelper, 4);
1030     }
1031   }
1032   
1033   OutStreamer.AddBlankLine();
1034 }
1035
1036
1037 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1038   bool isPPC64 = TM.getDataLayout()->getPointerSizeInBits() == 64;
1039
1040   // Darwin/PPC always uses mach-o.
1041   const TargetLoweringObjectFileMachO &TLOFMacho = 
1042     static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1043   MachineModuleInfoMachO &MMIMacho =
1044     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1045   
1046   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
1047   if (!Stubs.empty())
1048     EmitFunctionStubs(Stubs);
1049
1050   if (MAI->doesSupportExceptionHandling() && MMI) {
1051     // Add the (possibly multiple) personalities to the set of global values.
1052     // Only referenced functions get into the Personalities list.
1053     const std::vector<const Function*> &Personalities = MMI->getPersonalities();
1054     for (std::vector<const Function*>::const_iterator I = Personalities.begin(),
1055          E = Personalities.end(); I != E; ++I) {
1056       if (*I) {
1057         MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
1058         MachineModuleInfoImpl::StubValueTy &StubSym =
1059           MMIMacho.getGVStubEntry(NLPSym);
1060         StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
1061       }
1062     }
1063   }
1064
1065   // Output stubs for dynamically-linked functions.
1066   Stubs = MMIMacho.GetGVStubList();
1067   
1068   // Output macho stubs for external and common global variables.
1069   if (!Stubs.empty()) {
1070     // Switch with ".non_lazy_symbol_pointer" directive.
1071     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1072     EmitAlignment(isPPC64 ? 3 : 2);
1073     
1074     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1075       // L_foo$stub:
1076       OutStreamer.EmitLabel(Stubs[i].first);
1077       //   .indirect_symbol _foo
1078       MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1079       OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
1080
1081       if (MCSym.getInt())
1082         // External to current translation unit.
1083         OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/);
1084       else
1085         // Internal to current translation unit.
1086         //
1087         // When we place the LSDA into the TEXT section, the type info pointers
1088         // need to be indirect and pc-rel. We accomplish this by using NLPs.
1089         // However, sometimes the types are local to the file. So we need to
1090         // fill in the value for the NLP in those cases.
1091         OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
1092                                                       OutContext),
1093                               isPPC64 ? 8 : 4/*size*/);
1094     }
1095
1096     Stubs.clear();
1097     OutStreamer.AddBlankLine();
1098   }
1099
1100   Stubs = MMIMacho.GetHiddenGVStubList();
1101   if (!Stubs.empty()) {
1102     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1103     EmitAlignment(isPPC64 ? 3 : 2);
1104     
1105     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1106       // L_foo$stub:
1107       OutStreamer.EmitLabel(Stubs[i].first);
1108       //   .long _foo
1109       OutStreamer.EmitValue(MCSymbolRefExpr::
1110                             Create(Stubs[i].second.getPointer(),
1111                                    OutContext),
1112                             isPPC64 ? 8 : 4/*size*/);
1113     }
1114
1115     Stubs.clear();
1116     OutStreamer.AddBlankLine();
1117   }
1118
1119   // Funny Darwin hack: This flag tells the linker that no global symbols
1120   // contain code that falls through to other global symbols (e.g. the obvious
1121   // implementation of multiple entry points).  If this doesn't occur, the
1122   // linker can safely perform dead code stripping.  Since LLVM never generates
1123   // code that does this, it is always safe to set.
1124   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1125
1126   return AsmPrinter::doFinalization(M);
1127 }
1128
1129 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1130 /// for a MachineFunction to the given output stream, in a format that the
1131 /// Darwin assembler can deal with.
1132 ///
1133 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
1134                                            MCStreamer &Streamer) {
1135   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1136
1137   if (Subtarget->isDarwin())
1138     return new PPCDarwinAsmPrinter(tm, Streamer);
1139   return new PPCLinuxAsmPrinter(tm, Streamer);
1140 }
1141
1142 // Force static initialization.
1143 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1144   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1145   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1146 }