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