PPCAsmPrinter.cpp revision 1b0a2d8370b28de0d3998b0303bc3dad983989d9
1//===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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 "PPCTargetMachine.h"
22#include "PPCSubtarget.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Module.h"
26#include "llvm/Assembly/Writer.h"
27#include "llvm/CodeGen/AsmPrinter.h"
28#include "llvm/CodeGen/DwarfWriter.h"
29#include "llvm/CodeGen/MachineDebugInfo.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
32#include "llvm/Support/Mangler.h"
33#include "llvm/Support/MathExtras.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Target/TargetAsmInfo.h"
38#include "llvm/Target/MRegisterInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetOptions.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/StringExtras.h"
43#include <iostream>
44#include <set>
45using namespace llvm;
46
47namespace {
48  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
49
50  struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
51    std::set<std::string> FnStubs, GVStubs;
52    const PPCSubtarget &Subtarget;
53
54    PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
55      : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
56    }
57
58    virtual const char *getPassName() const {
59      return "PowerPC Assembly Printer";
60    }
61
62    PPCTargetMachine &getTM() {
63      return static_cast<PPCTargetMachine&>(TM);
64    }
65
66    unsigned enumRegToMachineReg(unsigned enumReg) {
67      switch (enumReg) {
68      default: assert(0 && "Unhandled register!"); break;
69      case PPC::CR0:  return  0;
70      case PPC::CR1:  return  1;
71      case PPC::CR2:  return  2;
72      case PPC::CR3:  return  3;
73      case PPC::CR4:  return  4;
74      case PPC::CR5:  return  5;
75      case PPC::CR6:  return  6;
76      case PPC::CR7:  return  7;
77      }
78      abort();
79    }
80
81    /// printInstruction - This method is automatically generated by tablegen
82    /// from the instruction set description.  This method returns true if the
83    /// machine instruction was sufficiently described to print it, otherwise it
84    /// returns false.
85    bool printInstruction(const MachineInstr *MI);
86
87    void printMachineInstruction(const MachineInstr *MI);
88    void printOp(const MachineOperand &MO);
89
90    void printOperand(const MachineInstr *MI, unsigned OpNo) {
91      const MachineOperand &MO = MI->getOperand(OpNo);
92      if (MO.isRegister()) {
93        assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
94        O << TM.getRegisterInfo()->get(MO.getReg()).Name;
95      } else if (MO.isImmediate()) {
96        O << MO.getImmedValue();
97      } else {
98        printOp(MO);
99      }
100    }
101
102    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
103                         unsigned AsmVariant, const char *ExtraCode);
104    bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
105                               unsigned AsmVariant, const char *ExtraCode);
106
107
108    void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
109      char value = MI->getOperand(OpNo).getImmedValue();
110      value = (value << (32-5)) >> (32-5);
111      O << (int)value;
112    }
113    void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
114      unsigned char value = MI->getOperand(OpNo).getImmedValue();
115      assert(value <= 31 && "Invalid u5imm argument!");
116      O << (unsigned int)value;
117    }
118    void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
119      unsigned char value = MI->getOperand(OpNo).getImmedValue();
120      assert(value <= 63 && "Invalid u6imm argument!");
121      O << (unsigned int)value;
122    }
123    void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
124      O << (short)MI->getOperand(OpNo).getImmedValue();
125    }
126    void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
127      O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
128    }
129    void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
130      if (MI->getOperand(OpNo).isImmediate()) {
131        O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
132      } else {
133        O << "lo16(";
134        printOp(MI->getOperand(OpNo));
135        if (TM.getRelocationModel() == Reloc::PIC_)
136          O << "-\"L" << getFunctionNumber() << "$pb\")";
137        else
138          O << ')';
139      }
140    }
141    void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
142      // Branches can take an immediate operand.  This is used by the branch
143      // selection pass to print $+8, an eight byte displacement from the PC.
144      if (MI->getOperand(OpNo).isImmediate()) {
145        O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
146      } else {
147        printOp(MI->getOperand(OpNo));
148      }
149    }
150    void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
151      const MachineOperand &MO = MI->getOperand(OpNo);
152      if (TM.getRelocationModel() != Reloc::Static) {
153        if (MO.getType() == MachineOperand::MO_GlobalAddress) {
154          GlobalValue *GV = MO.getGlobal();
155          if (((GV->isExternal() || GV->hasWeakLinkage() ||
156                GV->hasLinkOnceLinkage()))) {
157            // Dynamically-resolved functions need a stub for the function.
158            std::string Name = Mang->getValueName(GV);
159            FnStubs.insert(Name);
160            O << "L" << Name << "$stub";
161            return;
162          }
163        }
164        if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
165          std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
166          FnStubs.insert(Name);
167          O << "L" << Name << "$stub";
168          return;
169        }
170      }
171
172      printOp(MI->getOperand(OpNo));
173    }
174    void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
175     O << (int)MI->getOperand(OpNo).getImmedValue()*4;
176    }
177    void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
178      O << "\"L" << getFunctionNumber() << "$pb\"\n";
179      O << "\"L" << getFunctionNumber() << "$pb\":";
180    }
181    void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
182      if (MI->getOperand(OpNo).isImmediate()) {
183        printS16ImmOperand(MI, OpNo);
184      } else {
185        O << "ha16(";
186        printOp(MI->getOperand(OpNo));
187        if (TM.getRelocationModel() == Reloc::PIC_)
188          O << "-\"L" << getFunctionNumber() << "$pb\")";
189        else
190          O << ')';
191      }
192    }
193    void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
194      if (MI->getOperand(OpNo).isImmediate()) {
195        printS16ImmOperand(MI, OpNo);
196      } else {
197        O << "lo16(";
198        printOp(MI->getOperand(OpNo));
199        if (TM.getRelocationModel() == Reloc::PIC_)
200          O << "-\"L" << getFunctionNumber() << "$pb\")";
201        else
202          O << ')';
203      }
204    }
205    void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
206      unsigned CCReg = MI->getOperand(OpNo).getReg();
207      unsigned RegNo = enumRegToMachineReg(CCReg);
208      O << (0x80 >> RegNo);
209    }
210    // The new addressing mode printers.
211    void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
212      printSymbolLo(MI, OpNo);
213      O << '(';
214      if (MI->getOperand(OpNo+1).isRegister() &&
215          MI->getOperand(OpNo+1).getReg() == PPC::R0)
216        O << "0";
217      else
218        printOperand(MI, OpNo+1);
219      O << ')';
220    }
221    void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
222      if (MI->getOperand(OpNo).isImmediate())
223        printS16X4ImmOperand(MI, OpNo);
224      else
225        printSymbolLo(MI, OpNo);
226      O << '(';
227      if (MI->getOperand(OpNo+1).isRegister() &&
228          MI->getOperand(OpNo+1).getReg() == PPC::R0)
229        O << "0";
230      else
231        printOperand(MI, OpNo+1);
232      O << ')';
233    }
234
235    void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
236      // When used as the base register, r0 reads constant zero rather than
237      // the value contained in the register.  For this reason, the darwin
238      // assembler requires that we print r0 as 0 (no r) when used as the base.
239      const MachineOperand &MO = MI->getOperand(OpNo);
240      if (MO.getReg() == PPC::R0)
241        O << '0';
242      else
243        O << TM.getRegisterInfo()->get(MO.getReg()).Name;
244      O << ", ";
245      printOperand(MI, OpNo+1);
246    }
247
248    void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
249                               const char *Modifier);
250
251    virtual bool runOnMachineFunction(MachineFunction &F) = 0;
252    virtual bool doFinalization(Module &M) = 0;
253  };
254
255  /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
256  /// X
257  struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
258
259    DwarfWriter DW;
260
261    DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
262                     const TargetAsmInfo *T)
263      : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
264    }
265
266    virtual const char *getPassName() const {
267      return "Darwin PPC Assembly Printer";
268    }
269
270    bool runOnMachineFunction(MachineFunction &F);
271    bool doInitialization(Module &M);
272    bool doFinalization(Module &M);
273
274    void getAnalysisUsage(AnalysisUsage &AU) const {
275      AU.setPreservesAll();
276      AU.addRequired<MachineDebugInfo>();
277      PPCAsmPrinter::getAnalysisUsage(AU);
278    }
279
280    /// getSectionForFunction - Return the section that we should emit the
281    /// specified function body into.
282    virtual std::string getSectionForFunction(const Function &F) const;
283  };
284} // end of anonymous namespace
285
286// Include the auto-generated portion of the assembly writer
287#include "PPCGenAsmWriter.inc"
288
289void PPCAsmPrinter::printOp(const MachineOperand &MO) {
290  switch (MO.getType()) {
291  case MachineOperand::MO_Immediate:
292    std::cerr << "printOp() does not handle immediate values\n";
293    abort();
294    return;
295
296  case MachineOperand::MO_MachineBasicBlock:
297    printBasicBlockLabel(MO.getMachineBasicBlock());
298    return;
299  case MachineOperand::MO_JumpTableIndex:
300    O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
301      << '_' << MO.getJumpTableIndex();
302    // FIXME: PIC relocation model
303    return;
304  case MachineOperand::MO_ConstantPoolIndex:
305    O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
306      << '_' << MO.getConstantPoolIndex();
307    return;
308  case MachineOperand::MO_ExternalSymbol:
309    // Computing the address of an external symbol, not calling it.
310    if (TM.getRelocationModel() != Reloc::Static) {
311      std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
312      GVStubs.insert(Name);
313      O << "L" << Name << "$non_lazy_ptr";
314      return;
315    }
316    O << TAI->getGlobalPrefix() << MO.getSymbolName();
317    return;
318  case MachineOperand::MO_GlobalAddress: {
319    // Computing the address of a global symbol, not calling it.
320    GlobalValue *GV = MO.getGlobal();
321    std::string Name = Mang->getValueName(GV);
322
323    // External or weakly linked global variables need non-lazily-resolved stubs
324    if (TM.getRelocationModel() != Reloc::Static) {
325      if (((GV->isExternal() || GV->hasWeakLinkage() ||
326            GV->hasLinkOnceLinkage()))) {
327        GVStubs.insert(Name);
328        O << "L" << Name << "$non_lazy_ptr";
329        return;
330      }
331    }
332
333    O << Name;
334    return;
335  }
336
337  default:
338    O << "<unknown operand type: " << MO.getType() << ">";
339    return;
340  }
341}
342
343/// PrintAsmOperand - Print out an operand for an inline asm expression.
344///
345bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
346                                    unsigned AsmVariant,
347                                    const char *ExtraCode) {
348  // Does this asm operand have a single letter operand modifier?
349  if (ExtraCode && ExtraCode[0]) {
350    if (ExtraCode[1] != 0) return true; // Unknown modifier.
351
352    switch (ExtraCode[0]) {
353    default: return true;  // Unknown modifier.
354    case 'L': // Write second word of DImode reference.
355      // Verify that this operand has two consecutive registers.
356      if (!MI->getOperand(OpNo).isRegister() ||
357          OpNo+1 == MI->getNumOperands() ||
358          !MI->getOperand(OpNo+1).isRegister())
359        return true;
360      ++OpNo;   // Return the high-part.
361      break;
362    }
363  }
364
365  printOperand(MI, OpNo);
366  return false;
367}
368
369bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
370                                          unsigned AsmVariant,
371                                          const char *ExtraCode) {
372  if (ExtraCode && ExtraCode[0])
373    return true; // Unknown modifier.
374  printMemRegReg(MI, OpNo);
375  return false;
376}
377
378void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
379                                          const char *Modifier) {
380  assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
381  unsigned Code = MI->getOperand(OpNo).getImm();
382  if (!strcmp(Modifier, "cc")) {
383    switch ((PPC::Predicate)Code) {
384    case PPC::PRED_ALWAYS: return; // Don't print anything for always.
385    case PPC::PRED_LT: O << "lt"; return;
386    case PPC::PRED_LE: O << "le"; return;
387    case PPC::PRED_EQ: O << "eq"; return;
388    case PPC::PRED_GE: O << "ge"; return;
389    case PPC::PRED_GT: O << "gt"; return;
390    case PPC::PRED_NE: O << "ne"; return;
391    case PPC::PRED_UN: O << "un"; return;
392    case PPC::PRED_NU: O << "nu"; return;
393    }
394
395  } else {
396    assert(!strcmp(Modifier, "reg") &&
397           "Need to specify 'cc' or 'reg' as predicate op modifier!");
398    // Don't print the register for 'always'.
399    if (Code == PPC::PRED_ALWAYS) return;
400    printOperand(MI, OpNo+1);
401  }
402}
403
404
405/// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
406/// the current output stream.
407///
408void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
409  ++EmittedInsts;
410
411  // Check for slwi/srwi mnemonics.
412  if (MI->getOpcode() == PPC::RLWINM) {
413    bool FoundMnemonic = false;
414    unsigned char SH = MI->getOperand(2).getImmedValue();
415    unsigned char MB = MI->getOperand(3).getImmedValue();
416    unsigned char ME = MI->getOperand(4).getImmedValue();
417    if (SH <= 31 && MB == 0 && ME == (31-SH)) {
418      O << "slwi "; FoundMnemonic = true;
419    }
420    if (SH <= 31 && MB == (32-SH) && ME == 31) {
421      O << "srwi "; FoundMnemonic = true;
422      SH = 32-SH;
423    }
424    if (FoundMnemonic) {
425      printOperand(MI, 0);
426      O << ", ";
427      printOperand(MI, 1);
428      O << ", " << (unsigned int)SH << "\n";
429      return;
430    }
431  } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
432    if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
433      O << "mr ";
434      printOperand(MI, 0);
435      O << ", ";
436      printOperand(MI, 1);
437      O << "\n";
438      return;
439    }
440  }
441
442  if (printInstruction(MI))
443    return; // Printer was automatically generated
444
445  assert(0 && "Unhandled instruction in asm writer!");
446  abort();
447  return;
448}
449
450
451
452std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
453  switch (F.getLinkage()) {
454  default: assert(0 && "Unknown linkage type!");
455  case Function::ExternalLinkage:
456  case Function::InternalLinkage: return TAI->getTextSection();
457  case Function::WeakLinkage:
458  case Function::LinkOnceLinkage:
459    return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
460  }
461}
462
463/// runOnMachineFunction - This uses the printMachineInstruction()
464/// method to print assembly for each instruction.
465///
466bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
467  DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
468
469  SetupMachineFunction(MF);
470  O << "\n\n";
471
472  // Print out constants referenced by the function
473  EmitConstantPool(MF.getConstantPool());
474
475  // Print out labels for the function.
476  const Function *F = MF.getFunction();
477  SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
478
479  switch (F->getLinkage()) {
480  default: assert(0 && "Unknown linkage type!");
481  case Function::InternalLinkage:  // Symbols default to internal.
482    break;
483  case Function::ExternalLinkage:
484    O << "\t.globl\t" << CurrentFnName << "\n";
485    break;
486  case Function::WeakLinkage:
487  case Function::LinkOnceLinkage:
488    O << "\t.globl\t" << CurrentFnName << "\n";
489    O << "\t.weak_definition\t" << CurrentFnName << "\n";
490    break;
491  }
492  EmitAlignment(4, F);
493  O << CurrentFnName << ":\n";
494
495  // Emit pre-function debug information.
496  DW.BeginFunction(&MF);
497
498  // Print out code for the function.
499  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
500       I != E; ++I) {
501    // Print a label for the basic block.
502    if (I != MF.begin()) {
503      printBasicBlockLabel(I, true);
504      O << '\n';
505    }
506    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
507         II != E; ++II) {
508      // Print the assembly for the instruction.
509      O << "\t";
510      printMachineInstruction(II);
511    }
512  }
513
514  // Print out jump tables referenced by the function.
515  EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
516
517  // Emit post-function debug information.
518  DW.EndFunction();
519
520  // We didn't modify anything.
521  return false;
522}
523
524
525bool DarwinAsmPrinter::doInitialization(Module &M) {
526  if (Subtarget.isGigaProcessor())
527    O << "\t.machine ppc970\n";
528  AsmPrinter::doInitialization(M);
529
530  // Darwin wants symbols to be quoted if they have complex names.
531  Mang->setUseQuotes(true);
532
533  // Emit initial debug information.
534  DW.BeginModule(&M);
535  return false;
536}
537
538bool DarwinAsmPrinter::doFinalization(Module &M) {
539  const TargetData *TD = TM.getTargetData();
540
541  // Print out module-level global variables here.
542  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
543       I != E; ++I) {
544    if (!I->hasInitializer()) continue;   // External global require no code
545
546    // Check to see if this is a special global used by LLVM, if so, emit it.
547    if (EmitSpecialLLVMGlobal(I))
548      continue;
549
550    std::string name = Mang->getValueName(I);
551    Constant *C = I->getInitializer();
552    unsigned Size = TD->getTypeSize(C->getType());
553    unsigned Align = TD->getPreferredAlignmentLog(I);
554
555    if (C->isNullValue() && /* FIXME: Verify correct */
556        (I->hasInternalLinkage() || I->hasWeakLinkage() ||
557         I->hasLinkOnceLinkage() ||
558         (I->hasExternalLinkage() && !I->hasSection()))) {
559      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
560      if (I->hasExternalLinkage()) {
561        O << "\t.globl " << name << '\n';
562        O << "\t.zerofill __DATA, __common, " << name << ", "
563          << Size << ", " << Align;
564      } else if (I->hasInternalLinkage()) {
565        SwitchToDataSection("\t.data", I);
566        O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
567      } else {
568        SwitchToDataSection("\t.data", I);
569        O << ".comm " << name << "," << Size;
570      }
571      O << "\t\t; '" << I->getName() << "'\n";
572    } else {
573      switch (I->getLinkage()) {
574      case GlobalValue::LinkOnceLinkage:
575      case GlobalValue::WeakLinkage:
576        O << "\t.globl " << name << '\n'
577          << "\t.weak_definition " << name << '\n';
578        SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
579        break;
580      case GlobalValue::AppendingLinkage:
581        // FIXME: appending linkage variables should go into a section of
582        // their name or something.  For now, just emit them as external.
583      case GlobalValue::ExternalLinkage:
584        // If external or appending, declare as a global symbol
585        O << "\t.globl " << name << "\n";
586        // FALL THROUGH
587      case GlobalValue::InternalLinkage:
588        if (I->isConstant()) {
589          const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
590          if (TAI->getCStringSection() && CVA && CVA->isCString()) {
591            SwitchToDataSection(TAI->getCStringSection(), I);
592            break;
593          }
594        }
595
596        SwitchToDataSection("\t.data", I);
597        break;
598      default:
599        std::cerr << "Unknown linkage type!";
600        abort();
601      }
602
603      EmitAlignment(Align, I);
604      O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
605      EmitGlobalConstant(C);
606      O << '\n';
607    }
608  }
609
610  bool isPPC64 = TD->getPointerSizeInBits() == 64;
611
612  // Output stubs for dynamically-linked functions
613  if (TM.getRelocationModel() == Reloc::PIC_) {
614    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
615         i != e; ++i) {
616      SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
617                          "pure_instructions,32");
618      EmitAlignment(4);
619      O << "L" << *i << "$stub:\n";
620      O << "\t.indirect_symbol " << *i << "\n";
621      O << "\tmflr r0\n";
622      O << "\tbcl 20,31,L0$" << *i << "\n";
623      O << "L0$" << *i << ":\n";
624      O << "\tmflr r11\n";
625      O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
626      O << "\tmtlr r0\n";
627      if (isPPC64)
628        O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
629      else
630        O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
631      O << "\tmtctr r12\n";
632      O << "\tbctr\n";
633      SwitchToDataSection(".lazy_symbol_pointer");
634      O << "L" << *i << "$lazy_ptr:\n";
635      O << "\t.indirect_symbol " << *i << "\n";
636      if (isPPC64)
637        O << "\t.quad dyld_stub_binding_helper\n";
638      else
639        O << "\t.long dyld_stub_binding_helper\n";
640    }
641  } else {
642    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
643         i != e; ++i) {
644      SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
645                          "pure_instructions,16");
646      EmitAlignment(4);
647      O << "L" << *i << "$stub:\n";
648      O << "\t.indirect_symbol " << *i << "\n";
649      O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
650      if (isPPC64)
651        O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
652      else
653        O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
654      O << "\tmtctr r12\n";
655      O << "\tbctr\n";
656      SwitchToDataSection(".lazy_symbol_pointer");
657      O << "L" << *i << "$lazy_ptr:\n";
658      O << "\t.indirect_symbol " << *i << "\n";
659      if (isPPC64)
660        O << "\t.quad dyld_stub_binding_helper\n";
661      else
662        O << "\t.long dyld_stub_binding_helper\n";
663    }
664  }
665
666  O << "\n";
667
668  // Output stubs for external and common global variables.
669  if (GVStubs.begin() != GVStubs.end()) {
670    SwitchToDataSection(".non_lazy_symbol_pointer");
671    for (std::set<std::string>::iterator I = GVStubs.begin(),
672         E = GVStubs.end(); I != E; ++I) {
673      O << "L" << *I << "$non_lazy_ptr:\n";
674      O << "\t.indirect_symbol " << *I << "\n";
675      if (isPPC64)
676        O << "\t.quad\t0\n";
677      else
678        O << "\t.long\t0\n";
679
680    }
681  }
682
683  // Emit initial debug information.
684  DW.EndModule();
685
686  // Funny Darwin hack: This flag tells the linker that no global symbols
687  // contain code that falls through to other global symbols (e.g. the obvious
688  // implementation of multiple entry points).  If this doesn't occur, the
689  // linker can safely perform dead code stripping.  Since LLVM never generates
690  // code that does this, it is always safe to set.
691  O << "\t.subsections_via_symbols\n";
692
693  AsmPrinter::doFinalization(M);
694  return false; // success
695}
696
697
698
699/// createDarwinCodePrinterPass - Returns a pass that prints the PPC assembly
700/// code for a MachineFunction to the given output stream, in a format that the
701/// Darwin assembler can deal with.
702///
703FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
704                                            PPCTargetMachine &tm) {
705  return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
706}
707
708