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