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