TargetRegistry: Change AsmPrinter constructor to be typed as returning an
[oota-llvm.git] / lib / Target / PowerPC / AsmPrinter / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "asmprinter"
20 #include "PPC.h"
21 #include "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/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/MC/MCSectionMachO.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSet.h"
51 using namespace llvm;
52
53 STATISTIC(EmittedInsts, "Number of machine instrs printed");
54
55 namespace {
56   class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
57   protected:
58     struct FnStubInfo {
59       std::string Stub, LazyPtr, AnonSymbol;
60       
61       FnStubInfo() {}
62       
63       void Init(const GlobalValue *GV, Mangler *Mang) {
64         // Already initialized.
65         if (!Stub.empty()) return;
66         Stub = Mang->getMangledName(GV, "$stub", true);
67         LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
68         AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
69       }
70
71       void Init(const std::string &GV, Mangler *Mang) {
72         // Already initialized.
73         if (!Stub.empty()) return;
74         Stub = Mang->makeNameProper(GV + "$stub",
75                                     Mangler::Private);
76         LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
77                                        Mangler::Private);
78         AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
79                                           Mangler::Private);
80       }
81     };
82     
83     StringMap<FnStubInfo> FnStubs;
84     StringMap<std::string> GVStubs, HiddenGVStubs;
85     const PPCSubtarget &Subtarget;
86   public:
87     explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
88                            const TargetAsmInfo *T, bool V)
89       : AsmPrinter(O, TM, T, V),
90         Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
91
92     virtual const char *getPassName() const {
93       return "PowerPC Assembly Printer";
94     }
95
96     PPCTargetMachine &getTM() {
97       return static_cast<PPCTargetMachine&>(TM);
98     }
99
100     unsigned enumRegToMachineReg(unsigned enumReg) {
101       switch (enumReg) {
102       default: llvm_unreachable("Unhandled register!");
103       case PPC::CR0:  return  0;
104       case PPC::CR1:  return  1;
105       case PPC::CR2:  return  2;
106       case PPC::CR3:  return  3;
107       case PPC::CR4:  return  4;
108       case PPC::CR5:  return  5;
109       case PPC::CR6:  return  6;
110       case PPC::CR7:  return  7;
111       }
112       llvm_unreachable(0);
113     }
114
115     /// printInstruction - This method is automatically generated by tablegen
116     /// from the instruction set description.  This method returns true if the
117     /// machine instruction was sufficiently described to print it, otherwise it
118     /// returns false.
119     void printInstruction(const MachineInstr *MI);
120
121     void printMachineInstruction(const MachineInstr *MI);
122     void printOp(const MachineOperand &MO);
123
124     /// stripRegisterPrefix - This method strips the character prefix from a
125     /// register name so that only the number is left.  Used by for linux asm.
126     const char *stripRegisterPrefix(const char *RegName) {
127       switch (RegName[0]) {
128       case 'r':
129       case 'f':
130       case 'v': return RegName + 1;
131       case 'c': if (RegName[1] == 'r') return RegName + 2;
132       }
133
134       return RegName;
135     }
136
137     /// printRegister - Print register according to target requirements.
138     ///
139     void printRegister(const MachineOperand &MO, bool R0AsZero) {
140       unsigned RegNo = MO.getReg();
141       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
142
143       // If we should use 0 for R0.
144       if (R0AsZero && RegNo == PPC::R0) {
145         O << "0";
146         return;
147       }
148
149       const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
150       // Linux assembler (Others?) does not take register mnemonics.
151       // FIXME - What about special registers used in mfspr/mtspr?
152       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
153       O << RegName;
154     }
155
156     void printOperand(const MachineInstr *MI, unsigned OpNo) {
157       const MachineOperand &MO = MI->getOperand(OpNo);
158       if (MO.isReg()) {
159         printRegister(MO, false);
160       } else if (MO.isImm()) {
161         O << MO.getImm();
162       } else {
163         printOp(MO);
164       }
165     }
166
167     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
168                          unsigned AsmVariant, const char *ExtraCode);
169     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
170                                unsigned AsmVariant, const char *ExtraCode);
171
172
173     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
174       char value = MI->getOperand(OpNo).getImm();
175       value = (value << (32-5)) >> (32-5);
176       O << (int)value;
177     }
178     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
179       unsigned char value = MI->getOperand(OpNo).getImm();
180       assert(value <= 31 && "Invalid u5imm argument!");
181       O << (unsigned int)value;
182     }
183     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
184       unsigned char value = MI->getOperand(OpNo).getImm();
185       assert(value <= 63 && "Invalid u6imm argument!");
186       O << (unsigned int)value;
187     }
188     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
189       O << (short)MI->getOperand(OpNo).getImm();
190     }
191     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
192       O << (unsigned short)MI->getOperand(OpNo).getImm();
193     }
194     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
195       if (MI->getOperand(OpNo).isImm()) {
196         O << (short)(MI->getOperand(OpNo).getImm()*4);
197       } else {
198         O << "lo16(";
199         printOp(MI->getOperand(OpNo));
200         if (TM.getRelocationModel() == Reloc::PIC_)
201           O << "-\"L" << getFunctionNumber() << "$pb\")";
202         else
203           O << ')';
204       }
205     }
206     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
207       // Branches can take an immediate operand.  This is used by the branch
208       // selection pass to print $+8, an eight byte displacement from the PC.
209       if (MI->getOperand(OpNo).isImm()) {
210         O << "$+" << MI->getOperand(OpNo).getImm()*4;
211       } else {
212         printOp(MI->getOperand(OpNo));
213       }
214     }
215     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
216       const MachineOperand &MO = MI->getOperand(OpNo);
217       if (TM.getRelocationModel() != Reloc::Static) {
218         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
219           GlobalValue *GV = MO.getGlobal();
220           if (GV->isDeclaration() || GV->isWeakForLinker()) {
221             // Dynamically-resolved functions need a stub for the function.
222             FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
223             FnInfo.Init(GV, Mang);
224             O << FnInfo.Stub;
225             return;
226           }
227         }
228         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
229           FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
230           FnInfo.Init(MO.getSymbolName(), Mang);
231           O << FnInfo.Stub;
232           return;
233         }
234       }
235
236       printOp(MI->getOperand(OpNo));
237     }
238     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
239      O << (int)MI->getOperand(OpNo).getImm()*4;
240     }
241     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
242       O << "\"L" << getFunctionNumber() << "$pb\"\n";
243       O << "\"L" << getFunctionNumber() << "$pb\":";
244     }
245     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
246       if (MI->getOperand(OpNo).isImm()) {
247         printS16ImmOperand(MI, OpNo);
248       } else {
249         if (Subtarget.isDarwin()) O << "ha16(";
250         printOp(MI->getOperand(OpNo));
251         if (TM.getRelocationModel() == Reloc::PIC_)
252           O << "-\"L" << getFunctionNumber() << "$pb\"";
253         if (Subtarget.isDarwin())
254           O << ')';
255         else
256           O << "@ha";
257       }
258     }
259     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
260       if (MI->getOperand(OpNo).isImm()) {
261         printS16ImmOperand(MI, OpNo);
262       } else {
263         if (Subtarget.isDarwin()) O << "lo16(";
264         printOp(MI->getOperand(OpNo));
265         if (TM.getRelocationModel() == Reloc::PIC_)
266           O << "-\"L" << getFunctionNumber() << "$pb\"";
267         if (Subtarget.isDarwin())
268           O << ')';
269         else
270           O << "@l";
271       }
272     }
273     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
274       unsigned CCReg = MI->getOperand(OpNo).getReg();
275       unsigned RegNo = enumRegToMachineReg(CCReg);
276       O << (0x80 >> RegNo);
277     }
278     // The new addressing mode printers.
279     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
280       printSymbolLo(MI, OpNo);
281       O << '(';
282       if (MI->getOperand(OpNo+1).isReg() &&
283           MI->getOperand(OpNo+1).getReg() == PPC::R0)
284         O << "0";
285       else
286         printOperand(MI, OpNo+1);
287       O << ')';
288     }
289     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
290       if (MI->getOperand(OpNo).isImm())
291         printS16X4ImmOperand(MI, OpNo);
292       else
293         printSymbolLo(MI, OpNo);
294       O << '(';
295       if (MI->getOperand(OpNo+1).isReg() &&
296           MI->getOperand(OpNo+1).getReg() == PPC::R0)
297         O << "0";
298       else
299         printOperand(MI, OpNo+1);
300       O << ')';
301     }
302
303     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
304       // When used as the base register, r0 reads constant zero rather than
305       // the value contained in the register.  For this reason, the darwin
306       // assembler requires that we print r0 as 0 (no r) when used as the base.
307       const MachineOperand &MO = MI->getOperand(OpNo);
308       printRegister(MO, true);
309       O << ", ";
310       printOperand(MI, OpNo+1);
311     }
312
313     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
314                                const char *Modifier);
315
316     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
317
318     virtual void EmitExternalGlobal(const GlobalVariable *GV);
319   };
320
321   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
322   class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
323   public:
324     explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
325                                 const TargetAsmInfo *T, bool V)
326       : PPCAsmPrinter(O, TM, T, V){}
327
328     virtual const char *getPassName() const {
329       return "Linux PPC Assembly Printer";
330     }
331
332     bool runOnMachineFunction(MachineFunction &F);
333
334     void getAnalysisUsage(AnalysisUsage &AU) const {
335       AU.setPreservesAll();
336       AU.addRequired<MachineModuleInfo>();
337       AU.addRequired<DwarfWriter>();
338       PPCAsmPrinter::getAnalysisUsage(AU);
339     }
340
341     void PrintGlobalVariable(const GlobalVariable *GVar);
342   };
343
344   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
345   /// OS X
346   class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
347     formatted_raw_ostream &OS;
348   public:
349     explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
350                                  const TargetAsmInfo *T, bool V)
351       : PPCAsmPrinter(O, TM, T, V), OS(O) {}
352
353     virtual const char *getPassName() const {
354       return "Darwin PPC Assembly Printer";
355     }
356
357     bool runOnMachineFunction(MachineFunction &F);
358     bool doInitialization(Module &M);
359     bool doFinalization(Module &M);
360
361     void getAnalysisUsage(AnalysisUsage &AU) const {
362       AU.setPreservesAll();
363       AU.addRequired<MachineModuleInfo>();
364       AU.addRequired<DwarfWriter>();
365       PPCAsmPrinter::getAnalysisUsage(AU);
366     }
367
368     void PrintGlobalVariable(const GlobalVariable *GVar);
369   };
370 } // end of anonymous namespace
371
372 // Include the auto-generated portion of the assembly writer
373 #include "PPCGenAsmWriter.inc"
374
375 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
376   switch (MO.getType()) {
377   case MachineOperand::MO_Immediate:
378     llvm_unreachable("printOp() does not handle immediate values");
379
380   case MachineOperand::MO_MachineBasicBlock:
381     printBasicBlockLabel(MO.getMBB());
382     return;
383   case MachineOperand::MO_JumpTableIndex:
384     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
385       << '_' << MO.getIndex();
386     // FIXME: PIC relocation model
387     return;
388   case MachineOperand::MO_ConstantPoolIndex:
389     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
390       << '_' << MO.getIndex();
391     return;
392   case MachineOperand::MO_ExternalSymbol: {
393     // Computing the address of an external symbol, not calling it.
394     std::string Name(TAI->getGlobalPrefix());
395     Name += MO.getSymbolName();
396     
397     if (TM.getRelocationModel() != Reloc::Static) {
398       GVStubs[Name] = Name+"$non_lazy_ptr";
399       Name += "$non_lazy_ptr";
400     }
401     O << Name;
402     return;
403   }
404   case MachineOperand::MO_GlobalAddress: {
405     // Computing the address of a global symbol, not calling it.
406     GlobalValue *GV = MO.getGlobal();
407     std::string Name;
408
409     // External or weakly linked global variables need non-lazily-resolved stubs
410     if (TM.getRelocationModel() != Reloc::Static &&
411         (GV->isDeclaration() || GV->isWeakForLinker())) {
412       if (!GV->hasHiddenVisibility()) {
413         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
414         GVStubs[Mang->getMangledName(GV)] = Name;
415       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
416                  GV->hasAvailableExternallyLinkage()) {
417         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
418         HiddenGVStubs[Mang->getMangledName(GV)] = Name;
419       } else {
420         Name = Mang->getMangledName(GV);
421       }
422     } else {
423       Name = Mang->getMangledName(GV);
424     }
425     O << Name;
426
427     printOffset(MO.getOffset());
428     return;
429   }
430
431   default:
432     O << "<unknown operand type: " << MO.getType() << ">";
433     return;
434   }
435 }
436
437 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
438 ///
439 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
440   std::string Name;
441   
442   if (TM.getRelocationModel() != Reloc::Static) {
443     Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
444   } else {
445     Name = Mang->getMangledName(GV);
446   }
447   O << Name;
448 }
449
450 /// PrintAsmOperand - Print out an operand for an inline asm expression.
451 ///
452 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
453                                     unsigned AsmVariant,
454                                     const char *ExtraCode) {
455   // Does this asm operand have a single letter operand modifier?
456   if (ExtraCode && ExtraCode[0]) {
457     if (ExtraCode[1] != 0) return true; // Unknown modifier.
458
459     switch (ExtraCode[0]) {
460     default: return true;  // Unknown modifier.
461     case 'c': // Don't print "$" before a global var name or constant.
462       // PPC never has a prefix.
463       printOperand(MI, OpNo);
464       return false;
465     case 'L': // Write second word of DImode reference.
466       // Verify that this operand has two consecutive registers.
467       if (!MI->getOperand(OpNo).isReg() ||
468           OpNo+1 == MI->getNumOperands() ||
469           !MI->getOperand(OpNo+1).isReg())
470         return true;
471       ++OpNo;   // Return the high-part.
472       break;
473     case 'I':
474       // Write 'i' if an integer constant, otherwise nothing.  Used to print
475       // addi vs add, etc.
476       if (MI->getOperand(OpNo).isImm())
477         O << "i";
478       return false;
479     }
480   }
481
482   printOperand(MI, OpNo);
483   return false;
484 }
485
486 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
487                                           unsigned AsmVariant,
488                                           const char *ExtraCode) {
489   if (ExtraCode && ExtraCode[0])
490     return true; // Unknown modifier.
491   if (MI->getOperand(OpNo).isReg())
492     printMemRegReg(MI, OpNo);
493   else
494     printMemRegImm(MI, OpNo);
495   return false;
496 }
497
498 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
499                                           const char *Modifier) {
500   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
501   unsigned Code = MI->getOperand(OpNo).getImm();
502   if (!strcmp(Modifier, "cc")) {
503     switch ((PPC::Predicate)Code) {
504     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
505     case PPC::PRED_LT: O << "lt"; return;
506     case PPC::PRED_LE: O << "le"; return;
507     case PPC::PRED_EQ: O << "eq"; return;
508     case PPC::PRED_GE: O << "ge"; return;
509     case PPC::PRED_GT: O << "gt"; return;
510     case PPC::PRED_NE: O << "ne"; return;
511     case PPC::PRED_UN: O << "un"; return;
512     case PPC::PRED_NU: O << "nu"; return;
513     }
514
515   } else {
516     assert(!strcmp(Modifier, "reg") &&
517            "Need to specify 'cc' or 'reg' as predicate op modifier!");
518     // Don't print the register for 'always'.
519     if (Code == PPC::PRED_ALWAYS) return;
520     printOperand(MI, OpNo+1);
521   }
522 }
523
524
525 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
526 /// the current output stream.
527 ///
528 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
529   ++EmittedInsts;
530
531   // Check for slwi/srwi mnemonics.
532   if (MI->getOpcode() == PPC::RLWINM) {
533     bool FoundMnemonic = false;
534     unsigned char SH = MI->getOperand(2).getImm();
535     unsigned char MB = MI->getOperand(3).getImm();
536     unsigned char ME = MI->getOperand(4).getImm();
537     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
538       O << "\tslwi "; FoundMnemonic = true;
539     }
540     if (SH <= 31 && MB == (32-SH) && ME == 31) {
541       O << "\tsrwi "; FoundMnemonic = true;
542       SH = 32-SH;
543     }
544     if (FoundMnemonic) {
545       printOperand(MI, 0);
546       O << ", ";
547       printOperand(MI, 1);
548       O << ", " << (unsigned int)SH << '\n';
549       return;
550     }
551   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
552     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
553       O << "\tmr ";
554       printOperand(MI, 0);
555       O << ", ";
556       printOperand(MI, 1);
557       O << '\n';
558       return;
559     }
560   } else if (MI->getOpcode() == PPC::RLDICR) {
561     unsigned char SH = MI->getOperand(2).getImm();
562     unsigned char ME = MI->getOperand(3).getImm();
563     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
564     if (63-SH == ME) {
565       O << "\tsldi ";
566       printOperand(MI, 0);
567       O << ", ";
568       printOperand(MI, 1);
569       O << ", " << (unsigned int)SH << '\n';
570       return;
571     }
572   }
573
574   printInstruction(MI);
575 }
576
577 /// runOnMachineFunction - This uses the printMachineInstruction()
578 /// method to print assembly for each instruction.
579 ///
580 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
581   this->MF = &MF;
582
583   SetupMachineFunction(MF);
584   O << "\n\n";
585
586   // Print out constants referenced by the function
587   EmitConstantPool(MF.getConstantPool());
588
589   // Print out labels for the function.
590   const Function *F = MF.getFunction();
591   SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
592
593   switch (F->getLinkage()) {
594   default: llvm_unreachable("Unknown linkage type!");
595   case Function::PrivateLinkage:
596   case Function::LinkerPrivateLinkage:
597   case Function::InternalLinkage:  // Symbols default to internal.
598     break;
599   case Function::ExternalLinkage:
600     O << "\t.global\t" << CurrentFnName << '\n'
601       << "\t.type\t" << CurrentFnName << ", @function\n";
602     break;
603   case Function::WeakAnyLinkage:
604   case Function::WeakODRLinkage:
605   case Function::LinkOnceAnyLinkage:
606   case Function::LinkOnceODRLinkage:
607     O << "\t.global\t" << CurrentFnName << '\n';
608     O << "\t.weak\t" << CurrentFnName << '\n';
609     break;
610   }
611
612   printVisibility(CurrentFnName, F->getVisibility());
613
614   EmitAlignment(MF.getAlignment(), F);
615   O << CurrentFnName << ":\n";
616
617   // Emit pre-function debug information.
618   DW->BeginFunction(&MF);
619
620   // Print out code for the function.
621   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
622        I != E; ++I) {
623     // Print a label for the basic block.
624     if (I != MF.begin()) {
625       printBasicBlockLabel(I, true, true);
626       O << '\n';
627     }
628     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
629          II != E; ++II) {
630       // Print the assembly for the instruction.
631       printMachineInstruction(II);
632     }
633   }
634
635   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
636
637   // Print out jump tables referenced by the function.
638   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
639
640   SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
641
642   // Emit post-function debug information.
643   DW->EndFunction(&MF);
644
645   // We didn't modify anything.
646   return false;
647 }
648
649 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
650   const TargetData *TD = TM.getTargetData();
651
652   if (!GVar->hasInitializer())
653     return;   // External global require no code
654
655   // Check to see if this is a special global used by LLVM, if so, emit it.
656   if (EmitSpecialLLVMGlobal(GVar))
657     return;
658
659   std::string name = Mang->getMangledName(GVar);
660
661   printVisibility(name, GVar->getVisibility());
662
663   Constant *C = GVar->getInitializer();
664   const Type *Type = C->getType();
665   unsigned Size = TD->getTypeAllocSize(Type);
666   unsigned Align = TD->getPreferredAlignmentLog(GVar);
667
668   SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang, TM));
669
670   if (C->isNullValue() && /* FIXME: Verify correct */
671       !GVar->hasSection() &&
672       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
673        GVar->isWeakForLinker())) {
674       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
675
676       if (GVar->hasExternalLinkage()) {
677         O << "\t.global " << name << '\n';
678         O << "\t.type " << name << ", @object\n";
679         O << name << ":\n";
680         O << "\t.zero " << Size << '\n';
681       } else if (GVar->hasLocalLinkage()) {
682         O << TAI->getLCOMMDirective() << name << ',' << Size;
683       } else {
684         O << ".comm " << name << ',' << Size;
685       }
686       if (VerboseAsm) {
687         O << "\t\t" << TAI->getCommentString() << " '";
688         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
689         O << "'";
690       }
691       O << '\n';
692       return;
693   }
694
695   switch (GVar->getLinkage()) {
696    case GlobalValue::LinkOnceAnyLinkage:
697    case GlobalValue::LinkOnceODRLinkage:
698    case GlobalValue::WeakAnyLinkage:
699    case GlobalValue::WeakODRLinkage:
700    case GlobalValue::CommonLinkage:
701     O << "\t.global " << name << '\n'
702       << "\t.type " << name << ", @object\n"
703       << "\t.weak " << name << '\n';
704     break;
705    case GlobalValue::AppendingLinkage:
706     // FIXME: appending linkage variables should go into a section of
707     // their name or something.  For now, just emit them as external.
708    case GlobalValue::ExternalLinkage:
709     // If external or appending, declare as a global symbol
710     O << "\t.global " << name << '\n'
711       << "\t.type " << name << ", @object\n";
712     // FALL THROUGH
713    case GlobalValue::InternalLinkage:
714    case GlobalValue::PrivateLinkage:
715    case GlobalValue::LinkerPrivateLinkage:
716     break;
717    default:
718     llvm_unreachable("Unknown linkage type!");
719   }
720
721   EmitAlignment(Align, GVar);
722   O << name << ":";
723   if (VerboseAsm) {
724     O << "\t\t\t\t" << TAI->getCommentString() << " '";
725     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
726     O << "'";
727   }
728   O << '\n';
729
730   EmitGlobalConstant(C);
731   O << '\n';
732 }
733
734
735 /// runOnMachineFunction - This uses the printMachineInstruction()
736 /// method to print assembly for each instruction.
737 ///
738 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
739   this->MF = &MF;
740
741   SetupMachineFunction(MF);
742   O << "\n\n";
743
744   // Print out constants referenced by the function
745   EmitConstantPool(MF.getConstantPool());
746
747   // Print out labels for the function.
748   const Function *F = MF.getFunction();
749   SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
750
751   switch (F->getLinkage()) {
752   default: llvm_unreachable("Unknown linkage type!");
753   case Function::PrivateLinkage:
754   case Function::LinkerPrivateLinkage:
755   case Function::InternalLinkage:  // Symbols default to internal.
756     break;
757   case Function::ExternalLinkage:
758     O << "\t.globl\t" << CurrentFnName << '\n';
759     break;
760   case Function::WeakAnyLinkage:
761   case Function::WeakODRLinkage:
762   case Function::LinkOnceAnyLinkage:
763   case Function::LinkOnceODRLinkage:
764     O << "\t.globl\t" << CurrentFnName << '\n';
765     O << "\t.weak_definition\t" << CurrentFnName << '\n';
766     break;
767   }
768
769   printVisibility(CurrentFnName, F->getVisibility());
770
771   EmitAlignment(MF.getAlignment(), F);
772   O << CurrentFnName << ":\n";
773
774   // Emit pre-function debug information.
775   DW->BeginFunction(&MF);
776
777   // If the function is empty, then we need to emit *something*. Otherwise, the
778   // function's label might be associated with something that it wasn't meant to
779   // be associated with. We emit a noop in this situation.
780   MachineFunction::iterator I = MF.begin();
781
782   if (++I == MF.end() && MF.front().empty())
783     O << "\tnop\n";
784
785   // Print out code for the function.
786   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
787        I != E; ++I) {
788     // Print a label for the basic block.
789     if (I != MF.begin()) {
790       printBasicBlockLabel(I, true, true, VerboseAsm);
791       O << '\n';
792     }
793     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
794          II != IE; ++II) {
795       // Print the assembly for the instruction.
796       printMachineInstruction(II);
797     }
798   }
799
800   // Print out jump tables referenced by the function.
801   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
802
803   // Emit post-function debug information.
804   DW->EndFunction(&MF);
805
806   // We didn't modify anything.
807   return false;
808 }
809
810
811 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
812   static const char *const CPUDirectives[] = {
813     "",
814     "ppc",
815     "ppc601",
816     "ppc602",
817     "ppc603",
818     "ppc7400",
819     "ppc750",
820     "ppc970",
821     "ppc64"
822   };
823
824   unsigned Directive = Subtarget.getDarwinDirective();
825   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
826     Directive = PPC::DIR_970;
827   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
828     Directive = PPC::DIR_7400;
829   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
830     Directive = PPC::DIR_64;
831   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
832   O << "\t.machine " << CPUDirectives[Directive] << '\n';
833
834   bool Result = AsmPrinter::doInitialization(M);
835   assert(MMI);
836
837   // Prime text sections so they are adjacent.  This reduces the likelihood a
838   // large data or debug section causes a branch to exceed 16M limit.
839   TargetLoweringObjectFileMachO &TLOFMacho = 
840     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
841   SwitchToSection(TLOFMacho.getTextCoalSection());
842   if (TM.getRelocationModel() == Reloc::PIC_) {
843     SwitchToSection(TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
844                                               MCSectionMachO::S_SYMBOL_STUBS |
845                                        MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
846                                               32, SectionKind::getText()));
847   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
848     SwitchToSection(TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
849                                               MCSectionMachO::S_SYMBOL_STUBS |
850                                        MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
851                                               16, SectionKind::getText()));
852   }
853   SwitchToSection(getObjFileLowering().getTextSection());
854
855   return Result;
856 }
857
858 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
859   const TargetData *TD = TM.getTargetData();
860
861   if (!GVar->hasInitializer())
862     return;   // External global require no code
863
864   // Check to see if this is a special global used by LLVM, if so, emit it.
865   if (EmitSpecialLLVMGlobal(GVar)) {
866     if (TM.getRelocationModel() == Reloc::Static) {
867       if (GVar->getName() == "llvm.global_ctors")
868         O << ".reference .constructors_used\n";
869       else if (GVar->getName() == "llvm.global_dtors")
870         O << ".reference .destructors_used\n";
871     }
872     return;
873   }
874
875   std::string name = Mang->getMangledName(GVar);
876   printVisibility(name, GVar->getVisibility());
877
878   Constant *C = GVar->getInitializer();
879   const Type *Type = C->getType();
880   unsigned Size = TD->getTypeAllocSize(Type);
881   unsigned Align = TD->getPreferredAlignmentLog(GVar);
882
883   const MCSection *TheSection =
884     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
885   SwitchToSection(TheSection);
886
887   /// FIXME: Drive this off the section!
888   if (C->isNullValue() && /* FIXME: Verify correct */
889       !GVar->hasSection() &&
890       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
891        GVar->isWeakForLinker()) &&
892       // Don't put things that should go in the cstring section into "comm".
893       !TheSection->getKind().isMergeableCString()) {
894     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
895
896     if (GVar->hasExternalLinkage()) {
897       O << "\t.globl " << name << '\n';
898       O << "\t.zerofill __DATA, __common, " << name << ", "
899         << Size << ", " << Align;
900     } else if (GVar->hasLocalLinkage()) {
901       O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
902     } else if (!GVar->hasCommonLinkage()) {
903       O << "\t.globl " << name << '\n'
904         << TAI->getWeakDefDirective() << name << '\n';
905       EmitAlignment(Align, GVar);
906       O << name << ":";
907       if (VerboseAsm) {
908         O << "\t\t\t\t" << TAI->getCommentString() << " ";
909         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
910       }
911       O << '\n';
912       EmitGlobalConstant(C);
913       return;
914     } else {
915       O << ".comm " << name << ',' << Size;
916       // Darwin 9 and above support aligned common data.
917       if (Subtarget.isDarwin9())
918         O << ',' << Align;
919     }
920     if (VerboseAsm) {
921       O << "\t\t" << TAI->getCommentString() << " '";
922       WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
923       O << "'";
924     }
925     O << '\n';
926     return;
927   }
928
929   switch (GVar->getLinkage()) {
930    case GlobalValue::LinkOnceAnyLinkage:
931    case GlobalValue::LinkOnceODRLinkage:
932    case GlobalValue::WeakAnyLinkage:
933    case GlobalValue::WeakODRLinkage:
934    case GlobalValue::CommonLinkage:
935     O << "\t.globl " << name << '\n'
936       << "\t.weak_definition " << name << '\n';
937     break;
938    case GlobalValue::AppendingLinkage:
939     // FIXME: appending linkage variables should go into a section of
940     // their name or something.  For now, just emit them as external.
941    case GlobalValue::ExternalLinkage:
942     // If external or appending, declare as a global symbol
943     O << "\t.globl " << name << '\n';
944     // FALL THROUGH
945    case GlobalValue::InternalLinkage:
946    case GlobalValue::PrivateLinkage:
947    case GlobalValue::LinkerPrivateLinkage:
948     break;
949    default:
950     llvm_unreachable("Unknown linkage type!");
951   }
952
953   EmitAlignment(Align, GVar);
954   O << name << ":";
955   if (VerboseAsm) {
956     O << "\t\t\t\t" << TAI->getCommentString() << " '";
957     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
958     O << "'";
959   }
960   O << '\n';
961
962   EmitGlobalConstant(C);
963   O << '\n';
964 }
965
966 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
967   const TargetData *TD = TM.getTargetData();
968
969   bool isPPC64 = TD->getPointerSizeInBits() == 64;
970
971   // Darwin/PPC always uses mach-o.
972   TargetLoweringObjectFileMachO &TLOFMacho = 
973     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
974
975   
976   const MCSection *LSPSection = 0;
977   if (!FnStubs.empty()) // .lazy_symbol_pointer
978     LSPSection = TLOFMacho.getLazySymbolPointerSection();
979     
980   
981   // Output stubs for dynamically-linked functions
982   if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
983     const MCSection *StubSection = 
984       TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
985                                 MCSectionMachO::S_SYMBOL_STUBS |
986                                 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
987                                 32, SectionKind::getText());
988      for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
989          I != E; ++I) {
990       SwitchToSection(StubSection);
991       EmitAlignment(4);
992       const FnStubInfo &Info = I->second;
993       O << Info.Stub << ":\n";
994       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
995       O << "\tmflr r0\n";
996       O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
997       O << Info.AnonSymbol << ":\n";
998       O << "\tmflr r11\n";
999       O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1000       O << ")\n";
1001       O << "\tmtlr r0\n";
1002       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1003       O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1004       O << "\tmtctr r12\n";
1005       O << "\tbctr\n";
1006       
1007       SwitchToSection(LSPSection);
1008       O << Info.LazyPtr << ":\n";
1009       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1010       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1011     }
1012   } else if (!FnStubs.empty()) {
1013     const MCSection *StubSection =
1014       TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1015                                 MCSectionMachO::S_SYMBOL_STUBS |
1016                                 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1017                                 16, SectionKind::getText());
1018     
1019     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1020          I != E; ++I) {
1021       SwitchToSection(StubSection);
1022       EmitAlignment(4);
1023       const FnStubInfo &Info = I->second;
1024       O << Info.Stub << ":\n";
1025       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1026       O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1027       O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(";
1028       O << Info.LazyPtr << ")(r11)\n";
1029       O << "\tmtctr r12\n";
1030       O << "\tbctr\n";
1031       SwitchToSection(LSPSection);
1032       O << Info.LazyPtr << ":\n";
1033       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1034       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1035     }
1036   }
1037
1038   O << '\n';
1039
1040   if (TAI->doesSupportExceptionHandling() && MMI) {
1041     // Add the (possibly multiple) personalities to the set of global values.
1042     // Only referenced functions get into the Personalities list.
1043     const std::vector<Function *> &Personalities = MMI->getPersonalities();
1044     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1045          E = Personalities.end(); I != E; ++I) {
1046       if (*I)
1047         GVStubs[Mang->getMangledName(*I)] =
1048           Mang->getMangledName(*I, "$non_lazy_ptr", true);
1049     }
1050   }
1051
1052   // Output macho stubs for external and common global variables.
1053   if (!GVStubs.empty()) {
1054     // Switch with ".non_lazy_symbol_pointer" directive.
1055     SwitchToSection(TLOFMacho.getNonLazySymbolPointerSection());
1056     EmitAlignment(isPPC64 ? 3 : 2);
1057     
1058     for (StringMap<std::string>::iterator I = GVStubs.begin(),
1059          E = GVStubs.end(); I != E; ++I) {
1060       O << I->second << ":\n";
1061       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1062       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1063     }
1064   }
1065
1066   if (!HiddenGVStubs.empty()) {
1067     SwitchToSection(getObjFileLowering().getDataSection());
1068     EmitAlignment(isPPC64 ? 3 : 2);
1069     for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1070          E = HiddenGVStubs.end(); I != E; ++I) {
1071       O << I->second << ":\n";
1072       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1073     }
1074   }
1075
1076   // Funny Darwin hack: This flag tells the linker that no global symbols
1077   // contain code that falls through to other global symbols (e.g. the obvious
1078   // implementation of multiple entry points).  If this doesn't occur, the
1079   // linker can safely perform dead code stripping.  Since LLVM never generates
1080   // code that does this, it is always safe to set.
1081   O << "\t.subsections_via_symbols\n";
1082
1083   return AsmPrinter::doFinalization(M);
1084 }
1085
1086
1087
1088 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1089 /// for a MachineFunction to the given output stream, in a format that the
1090 /// Darwin assembler can deal with.
1091 ///
1092 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1093                                            TargetMachine &tm,
1094                                            const TargetAsmInfo *tai,
1095                                            bool verbose) {
1096   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1097
1098   if (Subtarget->isDarwin())
1099     return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1100   return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1101 }
1102
1103 // Force static initialization.
1104 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1105   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1106   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1107 }