PPCAsmPrinter.cpp revision 7809811e4ed3c2462efa327cef0464b9844baea2
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/Target/MRegisterInfo.h"
37#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetOptions.h"
39#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
41#include <iostream>
42#include <set>
43using namespace llvm;
44
45namespace {
46  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
47
48  class PPCAsmPrinter : public AsmPrinter {
49  public:
50    std::set<std::string> FnStubs, GVStubs;
51
52    PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
53      : AsmPrinter(O, TM) {}
54
55    virtual const char *getPassName() const {
56      return "PowerPC Assembly Printer";
57    }
58
59    PPCTargetMachine &getTM() {
60      return static_cast<PPCTargetMachine&>(TM);
61    }
62
63    unsigned enumRegToMachineReg(unsigned enumReg) {
64      switch (enumReg) {
65      default: assert(0 && "Unhandled register!"); break;
66      case PPC::CR0:  return  0;
67      case PPC::CR1:  return  1;
68      case PPC::CR2:  return  2;
69      case PPC::CR3:  return  3;
70      case PPC::CR4:  return  4;
71      case PPC::CR5:  return  5;
72      case PPC::CR6:  return  6;
73      case PPC::CR7:  return  7;
74      }
75      abort();
76    }
77
78    /// printInstruction - This method is automatically generated by tablegen
79    /// from the instruction set description.  This method returns true if the
80    /// machine instruction was sufficiently described to print it, otherwise it
81    /// returns false.
82    bool printInstruction(const MachineInstr *MI);
83
84    void printMachineInstruction(const MachineInstr *MI);
85    void printOp(const MachineOperand &MO);
86
87    void printOperand(const MachineInstr *MI, unsigned OpNo) {
88      const MachineOperand &MO = MI->getOperand(OpNo);
89      if (MO.getType() == MachineOperand::MO_MachineRegister) {
90        assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
91        O << TM.getRegisterInfo()->get(MO.getReg()).Name;
92      } else if (MO.isImmediate()) {
93        O << MO.getImmedValue();
94      } else {
95        printOp(MO);
96      }
97    }
98
99    bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
100                         unsigned AsmVariant, const char *ExtraCode);
101    bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
102                               unsigned AsmVariant, const char *ExtraCode);
103
104
105    void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
106      unsigned char value = MI->getOperand(OpNo).getImmedValue();
107      assert(value <= 31 && "Invalid u5imm argument!");
108      O << (unsigned int)value;
109    }
110    void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
111      unsigned char value = MI->getOperand(OpNo).getImmedValue();
112      assert(value <= 63 && "Invalid u6imm argument!");
113      O << (unsigned int)value;
114    }
115    void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
116      O << (short)MI->getOperand(OpNo).getImmedValue();
117    }
118    void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
119      O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
120    }
121    void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
122      O << (short)MI->getOperand(OpNo).getImmedValue()*4;
123    }
124    void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
125      // Branches can take an immediate operand.  This is used by the branch
126      // selection pass to print $+8, an eight byte displacement from the PC.
127      if (MI->getOperand(OpNo).isImmediate()) {
128        O << "$+" << MI->getOperand(OpNo).getImmedValue();
129      } else {
130        printOp(MI->getOperand(OpNo));
131      }
132    }
133    void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
134      const MachineOperand &MO = MI->getOperand(OpNo);
135      if (TM.getRelocationModel() != Reloc::Static) {
136        if (MO.getType() == MachineOperand::MO_GlobalAddress) {
137          GlobalValue *GV = MO.getGlobal();
138          if (((GV->isExternal() || GV->hasWeakLinkage() ||
139                GV->hasLinkOnceLinkage()))) {
140            // Dynamically-resolved functions need a stub for the function.
141            std::string Name = Mang->getValueName(GV);
142            FnStubs.insert(Name);
143            O << "L" << Name << "$stub";
144            return;
145          }
146        }
147        if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
148          std::string Name(GlobalPrefix); Name += MO.getSymbolName();
149          FnStubs.insert(Name);
150          O << "L" << Name << "$stub";
151          return;
152        }
153      }
154
155      printOp(MI->getOperand(OpNo));
156    }
157    void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
158     O << (int)MI->getOperand(OpNo).getImmedValue()*4;
159    }
160    void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
161      O << "\"L" << getFunctionNumber() << "$pb\"\n";
162      O << "\"L" << getFunctionNumber() << "$pb\":";
163    }
164    void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
165      if (MI->getOperand(OpNo).isImmediate()) {
166        printS16ImmOperand(MI, OpNo);
167      } else {
168        O << "ha16(";
169        printOp(MI->getOperand(OpNo));
170        if (TM.getRelocationModel() == Reloc::PIC)
171          O << "-\"L" << getFunctionNumber() << "$pb\")";
172        else
173          O << ')';
174      }
175    }
176    void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
177      if (MI->getOperand(OpNo).isImmediate()) {
178        printS16ImmOperand(MI, OpNo);
179      } else {
180        O << "lo16(";
181        printOp(MI->getOperand(OpNo));
182        if (TM.getRelocationModel() == Reloc::PIC)
183          O << "-\"L" << getFunctionNumber() << "$pb\")";
184        else
185          O << ')';
186      }
187    }
188    void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
189      unsigned CCReg = MI->getOperand(OpNo).getReg();
190      unsigned RegNo = enumRegToMachineReg(CCReg);
191      O << (0x80 >> RegNo);
192    }
193    // The new addressing mode printers.
194    void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
195      printSymbolLo(MI, OpNo);
196      O << '(';
197      printOperand(MI, OpNo+1);
198      O << ')';
199    }
200    void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
201      // When used as the base register, r0 reads constant zero rather than
202      // the value contained in the register.  For this reason, the darwin
203      // assembler requires that we print r0 as 0 (no r) when used as the base.
204      const MachineOperand &MO = MI->getOperand(OpNo);
205      if (MO.getReg() == PPC::R0)
206        O << '0';
207      else
208        O << TM.getRegisterInfo()->get(MO.getReg()).Name;
209      O << ", ";
210      printOperand(MI, OpNo+1);
211    }
212
213    virtual bool runOnMachineFunction(MachineFunction &F) = 0;
214    virtual bool doFinalization(Module &M) = 0;
215
216  };
217
218  /// DarwinDwarfWriter - Dwarf debug info writer customized for Darwin/Mac OS X
219  ///
220  struct DarwinDwarfWriter : public DwarfWriter {
221    // Ctor.
222    DarwinDwarfWriter(std::ostream &o, AsmPrinter *ap)
223    : DwarfWriter(o, ap)
224    {
225      needsSet = true;
226      DwarfAbbrevSection = ".section __DWARFA,__debug_abbrev";
227      DwarfInfoSection = ".section __DWARFA,__debug_info";
228      DwarfLineSection = ".section __DWARFA,__debug_line";
229      DwarfFrameSection = ".section __DWARFA,__debug_frame";
230      DwarfPubNamesSection = ".section __DWARFA,__debug_pubnames";
231      DwarfPubTypesSection = ".section __DWARFA,__debug_pubtypes";
232      DwarfStrSection = ".section __DWARFA,__debug_str";
233      DwarfLocSection = ".section __DWARFA,__debug_loc";
234      DwarfARangesSection = ".section __DWARFA,__debug_aranges";
235      DwarfRangesSection = ".section __DWARFA,__debug_ranges";
236      DwarfMacInfoSection = ".section __DWARFA,__debug_macinfo";
237      TextSection = ".text";
238      DataSection = ".data";
239    }
240  };
241
242  /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
243  /// X
244  struct DarwinAsmPrinter : public PPCAsmPrinter {
245
246    DarwinDwarfWriter DW;
247
248    DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
249      : PPCAsmPrinter(O, TM), DW(O, this) {
250      CommentString = ";";
251      GlobalPrefix = "_";
252      PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
253      ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
254      Data64bitsDirective = 0;       // we can't emit a 64-bit unit
255      AlignmentIsInBytes = false;    // Alignment is by power of 2.
256      ConstantPoolSection = "\t.const\t";
257      LCOMMDirective = "\t.lcomm\t";
258      StaticCtorsSection = ".mod_init_func";
259      StaticDtorsSection = ".mod_term_func";
260      InlineAsmStart = InlineAsmEnd = "";  // Don't use #APP/#NO_APP
261    }
262
263    virtual const char *getPassName() const {
264      return "Darwin PPC Assembly Printer";
265    }
266
267    bool runOnMachineFunction(MachineFunction &F);
268    bool doInitialization(Module &M);
269    bool doFinalization(Module &M);
270
271    void getAnalysisUsage(AnalysisUsage &AU) const {
272      AU.setPreservesAll();
273      AU.addRequired<MachineDebugInfo>();
274      PPCAsmPrinter::getAnalysisUsage(AU);
275    }
276
277  };
278
279  /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
280  ///
281  struct AIXAsmPrinter : public PPCAsmPrinter {
282    /// Map for labels corresponding to global variables
283    ///
284    std::map<const GlobalVariable*,std::string> GVToLabelMap;
285
286    AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
287      : PPCAsmPrinter(O, TM) {
288      CommentString = "#";
289      GlobalPrefix = ".";
290      ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
291      Data64bitsDirective = 0;       // we can't emit a 64-bit unit
292      AlignmentIsInBytes = false;    // Alignment is by power of 2.
293      ConstantPoolSection = "\t.const\t";
294    }
295
296    virtual const char *getPassName() const {
297      return "AIX PPC Assembly Printer";
298    }
299
300    bool runOnMachineFunction(MachineFunction &F);
301    bool doInitialization(Module &M);
302    bool doFinalization(Module &M);
303  };
304} // end of anonymous namespace
305
306/// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
307/// code for a MachineFunction to the given output stream, in a format that the
308/// Darwin assembler can deal with.
309///
310FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
311  return new DarwinAsmPrinter(o, tm);
312}
313
314/// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
315/// for a MachineFunction to the given output stream, in a format that the
316/// AIX 5L assembler can deal with.
317///
318FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
319  return new AIXAsmPrinter(o, tm);
320}
321
322// Include the auto-generated portion of the assembly writer
323#include "PPCGenAsmWriter.inc"
324
325void PPCAsmPrinter::printOp(const MachineOperand &MO) {
326  const MRegisterInfo &RI = *TM.getRegisterInfo();
327  int new_symbol;
328
329  switch (MO.getType()) {
330  case MachineOperand::MO_VirtualRegister:
331    if (Value *V = MO.getVRegValueOrNull()) {
332      O << "<" << V->getName() << ">";
333      return;
334    }
335    // FALLTHROUGH
336  case MachineOperand::MO_MachineRegister:
337  case MachineOperand::MO_CCRegister:
338    O << RI.get(MO.getReg()).Name;
339    return;
340
341  case MachineOperand::MO_SignExtendedImmed:
342  case MachineOperand::MO_UnextendedImmed:
343    std::cerr << "printOp() does not handle immediate values\n";
344    abort();
345    return;
346
347  case MachineOperand::MO_PCRelativeDisp:
348    std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
349    abort();
350    return;
351
352  case MachineOperand::MO_MachineBasicBlock: {
353    MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
354    O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << "_"
355      << MBBOp->getNumber() << "\t; " << MBBOp->getBasicBlock()->getName();
356    return;
357  }
358
359  case MachineOperand::MO_ConstantPoolIndex:
360    O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
361      << '_' << MO.getConstantPoolIndex();
362    return;
363  case MachineOperand::MO_ExternalSymbol:
364    // Computing the address of an external symbol, not calling it.
365    if (TM.getRelocationModel() != Reloc::Static) {
366      std::string Name(GlobalPrefix); Name += MO.getSymbolName();
367      GVStubs.insert(Name);
368      O << "L" << Name << "$non_lazy_ptr";
369      return;
370    }
371    O << GlobalPrefix << MO.getSymbolName();
372    return;
373  case MachineOperand::MO_GlobalAddress: {
374    // Computing the address of a global symbol, not calling it.
375    GlobalValue *GV = MO.getGlobal();
376    std::string Name = Mang->getValueName(GV);
377    int offset = MO.getOffset();
378
379    // External or weakly linked global variables need non-lazily-resolved stubs
380    if (TM.getRelocationModel() != Reloc::Static) {
381      if (((GV->isExternal() || GV->hasWeakLinkage() ||
382            GV->hasLinkOnceLinkage()))) {
383        GVStubs.insert(Name);
384        O << "L" << Name << "$non_lazy_ptr";
385        return;
386      }
387    }
388
389    O << Name;
390    return;
391  }
392
393  default:
394    O << "<unknown operand type: " << MO.getType() << ">";
395    return;
396  }
397}
398
399/// PrintAsmOperand - Print out an operand for an inline asm expression.
400///
401bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
402                                    unsigned AsmVariant,
403                                    const char *ExtraCode) {
404  // Does this asm operand have a single letter operand modifier?
405  if (ExtraCode && ExtraCode[0]) {
406    if (ExtraCode[1] != 0) return true; // Unknown modifier.
407
408    switch (ExtraCode[0]) {
409    default: return true;  // Unknown modifier.
410    case 'L': // Write second word of DImode reference.
411      // Verify that this operand has two consecutive registers.
412      if (!MI->getOperand(OpNo).isRegister() ||
413          OpNo+1 == MI->getNumOperands() ||
414          !MI->getOperand(OpNo+1).isRegister())
415        return true;
416      ++OpNo;   // Return the high-part.
417      break;
418    }
419  }
420
421  printOperand(MI, OpNo);
422  return false;
423}
424
425bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
426                                          unsigned AsmVariant,
427                                          const char *ExtraCode) {
428  if (ExtraCode && ExtraCode[0])
429    return true; // Unknown modifier.
430  printMemRegReg(MI, OpNo);
431  return false;
432}
433
434/// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
435/// the current output stream.
436///
437void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
438  ++EmittedInsts;
439
440  // Check for slwi/srwi mnemonics.
441  if (MI->getOpcode() == PPC::RLWINM) {
442    bool FoundMnemonic = false;
443    unsigned char SH = MI->getOperand(2).getImmedValue();
444    unsigned char MB = MI->getOperand(3).getImmedValue();
445    unsigned char ME = MI->getOperand(4).getImmedValue();
446    if (SH <= 31 && MB == 0 && ME == (31-SH)) {
447      O << "slwi "; FoundMnemonic = true;
448    }
449    if (SH <= 31 && MB == (32-SH) && ME == 31) {
450      O << "srwi "; FoundMnemonic = true;
451      SH = 32-SH;
452    }
453    if (FoundMnemonic) {
454      printOperand(MI, 0);
455      O << ", ";
456      printOperand(MI, 1);
457      O << ", " << (unsigned int)SH << "\n";
458      return;
459    }
460  } else if (MI->getOpcode() == PPC::OR4 || MI->getOpcode() == PPC::OR8) {
461    if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
462      O << "mr ";
463      printOperand(MI, 0);
464      O << ", ";
465      printOperand(MI, 1);
466      O << "\n";
467      return;
468    }
469  }
470
471  if (printInstruction(MI))
472    return; // Printer was automatically generated
473
474  assert(0 && "Unhandled instruction in asm writer!");
475  abort();
476  return;
477}
478
479
480/// runOnMachineFunction - This uses the printMachineInstruction()
481/// method to print assembly for each instruction.
482///
483bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
484  // FIXME - is this the earliest this can be set?
485  DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
486
487  SetupMachineFunction(MF);
488  O << "\n\n";
489
490  // Emit pre-function debug information.
491  DW.BeginFunction(MF);
492
493  // Print out constants referenced by the function
494  EmitConstantPool(MF.getConstantPool());
495
496  // Print out labels for the function.
497  const Function *F = MF.getFunction();
498  switch (F->getLinkage()) {
499  default: assert(0 && "Unknown linkage type!");
500  case Function::InternalLinkage:  // Symbols default to internal.
501    SwitchSection(".text", F);
502    break;
503  case Function::ExternalLinkage:
504    SwitchSection(".text", F);
505    O << "\t.globl\t" << CurrentFnName << "\n";
506    break;
507  case Function::WeakLinkage:
508  case Function::LinkOnceLinkage:
509    SwitchSection(".section __TEXT,__textcoal_nt,coalesced,pure_instructions",
510                  F);
511    O << "\t.globl\t" << CurrentFnName << "\n";
512    O << "\t.weak_definition\t" << CurrentFnName << "\n";
513    break;
514  }
515  EmitAlignment(4, F);
516  O << CurrentFnName << ":\n";
517
518  // Print out code for the function.
519  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
520       I != E; ++I) {
521    // Print a label for the basic block.
522    if (I != MF.begin()) {
523      O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
524        << I->getNumber() << ":\t";
525      if (!I->getBasicBlock()->getName().empty())
526        O << CommentString << " " << I->getBasicBlock()->getName();
527      O << "\n";
528    }
529    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
530         II != E; ++II) {
531      // Print the assembly for the instruction.
532      O << "\t";
533      printMachineInstruction(II);
534    }
535  }
536
537  // Emit post-function debug information.
538  DW.EndFunction(MF);
539
540  // We didn't modify anything.
541  return false;
542}
543
544
545bool DarwinAsmPrinter::doInitialization(Module &M) {
546  if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
547    O << "\t.machine ppc970\n";
548  AsmPrinter::doInitialization(M);
549
550  // Darwin wants symbols to be quoted if they have complex names.
551  Mang->setUseQuotes(true);
552
553  // Emit initial debug information.
554  DW.BeginModule(M);
555  return false;
556}
557
558bool DarwinAsmPrinter::doFinalization(Module &M) {
559  const TargetData &TD = TM.getTargetData();
560
561  // Print out module-level global variables here.
562  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
563       I != E; ++I) {
564    if (!I->hasInitializer()) continue;   // External global require no code
565
566    // Check to see if this is a special global used by LLVM, if so, emit it.
567    if (EmitSpecialLLVMGlobal(I))
568      continue;
569
570    std::string name = Mang->getValueName(I);
571    Constant *C = I->getInitializer();
572    unsigned Size = TD.getTypeSize(C->getType());
573    unsigned Align = getPreferredAlignmentLog(I);
574
575    if (C->isNullValue() && /* FIXME: Verify correct */
576        (I->hasInternalLinkage() || I->hasWeakLinkage() ||
577         I->hasLinkOnceLinkage() ||
578         (I->hasExternalLinkage() && !I->hasSection()))) {
579      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
580      if (I->hasExternalLinkage()) {
581        O << "\t.globl " << name << '\n';
582        O << "\t.zerofill __DATA, __common, " << name << ", "
583          << Size << ", " << Align;
584      } else if (I->hasInternalLinkage()) {
585        SwitchSection(".data", I);
586        O << LCOMMDirective << name << "," << Size << "," << Align;
587      } else {
588        SwitchSection(".data", I);
589        O << ".comm " << name << "," << Size;
590      }
591      O << "\t\t; '" << I->getName() << "'\n";
592    } else {
593      switch (I->getLinkage()) {
594      case GlobalValue::LinkOnceLinkage:
595      case GlobalValue::WeakLinkage:
596        O << "\t.globl " << name << '\n'
597          << "\t.weak_definition " << name << '\n';
598        SwitchSection(".section __DATA,__datacoal_nt,coalesced", I);
599        break;
600      case GlobalValue::AppendingLinkage:
601        // FIXME: appending linkage variables should go into a section of
602        // their name or something.  For now, just emit them as external.
603      case GlobalValue::ExternalLinkage:
604        // If external or appending, declare as a global symbol
605        O << "\t.globl " << name << "\n";
606        // FALL THROUGH
607      case GlobalValue::InternalLinkage:
608        SwitchSection(".data", I);
609        break;
610      default:
611        std::cerr << "Unknown linkage type!";
612        abort();
613      }
614
615      EmitAlignment(Align, I);
616      O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
617      EmitGlobalConstant(C);
618      O << '\n';
619    }
620  }
621
622  // Output stubs for dynamically-linked functions
623  if (TM.getRelocationModel() == Reloc::PIC) {
624    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
625         i != e; ++i) {
626      SwitchSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
627                    "pure_instructions,32", 0);
628      EmitAlignment(2);
629      O << "L" << *i << "$stub:\n";
630      O << "\t.indirect_symbol " << *i << "\n";
631      O << "\tmflr r0\n";
632      O << "\tbcl 20,31,L0$" << *i << "\n";
633      O << "L0$" << *i << ":\n";
634      O << "\tmflr r11\n";
635      O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
636      O << "\tmtlr r0\n";
637      O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
638      O << "\tmtctr r12\n";
639      O << "\tbctr\n";
640      SwitchSection(".lazy_symbol_pointer", 0);
641      O << "L" << *i << "$lazy_ptr:\n";
642      O << "\t.indirect_symbol " << *i << "\n";
643      O << "\t.long dyld_stub_binding_helper\n";
644    }
645  } else {
646    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
647         i != e; ++i) {
648      SwitchSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
649                    "pure_instructions,16", 0);
650      EmitAlignment(4);
651      O << "L" << *i << "$stub:\n";
652      O << "\t.indirect_symbol " << *i << "\n";
653      O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
654      O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
655      O << "\tmtctr r12\n";
656      O << "\tbctr\n";
657      SwitchSection(".lazy_symbol_pointer", 0);
658      O << "L" << *i << "$lazy_ptr:\n";
659      O << "\t.indirect_symbol " << *i << "\n";
660      O << "\t.long dyld_stub_binding_helper\n";
661    }
662  }
663
664  O << "\n";
665
666  // Output stubs for external and common global variables.
667  if (GVStubs.begin() != GVStubs.end()) {
668    SwitchSection(".non_lazy_symbol_pointer", 0);
669    for (std::set<std::string>::iterator I = GVStubs.begin(),
670         E = GVStubs.end(); I != E; ++I) {
671      O << "L" << *I << "$non_lazy_ptr:\n";
672      O << "\t.indirect_symbol " << *I << "\n";
673      O << "\t.long\t0\n";
674    }
675  }
676
677  // Emit initial debug information.
678  DW.EndModule(M);
679
680  // Funny Darwin hack: This flag tells the linker that no global symbols
681  // contain code that falls through to other global symbols (e.g. the obvious
682  // implementation of multiple entry points).  If this doesn't occur, the
683  // linker can safely perform dead code stripping.  Since LLVM never generates
684  // code that does this, it is always safe to set.
685  O << "\t.subsections_via_symbols\n";
686
687  AsmPrinter::doFinalization(M);
688  return false; // success
689}
690
691/// runOnMachineFunction - This uses the e()
692/// method to print assembly for each instruction.
693///
694bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
695  SetupMachineFunction(MF);
696
697  // Print out constants referenced by the function
698  EmitConstantPool(MF.getConstantPool());
699
700  // Print out header for the function.
701  O << "\t.csect .text[PR]\n"
702    << "\t.align 2\n"
703    << "\t.globl "  << CurrentFnName << '\n'
704    << "\t.globl ." << CurrentFnName << '\n'
705    << "\t.csect "  << CurrentFnName << "[DS],3\n"
706    << CurrentFnName << ":\n"
707    << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
708    << "\t.csect .text[PR]\n"
709    << '.' << CurrentFnName << ":\n";
710
711  // Print out code for the function.
712  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
713       I != E; ++I) {
714    // Print a label for the basic block.
715    O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
716      << I->getNumber()
717      << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
718    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
719      II != E; ++II) {
720      // Print the assembly for the instruction.
721      O << "\t";
722      printMachineInstruction(II);
723    }
724  }
725
726  O << "LT.." << CurrentFnName << ":\n"
727    << "\t.long 0\n"
728    << "\t.byte 0,0,32,65,128,0,0,0\n"
729    << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
730    << "\t.short 3\n"
731    << "\t.byte \"" << CurrentFnName << "\"\n"
732    << "\t.align 2\n";
733
734  // We didn't modify anything.
735  return false;
736}
737
738bool AIXAsmPrinter::doInitialization(Module &M) {
739  SwitchSection("", 0);
740  const TargetData &TD = TM.getTargetData();
741
742  O << "\t.machine \"ppc64\"\n"
743    << "\t.toc\n"
744    << "\t.csect .text[PR]\n";
745
746  // Print out module-level global variables
747  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
748       I != E; ++I) {
749    if (!I->hasInitializer())
750      continue;
751
752    std::string Name = I->getName();
753    Constant *C = I->getInitializer();
754    // N.B.: We are defaulting to writable strings
755    if (I->hasExternalLinkage()) {
756      O << "\t.globl " << Name << '\n'
757        << "\t.csect .data[RW],3\n";
758    } else {
759      O << "\t.csect _global.rw_c[RW],3\n";
760    }
761    O << Name << ":\n";
762    EmitGlobalConstant(C);
763  }
764
765  // Output labels for globals
766  if (M.global_begin() != M.global_end()) O << "\t.toc\n";
767  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
768       I != E; ++I) {
769    const GlobalVariable *GV = I;
770    // Do not output labels for unused variables
771    if (GV->isExternal() && GV->use_begin() == GV->use_end())
772      continue;
773
774    IncrementFunctionNumber();
775    std::string Name = GV->getName();
776    std::string Label = "LC.." + utostr(getFunctionNumber());
777    GVToLabelMap[GV] = Label;
778    O << Label << ":\n"
779      << "\t.tc " << Name << "[TC]," << Name;
780    if (GV->isExternal()) O << "[RW]";
781    O << '\n';
782   }
783
784  AsmPrinter::doInitialization(M);
785  return false; // success
786}
787
788bool AIXAsmPrinter::doFinalization(Module &M) {
789  const TargetData &TD = TM.getTargetData();
790  // Print out module-level global variables
791  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
792       I != E; ++I) {
793    if (I->hasInitializer() || I->hasExternalLinkage())
794      continue;
795
796    std::string Name = I->getName();
797    if (I->hasInternalLinkage()) {
798      O << "\t.lcomm " << Name << ",16,_global.bss_c";
799    } else {
800      O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
801        << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
802    }
803    O << "\t\t" << CommentString << " ";
804    WriteAsOperand(O, I, false, true, &M);
805    O << "\n";
806  }
807
808  O << "_section_.text:\n"
809    << "\t.csect .data[RW],3\n"
810    << "\t.llong _section_.text\n";
811  AsmPrinter::doFinalization(M);
812  return false; // success
813}
814