PPCAsmPrinter.cpp revision bf1118285c0f784b120a69b4a4207e15ef065ead
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 "PPCPredicates.h"
22#include "PPCTargetMachine.h"
23#include "PPCSubtarget.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Module.h"
27#include "llvm/Assembly/Writer.h"
28#include "llvm/CodeGen/AsmPrinter.h"
29#include "llvm/CodeGen/DwarfWriter.h"
30#include "llvm/CodeGen/MachineDebugInfo.h"
31#include "llvm/CodeGen/MachineFunctionPass.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/Support/Mangler.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Target/TargetAsmInfo.h"
39#include "llvm/Target/MRegisterInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetOptions.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/StringExtras.h"
44#include <set>
45using namespace llvm;
46
47STATISTIC(EmittedInsts, "Number of machine instrs printed");
48
49namespace {
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    /// stripRegisterPrefix - This method strips the character prefix from a
91    /// register name so that only the number is left.  Used by for linux asm.
92    const char *stripRegisterPrefix(const char *RegName) {
93      switch (RegName[0]) {
94      case 'r':
95      case 'f':
96      case 'v': return RegName + 1;
97      case 'c': if (RegName[1] == 'r') return RegName + 2;
98      }
99
100      return RegName;
101    }
102
103    /// printRegister - Print register according to target requirements.
104    ///
105    void printRegister(const MachineOperand &MO, bool R0AsZero) {
106      unsigned RegNo = MO.getReg();
107      assert(MRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
108
109      // If we should use 0 for R0.
110      if (R0AsZero && RegNo == PPC::R0) {
111        O << "0";
112        return;
113      }
114
115      const char *RegName = TM.getRegisterInfo()->get(RegNo).Name;
116      // Linux assembler (Others?) does not take register mnemonics.
117      // FIXME - What about special registers used in mfspr/mtspr?
118      if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
119      O << RegName;
120    }
121
122    void printOperand(const MachineInstr *MI, unsigned OpNo) {
123      const MachineOperand &MO = MI->getOperand(OpNo);
124      if (MO.isRegister()) {
125        printRegister(MO, false);
126      } else if (MO.isImmediate()) {
127        O << MO.getImmedValue();
128      } else {
129        printOp(MO);
130      }
131    }
132
133    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
134                         unsigned AsmVariant, const char *ExtraCode);
135    bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
136                               unsigned AsmVariant, const char *ExtraCode);
137
138
139    void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
140      char value = MI->getOperand(OpNo).getImmedValue();
141      value = (value << (32-5)) >> (32-5);
142      O << (int)value;
143    }
144    void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145      unsigned char value = MI->getOperand(OpNo).getImmedValue();
146      assert(value <= 31 && "Invalid u5imm argument!");
147      O << (unsigned int)value;
148    }
149    void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150      unsigned char value = MI->getOperand(OpNo).getImmedValue();
151      assert(value <= 63 && "Invalid u6imm argument!");
152      O << (unsigned int)value;
153    }
154    void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155      O << (short)MI->getOperand(OpNo).getImmedValue();
156    }
157    void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
158      O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
159    }
160    void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161      if (MI->getOperand(OpNo).isImmediate()) {
162        O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
163      } else {
164        O << "lo16(";
165        printOp(MI->getOperand(OpNo));
166        if (TM.getRelocationModel() == Reloc::PIC_)
167          O << "-\"L" << getFunctionNumber() << "$pb\")";
168        else
169          O << ')';
170      }
171    }
172    void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
173      // Branches can take an immediate operand.  This is used by the branch
174      // selection pass to print $+8, an eight byte displacement from the PC.
175      if (MI->getOperand(OpNo).isImmediate()) {
176        O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
177      } else {
178        printOp(MI->getOperand(OpNo));
179      }
180    }
181    void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
182      const MachineOperand &MO = MI->getOperand(OpNo);
183      if (TM.getRelocationModel() != Reloc::Static) {
184        if (MO.getType() == MachineOperand::MO_GlobalAddress) {
185          GlobalValue *GV = MO.getGlobal();
186          if (((GV->isExternal() || GV->hasWeakLinkage() ||
187                GV->hasLinkOnceLinkage()))) {
188            // Dynamically-resolved functions need a stub for the function.
189            std::string Name = Mang->getValueName(GV);
190            FnStubs.insert(Name);
191            O << "L" << Name << "$stub";
192            if (GV->hasExternalWeakLinkage())
193              ExtWeakSymbols.insert(GV);
194            return;
195          }
196        }
197        if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
198          std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
199          FnStubs.insert(Name);
200          O << "L" << Name << "$stub";
201          return;
202        }
203      }
204
205      printOp(MI->getOperand(OpNo));
206    }
207    void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
208     O << (int)MI->getOperand(OpNo).getImmedValue()*4;
209    }
210    void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
211      O << "\"L" << getFunctionNumber() << "$pb\"\n";
212      O << "\"L" << getFunctionNumber() << "$pb\":";
213    }
214    void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
215      if (MI->getOperand(OpNo).isImmediate()) {
216        printS16ImmOperand(MI, OpNo);
217      } else {
218        O << "ha16(";
219        printOp(MI->getOperand(OpNo));
220        if (TM.getRelocationModel() == Reloc::PIC_)
221          O << "-\"L" << getFunctionNumber() << "$pb\")";
222        else
223          O << ')';
224      }
225    }
226    void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
227      if (MI->getOperand(OpNo).isImmediate()) {
228        printS16ImmOperand(MI, OpNo);
229      } else {
230        O << "lo16(";
231        printOp(MI->getOperand(OpNo));
232        if (TM.getRelocationModel() == Reloc::PIC_)
233          O << "-\"L" << getFunctionNumber() << "$pb\")";
234        else
235          O << ')';
236      }
237    }
238    void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
239      unsigned CCReg = MI->getOperand(OpNo).getReg();
240      unsigned RegNo = enumRegToMachineReg(CCReg);
241      O << (0x80 >> RegNo);
242    }
243    // The new addressing mode printers.
244    void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
245      printSymbolLo(MI, OpNo);
246      O << '(';
247      if (MI->getOperand(OpNo+1).isRegister() &&
248          MI->getOperand(OpNo+1).getReg() == PPC::R0)
249        O << "0";
250      else
251        printOperand(MI, OpNo+1);
252      O << ')';
253    }
254    void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
255      if (MI->getOperand(OpNo).isImmediate())
256        printS16X4ImmOperand(MI, OpNo);
257      else
258        printSymbolLo(MI, OpNo);
259      O << '(';
260      if (MI->getOperand(OpNo+1).isRegister() &&
261          MI->getOperand(OpNo+1).getReg() == PPC::R0)
262        O << "0";
263      else
264        printOperand(MI, OpNo+1);
265      O << ')';
266    }
267
268    void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
269      // When used as the base register, r0 reads constant zero rather than
270      // the value contained in the register.  For this reason, the darwin
271      // assembler requires that we print r0 as 0 (no r) when used as the base.
272      const MachineOperand &MO = MI->getOperand(OpNo);
273      printRegister(MO, true);
274      O << ", ";
275      printOperand(MI, OpNo+1);
276    }
277
278    void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
279                               const char *Modifier);
280
281    virtual bool runOnMachineFunction(MachineFunction &F) = 0;
282    virtual bool doFinalization(Module &M) = 0;
283  };
284
285  /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
286  struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
287
288    DwarfWriter DW;
289
290    LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
291                    const TargetAsmInfo *T)
292      : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
293    }
294
295    virtual const char *getPassName() const {
296      return "Linux PPC Assembly Printer";
297    }
298
299    bool runOnMachineFunction(MachineFunction &F);
300    bool doInitialization(Module &M);
301    bool doFinalization(Module &M);
302
303    void getAnalysisUsage(AnalysisUsage &AU) const {
304      AU.setPreservesAll();
305      AU.addRequired<MachineDebugInfo>();
306      PPCAsmPrinter::getAnalysisUsage(AU);
307    }
308
309    /// getSectionForFunction - Return the section that we should emit the
310    /// specified function body into.
311    virtual std::string getSectionForFunction(const Function &F) const;
312  };
313
314  /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
315  /// X
316  struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
317
318    DwarfWriter DW;
319
320    DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
321                     const TargetAsmInfo *T)
322      : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
323    }
324
325    virtual const char *getPassName() const {
326      return "Darwin PPC Assembly Printer";
327    }
328
329    bool runOnMachineFunction(MachineFunction &F);
330    bool doInitialization(Module &M);
331    bool doFinalization(Module &M);
332
333    void getAnalysisUsage(AnalysisUsage &AU) const {
334      AU.setPreservesAll();
335      AU.addRequired<MachineDebugInfo>();
336      PPCAsmPrinter::getAnalysisUsage(AU);
337    }
338
339    /// getSectionForFunction - Return the section that we should emit the
340    /// specified function body into.
341    virtual std::string getSectionForFunction(const Function &F) const;
342  };
343} // end of anonymous namespace
344
345// Include the auto-generated portion of the assembly writer
346#include "PPCGenAsmWriter.inc"
347
348void PPCAsmPrinter::printOp(const MachineOperand &MO) {
349  switch (MO.getType()) {
350  case MachineOperand::MO_Immediate:
351    cerr << "printOp() does not handle immediate values\n";
352    abort();
353    return;
354
355  case MachineOperand::MO_MachineBasicBlock:
356    printBasicBlockLabel(MO.getMachineBasicBlock());
357    return;
358  case MachineOperand::MO_JumpTableIndex:
359    O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
360      << '_' << MO.getJumpTableIndex();
361    // FIXME: PIC relocation model
362    return;
363  case MachineOperand::MO_ConstantPoolIndex:
364    O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
365      << '_' << MO.getConstantPoolIndex();
366    return;
367  case MachineOperand::MO_ExternalSymbol:
368    // Computing the address of an external symbol, not calling it.
369    if (TM.getRelocationModel() != Reloc::Static) {
370      std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
371      GVStubs.insert(Name);
372      O << "L" << Name << "$non_lazy_ptr";
373      return;
374    }
375    O << TAI->getGlobalPrefix() << MO.getSymbolName();
376    return;
377  case MachineOperand::MO_GlobalAddress: {
378    // Computing the address of a global symbol, not calling it.
379    GlobalValue *GV = MO.getGlobal();
380    std::string Name = Mang->getValueName(GV);
381
382    // External or weakly linked global variables need non-lazily-resolved stubs
383    if (TM.getRelocationModel() != Reloc::Static) {
384      if (((GV->isExternal() || GV->hasWeakLinkage() ||
385            GV->hasLinkOnceLinkage()))) {
386        GVStubs.insert(Name);
387        O << "L" << Name << "$non_lazy_ptr";
388        return;
389      }
390    }
391    O << Name;
392
393    if (GV->hasExternalWeakLinkage())
394      ExtWeakSymbols.insert(GV);
395    return;
396  }
397
398  default:
399    O << "<unknown operand type: " << MO.getType() << ">";
400    return;
401  }
402}
403
404/// PrintAsmOperand - Print out an operand for an inline asm expression.
405///
406bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
407                                    unsigned AsmVariant,
408                                    const char *ExtraCode) {
409  // Does this asm operand have a single letter operand modifier?
410  if (ExtraCode && ExtraCode[0]) {
411    if (ExtraCode[1] != 0) return true; // Unknown modifier.
412
413    switch (ExtraCode[0]) {
414    default: return true;  // Unknown modifier.
415    case 'L': // Write second word of DImode reference.
416      // Verify that this operand has two consecutive registers.
417      if (!MI->getOperand(OpNo).isRegister() ||
418          OpNo+1 == MI->getNumOperands() ||
419          !MI->getOperand(OpNo+1).isRegister())
420        return true;
421      ++OpNo;   // Return the high-part.
422      break;
423    }
424  }
425
426  printOperand(MI, OpNo);
427  return false;
428}
429
430bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
431                                          unsigned AsmVariant,
432                                          const char *ExtraCode) {
433  if (ExtraCode && ExtraCode[0])
434    return true; // Unknown modifier.
435  printMemRegReg(MI, OpNo);
436  return false;
437}
438
439void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
440                                          const char *Modifier) {
441  assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
442  unsigned Code = MI->getOperand(OpNo).getImm();
443  if (!strcmp(Modifier, "cc")) {
444    switch ((PPC::Predicate)Code) {
445    case PPC::PRED_ALWAYS: return; // Don't print anything for always.
446    case PPC::PRED_LT: O << "lt"; return;
447    case PPC::PRED_LE: O << "le"; return;
448    case PPC::PRED_EQ: O << "eq"; return;
449    case PPC::PRED_GE: O << "ge"; return;
450    case PPC::PRED_GT: O << "gt"; return;
451    case PPC::PRED_NE: O << "ne"; return;
452    case PPC::PRED_UN: O << "un"; return;
453    case PPC::PRED_NU: O << "nu"; return;
454    }
455
456  } else {
457    assert(!strcmp(Modifier, "reg") &&
458           "Need to specify 'cc' or 'reg' as predicate op modifier!");
459    // Don't print the register for 'always'.
460    if (Code == PPC::PRED_ALWAYS) return;
461    printOperand(MI, OpNo+1);
462  }
463}
464
465
466/// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
467/// the current output stream.
468///
469void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
470  ++EmittedInsts;
471
472  // Check for slwi/srwi mnemonics.
473  if (MI->getOpcode() == PPC::RLWINM) {
474    bool FoundMnemonic = false;
475    unsigned char SH = MI->getOperand(2).getImmedValue();
476    unsigned char MB = MI->getOperand(3).getImmedValue();
477    unsigned char ME = MI->getOperand(4).getImmedValue();
478    if (SH <= 31 && MB == 0 && ME == (31-SH)) {
479      O << "slwi "; FoundMnemonic = true;
480    }
481    if (SH <= 31 && MB == (32-SH) && ME == 31) {
482      O << "srwi "; FoundMnemonic = true;
483      SH = 32-SH;
484    }
485    if (FoundMnemonic) {
486      printOperand(MI, 0);
487      O << ", ";
488      printOperand(MI, 1);
489      O << ", " << (unsigned int)SH << "\n";
490      return;
491    }
492  } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
493    if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
494      O << "mr ";
495      printOperand(MI, 0);
496      O << ", ";
497      printOperand(MI, 1);
498      O << "\n";
499      return;
500    }
501  } else if (MI->getOpcode() == PPC::RLDICR) {
502    unsigned char SH = MI->getOperand(2).getImmedValue();
503    unsigned char ME = MI->getOperand(3).getImmedValue();
504    // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
505    if (63-SH == ME) {
506      O << "sldi ";
507      printOperand(MI, 0);
508      O << ", ";
509      printOperand(MI, 1);
510      O << ", " << (unsigned int)SH << "\n";
511      return;
512    }
513  }
514
515  if (printInstruction(MI))
516    return; // Printer was automatically generated
517
518  assert(0 && "Unhandled instruction in asm writer!");
519  abort();
520  return;
521}
522
523/// runOnMachineFunction - This uses the printMachineInstruction()
524/// method to print assembly for each instruction.
525///
526bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
527  DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
528
529  SetupMachineFunction(MF);
530  O << "\n\n";
531
532  // Print out constants referenced by the function
533  EmitConstantPool(MF.getConstantPool());
534
535  // Print out labels for the function.
536  const Function *F = MF.getFunction();
537  SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
538
539  switch (F->getLinkage()) {
540  default: assert(0 && "Unknown linkage type!");
541  case Function::InternalLinkage:  // Symbols default to internal.
542    break;
543  case Function::ExternalLinkage:
544    O << "\t.global\t" << CurrentFnName << '\n'
545      << "\t.type\t" << CurrentFnName << ", @function\n";
546    break;
547  case Function::WeakLinkage:
548  case Function::LinkOnceLinkage:
549    O << "\t.global\t" << CurrentFnName << '\n';
550    O << "\t.weak\t" << CurrentFnName << '\n';
551    break;
552  }
553  EmitAlignment(2, F);
554  O << CurrentFnName << ":\n";
555
556  // Emit pre-function debug information.
557  DW.BeginFunction(&MF);
558
559  // Print out code for the function.
560  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
561       I != E; ++I) {
562    // Print a label for the basic block.
563    if (I != MF.begin()) {
564      printBasicBlockLabel(I, true);
565      O << '\n';
566    }
567    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
568         II != E; ++II) {
569      // Print the assembly for the instruction.
570      O << "\t";
571      printMachineInstruction(II);
572    }
573  }
574
575  O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
576
577  // Print out jump tables referenced by the function.
578  EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
579
580  // Emit post-function debug information.
581  DW.EndFunction();
582
583  // We didn't modify anything.
584  return false;
585}
586
587bool LinuxAsmPrinter::doInitialization(Module &M) {
588  AsmPrinter::doInitialization(M);
589
590  // GNU as handles section names wrapped in quotes
591  Mang->setUseQuotes(true);
592
593  SwitchToTextSection(TAI->getTextSection());
594
595  // Emit initial debug information.
596  DW.BeginModule(&M);
597  return false;
598}
599
600bool LinuxAsmPrinter::doFinalization(Module &M) {
601  const TargetData *TD = TM.getTargetData();
602
603  // Print out module-level global variables here.
604  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
605       I != E; ++I) {
606    if (!I->hasInitializer()) continue;   // External global require no code
607
608    // Check to see if this is a special global used by LLVM, if so, emit it.
609    if (EmitSpecialLLVMGlobal(I))
610      continue;
611
612    std::string name = Mang->getValueName(I);
613    Constant *C = I->getInitializer();
614    unsigned Size = TD->getTypeSize(C->getType());
615    unsigned Align = TD->getPreferredAlignmentLog(I);
616
617    if (C->isNullValue() && /* FIXME: Verify correct */
618        (I->hasInternalLinkage() || I->hasWeakLinkage() ||
619         I->hasLinkOnceLinkage() ||
620         (I->hasExternalLinkage() && !I->hasSection()))) {
621      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
622      if (I->hasExternalLinkage()) {
623        O << "\t.global " << name << '\n';
624        O << "\t.type " << name << ", @object\n";
625        //O << "\t.zerofill __DATA, __common, " << name << ", "
626        //  << Size << ", " << Align;
627      } else if (I->hasInternalLinkage()) {
628        SwitchToDataSection("\t.data", I);
629        O << TAI->getLCOMMDirective() << name << "," << Size;
630      } else {
631        SwitchToDataSection("\t.data", I);
632        O << ".comm " << name << "," << Size;
633      }
634      O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
635    } else {
636      switch (I->getLinkage()) {
637      case GlobalValue::LinkOnceLinkage:
638      case GlobalValue::WeakLinkage:
639        O << "\t.global " << name << '\n'
640          << "\t.type " << name << ", @object\n"
641          << "\t.weak " << name << '\n';
642        SwitchToDataSection("\t.data", I);
643        break;
644      case GlobalValue::AppendingLinkage:
645        // FIXME: appending linkage variables should go into a section of
646        // their name or something.  For now, just emit them as external.
647      case GlobalValue::ExternalLinkage:
648        // If external or appending, declare as a global symbol
649        O << "\t.global " << name << "\n"
650          << "\t.type " << name << ", @object\n";
651        // FALL THROUGH
652      case GlobalValue::InternalLinkage:
653        if (I->isConstant()) {
654          const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
655          if (TAI->getCStringSection() && CVA && CVA->isCString()) {
656            SwitchToDataSection(TAI->getCStringSection(), I);
657            break;
658          }
659        }
660
661        // FIXME: special handling for ".ctors" & ".dtors" sections
662        if (I->hasSection() &&
663            (I->getSection() == ".ctors" ||
664             I->getSection() == ".dtors")) {
665          std::string SectionName = ".section " + I->getSection()
666                                                + ",\"aw\",@progbits";
667          SwitchToDataSection(SectionName.c_str());
668        } else {
669          SwitchToDataSection(TAI->getDataSection(), I);
670        }
671        break;
672      default:
673        cerr << "Unknown linkage type!";
674        abort();
675      }
676
677      EmitAlignment(Align, I);
678      O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
679        << I->getName() << "'\n";
680
681      // If the initializer is a extern weak symbol, remember to emit the weak
682      // reference!
683      if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
684        if (GV->hasExternalWeakLinkage())
685          ExtWeakSymbols.insert(GV);
686
687      EmitGlobalConstant(C);
688      O << '\n';
689    }
690  }
691
692  // TODO
693
694  // Emit initial debug information.
695  DW.EndModule();
696
697  AsmPrinter::doFinalization(M);
698  return false; // success
699}
700
701std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
702  switch (F.getLinkage()) {
703  default: assert(0 && "Unknown linkage type!");
704  case Function::ExternalLinkage:
705  case Function::InternalLinkage: return TAI->getTextSection();
706  case Function::WeakLinkage:
707  case Function::LinkOnceLinkage:
708    return ".text";
709  }
710}
711
712std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
713  switch (F.getLinkage()) {
714  default: assert(0 && "Unknown linkage type!");
715  case Function::ExternalLinkage:
716  case Function::InternalLinkage: return TAI->getTextSection();
717  case Function::WeakLinkage:
718  case Function::LinkOnceLinkage:
719    return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
720  }
721}
722
723/// runOnMachineFunction - This uses the printMachineInstruction()
724/// method to print assembly for each instruction.
725///
726bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
727  DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
728
729  SetupMachineFunction(MF);
730  O << "\n\n";
731
732  // Print out constants referenced by the function
733  EmitConstantPool(MF.getConstantPool());
734
735  // Print out labels for the function.
736  const Function *F = MF.getFunction();
737  SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
738
739  switch (F->getLinkage()) {
740  default: assert(0 && "Unknown linkage type!");
741  case Function::InternalLinkage:  // Symbols default to internal.
742    break;
743  case Function::ExternalLinkage:
744    O << "\t.globl\t" << CurrentFnName << "\n";
745    break;
746  case Function::WeakLinkage:
747  case Function::LinkOnceLinkage:
748    O << "\t.globl\t" << CurrentFnName << "\n";
749    O << "\t.weak_definition\t" << CurrentFnName << "\n";
750    break;
751  }
752  EmitAlignment(4, F);
753  O << CurrentFnName << ":\n";
754
755  // Emit pre-function debug information.
756  DW.BeginFunction(&MF);
757
758  // Print out code for the function.
759  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
760       I != E; ++I) {
761    // Print a label for the basic block.
762    if (I != MF.begin()) {
763      printBasicBlockLabel(I, true);
764      O << '\n';
765    }
766    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
767         II != E; ++II) {
768      // Print the assembly for the instruction.
769      O << "\t";
770      printMachineInstruction(II);
771    }
772  }
773
774  // Print out jump tables referenced by the function.
775  EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
776
777  // Emit post-function debug information.
778  DW.EndFunction();
779
780  // We didn't modify anything.
781  return false;
782}
783
784
785bool DarwinAsmPrinter::doInitialization(Module &M) {
786  static const char *CPUDirectives[] = {
787    "ppc",
788    "ppc601",
789    "ppc602",
790    "ppc603",
791    "ppc7400",
792    "ppc750",
793    "ppc970",
794    "ppc64"
795  };
796
797  unsigned Directive = Subtarget.getDarwinDirective();
798  if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
799    Directive = PPC::DIR_970;
800  if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
801    Directive = PPC::DIR_7400;
802  if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
803    Directive = PPC::DIR_64;
804  assert(Directive <= PPC::DIR_64 && "Directive out of range.");
805  O << "\t.machine " << CPUDirectives[Directive] << "\n";
806
807  AsmPrinter::doInitialization(M);
808
809  // Darwin wants symbols to be quoted if they have complex names.
810  Mang->setUseQuotes(true);
811
812  // Prime text sections so they are adjacent.  This reduces the likelihood a
813  // large data or debug section causes a branch to exceed 16M limit.
814  SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
815                      "pure_instructions");
816  if (TM.getRelocationModel() == Reloc::PIC_) {
817    SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
818                          "pure_instructions,32");
819  } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
820    SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
821                        "pure_instructions,16");
822  }
823  SwitchToTextSection(TAI->getTextSection());
824
825  // Emit initial debug information.
826  DW.BeginModule(&M);
827  return false;
828}
829
830bool DarwinAsmPrinter::doFinalization(Module &M) {
831  const TargetData *TD = TM.getTargetData();
832
833  // Print out module-level global variables here.
834  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
835       I != E; ++I) {
836    if (!I->hasInitializer()) continue;   // External global require no code
837
838    // Check to see if this is a special global used by LLVM, if so, emit it.
839    if (EmitSpecialLLVMGlobal(I))
840      continue;
841
842    std::string name = Mang->getValueName(I);
843    Constant *C = I->getInitializer();
844    unsigned Size = TD->getTypeSize(C->getType());
845    unsigned Align = TD->getPreferredAlignmentLog(I);
846
847    if (C->isNullValue() && /* FIXME: Verify correct */
848        (I->hasInternalLinkage() || I->hasWeakLinkage() ||
849         I->hasLinkOnceLinkage() ||
850         (I->hasExternalLinkage() && !I->hasSection()))) {
851      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
852      if (I->hasExternalLinkage()) {
853        O << "\t.globl " << name << '\n';
854        O << "\t.zerofill __DATA, __common, " << name << ", "
855          << Size << ", " << Align;
856      } else if (I->hasInternalLinkage()) {
857        SwitchToDataSection("\t.data", I);
858        O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
859      } else {
860        SwitchToDataSection("\t.data", I);
861        O << ".comm " << name << "," << Size;
862      }
863      O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
864    } else {
865      switch (I->getLinkage()) {
866      case GlobalValue::LinkOnceLinkage:
867      case GlobalValue::WeakLinkage:
868        O << "\t.globl " << name << '\n'
869          << "\t.weak_definition " << name << '\n';
870        SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
871        break;
872      case GlobalValue::AppendingLinkage:
873        // FIXME: appending linkage variables should go into a section of
874        // their name or something.  For now, just emit them as external.
875      case GlobalValue::ExternalLinkage:
876        // If external or appending, declare as a global symbol
877        O << "\t.globl " << name << "\n";
878        // FALL THROUGH
879      case GlobalValue::InternalLinkage:
880        if (I->isConstant()) {
881          const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
882          if (TAI->getCStringSection() && CVA && CVA->isCString()) {
883            SwitchToDataSection(TAI->getCStringSection(), I);
884            break;
885          }
886        }
887
888        SwitchToDataSection("\t.data", I);
889        break;
890      default:
891        cerr << "Unknown linkage type!";
892        abort();
893      }
894
895      EmitAlignment(Align, I);
896      O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
897        << I->getName() << "'\n";
898
899      // If the initializer is a extern weak symbol, remember to emit the weak
900      // reference!
901      if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
902        if (GV->hasExternalWeakLinkage())
903          ExtWeakSymbols.insert(GV);
904
905      EmitGlobalConstant(C);
906      O << '\n';
907    }
908  }
909
910  bool isPPC64 = TD->getPointerSizeInBits() == 64;
911
912  // Output stubs for dynamically-linked functions
913  if (TM.getRelocationModel() == Reloc::PIC_) {
914    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
915         i != e; ++i) {
916      SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
917                          "pure_instructions,32");
918      EmitAlignment(4);
919      O << "L" << *i << "$stub:\n";
920      O << "\t.indirect_symbol " << *i << "\n";
921      O << "\tmflr r0\n";
922      O << "\tbcl 20,31,L0$" << *i << "\n";
923      O << "L0$" << *i << ":\n";
924      O << "\tmflr r11\n";
925      O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
926      O << "\tmtlr r0\n";
927      if (isPPC64)
928        O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
929      else
930        O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
931      O << "\tmtctr r12\n";
932      O << "\tbctr\n";
933      SwitchToDataSection(".lazy_symbol_pointer");
934      O << "L" << *i << "$lazy_ptr:\n";
935      O << "\t.indirect_symbol " << *i << "\n";
936      if (isPPC64)
937        O << "\t.quad dyld_stub_binding_helper\n";
938      else
939        O << "\t.long dyld_stub_binding_helper\n";
940    }
941  } else {
942    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
943         i != e; ++i) {
944      SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
945                          "pure_instructions,16");
946      EmitAlignment(4);
947      O << "L" << *i << "$stub:\n";
948      O << "\t.indirect_symbol " << *i << "\n";
949      O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
950      if (isPPC64)
951        O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
952      else
953        O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
954      O << "\tmtctr r12\n";
955      O << "\tbctr\n";
956      SwitchToDataSection(".lazy_symbol_pointer");
957      O << "L" << *i << "$lazy_ptr:\n";
958      O << "\t.indirect_symbol " << *i << "\n";
959      if (isPPC64)
960        O << "\t.quad dyld_stub_binding_helper\n";
961      else
962        O << "\t.long dyld_stub_binding_helper\n";
963    }
964  }
965
966  O << "\n";
967
968  // Output stubs for external and common global variables.
969  if (GVStubs.begin() != GVStubs.end()) {
970    SwitchToDataSection(".non_lazy_symbol_pointer");
971    for (std::set<std::string>::iterator I = GVStubs.begin(),
972         E = GVStubs.end(); I != E; ++I) {
973      O << "L" << *I << "$non_lazy_ptr:\n";
974      O << "\t.indirect_symbol " << *I << "\n";
975      if (isPPC64)
976        O << "\t.quad\t0\n";
977      else
978        O << "\t.long\t0\n";
979
980    }
981  }
982
983  // Emit initial debug information.
984  DW.EndModule();
985
986  // Funny Darwin hack: This flag tells the linker that no global symbols
987  // contain code that falls through to other global symbols (e.g. the obvious
988  // implementation of multiple entry points).  If this doesn't occur, the
989  // linker can safely perform dead code stripping.  Since LLVM never generates
990  // code that does this, it is always safe to set.
991  O << "\t.subsections_via_symbols\n";
992
993  AsmPrinter::doFinalization(M);
994  return false; // success
995}
996
997
998
999/// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1000/// for a MachineFunction to the given output stream, in a format that the
1001/// Darwin assembler can deal with.
1002///
1003FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1004                                            PPCTargetMachine &tm) {
1005  const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1006
1007  if (Subtarget->isDarwin()) {
1008    return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1009  } else {
1010    return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1011  }
1012}
1013
1014