Rename MDNode.h header. It defines MDnode and other metadata classes.
[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/Metadata.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/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegistry.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     bool 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   if (printInstruction(MI))
575     return; // Printer was automatically generated
576
577   llvm_unreachable("Unhandled instruction in asm writer!");
578 }
579
580 /// runOnMachineFunction - This uses the printMachineInstruction()
581 /// method to print assembly for each instruction.
582 ///
583 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
584   this->MF = &MF;
585
586   SetupMachineFunction(MF);
587   O << "\n\n";
588
589   // Print out constants referenced by the function
590   EmitConstantPool(MF.getConstantPool());
591
592   // Print out labels for the function.
593   const Function *F = MF.getFunction();
594   SwitchToSection(getObjFileLowering().SectionForGlobal(F, TM));
595
596   switch (F->getLinkage()) {
597   default: llvm_unreachable("Unknown linkage type!");
598   case Function::PrivateLinkage:
599   case Function::LinkerPrivateLinkage:
600   case Function::InternalLinkage:  // Symbols default to internal.
601     break;
602   case Function::ExternalLinkage:
603     O << "\t.global\t" << CurrentFnName << '\n'
604       << "\t.type\t" << CurrentFnName << ", @function\n";
605     break;
606   case Function::WeakAnyLinkage:
607   case Function::WeakODRLinkage:
608   case Function::LinkOnceAnyLinkage:
609   case Function::LinkOnceODRLinkage:
610     O << "\t.global\t" << CurrentFnName << '\n';
611     O << "\t.weak\t" << CurrentFnName << '\n';
612     break;
613   }
614
615   printVisibility(CurrentFnName, F->getVisibility());
616
617   EmitAlignment(MF.getAlignment(), F);
618   O << CurrentFnName << ":\n";
619
620   // Emit pre-function debug information.
621   DW->BeginFunction(&MF);
622
623   // Print out code for the function.
624   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
625        I != E; ++I) {
626     // Print a label for the basic block.
627     if (I != MF.begin()) {
628       printBasicBlockLabel(I, true, true);
629       O << '\n';
630     }
631     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
632          II != E; ++II) {
633       // Print the assembly for the instruction.
634       printMachineInstruction(II);
635     }
636   }
637
638   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
639
640   // Print out jump tables referenced by the function.
641   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
642
643   SwitchToSection(getObjFileLowering().SectionForGlobal(F, TM));
644
645   // Emit post-function debug information.
646   DW->EndFunction(&MF);
647
648   O.flush();
649
650   // We didn't modify anything.
651   return false;
652 }
653
654 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
655 /// Don't print things like \\n or \\0.
656 static void PrintUnmangledNameSafely(const Value *V, 
657                                      formatted_raw_ostream &OS) {
658   for (StringRef::iterator it = V->getName().begin(), 
659          ie = V->getName().end(); it != ie; ++it)
660     if (isprint(*it))
661       OS << *it;
662 }
663
664 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
665   const TargetData *TD = TM.getTargetData();
666
667   if (!GVar->hasInitializer())
668     return;   // External global require no code
669
670   // Check to see if this is a special global used by LLVM, if so, emit it.
671   if (EmitSpecialLLVMGlobal(GVar))
672     return;
673
674   std::string name = Mang->getMangledName(GVar);
675
676   printVisibility(name, GVar->getVisibility());
677
678   Constant *C = GVar->getInitializer();
679   if (isa<MDNode>(C) || isa<MDString>(C))
680     return;
681   const Type *Type = C->getType();
682   unsigned Size = TD->getTypeAllocSize(Type);
683   unsigned Align = TD->getPreferredAlignmentLog(GVar);
684
685   SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, TM));
686
687   if (C->isNullValue() && /* FIXME: Verify correct */
688       !GVar->hasSection() &&
689       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
690        GVar->isWeakForLinker())) {
691       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
692
693       if (GVar->hasExternalLinkage()) {
694         O << "\t.global " << name << '\n';
695         O << "\t.type " << name << ", @object\n";
696         O << name << ":\n";
697         O << "\t.zero " << Size << '\n';
698       } else if (GVar->hasLocalLinkage()) {
699         O << TAI->getLCOMMDirective() << name << ',' << Size;
700       } else {
701         O << ".comm " << name << ',' << Size;
702       }
703       if (VerboseAsm) {
704         O << "\t\t" << TAI->getCommentString() << " '";
705         PrintUnmangledNameSafely(GVar, O);
706         O << "'";
707       }
708       O << '\n';
709       return;
710   }
711
712   switch (GVar->getLinkage()) {
713    case GlobalValue::LinkOnceAnyLinkage:
714    case GlobalValue::LinkOnceODRLinkage:
715    case GlobalValue::WeakAnyLinkage:
716    case GlobalValue::WeakODRLinkage:
717    case GlobalValue::CommonLinkage:
718     O << "\t.global " << name << '\n'
719       << "\t.type " << name << ", @object\n"
720       << "\t.weak " << name << '\n';
721     break;
722    case GlobalValue::AppendingLinkage:
723     // FIXME: appending linkage variables should go into a section of
724     // their name or something.  For now, just emit them as external.
725    case GlobalValue::ExternalLinkage:
726     // If external or appending, declare as a global symbol
727     O << "\t.global " << name << '\n'
728       << "\t.type " << name << ", @object\n";
729     // FALL THROUGH
730    case GlobalValue::InternalLinkage:
731    case GlobalValue::PrivateLinkage:
732    case GlobalValue::LinkerPrivateLinkage:
733     break;
734    default:
735     llvm_unreachable("Unknown linkage type!");
736   }
737
738   EmitAlignment(Align, GVar);
739   O << name << ":";
740   if (VerboseAsm) {
741     O << "\t\t\t\t" << TAI->getCommentString() << " '";
742     PrintUnmangledNameSafely(GVar, O);
743     O << "'";
744   }
745   O << '\n';
746
747   EmitGlobalConstant(C);
748   O << '\n';
749 }
750
751
752 /// runOnMachineFunction - This uses the printMachineInstruction()
753 /// method to print assembly for each instruction.
754 ///
755 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
756   this->MF = &MF;
757
758   SetupMachineFunction(MF);
759   O << "\n\n";
760
761   // Print out constants referenced by the function
762   EmitConstantPool(MF.getConstantPool());
763
764   // Print out labels for the function.
765   const Function *F = MF.getFunction();
766   SwitchToSection(getObjFileLowering().SectionForGlobal(F, TM));
767
768   switch (F->getLinkage()) {
769   default: llvm_unreachable("Unknown linkage type!");
770   case Function::PrivateLinkage:
771   case Function::LinkerPrivateLinkage:
772   case Function::InternalLinkage:  // Symbols default to internal.
773     break;
774   case Function::ExternalLinkage:
775     O << "\t.globl\t" << CurrentFnName << '\n';
776     break;
777   case Function::WeakAnyLinkage:
778   case Function::WeakODRLinkage:
779   case Function::LinkOnceAnyLinkage:
780   case Function::LinkOnceODRLinkage:
781     O << "\t.globl\t" << CurrentFnName << '\n';
782     O << "\t.weak_definition\t" << CurrentFnName << '\n';
783     break;
784   }
785
786   printVisibility(CurrentFnName, F->getVisibility());
787
788   EmitAlignment(MF.getAlignment(), F);
789   O << CurrentFnName << ":\n";
790
791   // Emit pre-function debug information.
792   DW->BeginFunction(&MF);
793
794   // If the function is empty, then we need to emit *something*. Otherwise, the
795   // function's label might be associated with something that it wasn't meant to
796   // be associated with. We emit a noop in this situation.
797   MachineFunction::iterator I = MF.begin();
798
799   if (++I == MF.end() && MF.front().empty())
800     O << "\tnop\n";
801
802   // Print out code for the function.
803   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
804        I != E; ++I) {
805     // Print a label for the basic block.
806     if (I != MF.begin()) {
807       printBasicBlockLabel(I, true, true, VerboseAsm);
808       O << '\n';
809     }
810     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
811          II != IE; ++II) {
812       // Print the assembly for the instruction.
813       printMachineInstruction(II);
814     }
815   }
816
817   // Print out jump tables referenced by the function.
818   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
819
820   // Emit post-function debug information.
821   DW->EndFunction(&MF);
822
823   // We didn't modify anything.
824   return false;
825 }
826
827
828 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
829   static const char *const CPUDirectives[] = {
830     "",
831     "ppc",
832     "ppc601",
833     "ppc602",
834     "ppc603",
835     "ppc7400",
836     "ppc750",
837     "ppc970",
838     "ppc64"
839   };
840
841   unsigned Directive = Subtarget.getDarwinDirective();
842   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
843     Directive = PPC::DIR_970;
844   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
845     Directive = PPC::DIR_7400;
846   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
847     Directive = PPC::DIR_64;
848   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
849   O << "\t.machine " << CPUDirectives[Directive] << '\n';
850
851   bool Result = AsmPrinter::doInitialization(M);
852   assert(MMI);
853
854   // Prime text sections so they are adjacent.  This reduces the likelihood a
855   // large data or debug section causes a branch to exceed 16M limit.
856   SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
857                       "pure_instructions");
858   if (TM.getRelocationModel() == Reloc::PIC_) {
859     SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
860                           "pure_instructions,32");
861   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
862     SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
863                         "pure_instructions,16");
864   }
865   SwitchToSection(getObjFileLowering().getTextSection());
866
867   return Result;
868 }
869
870 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
871   const TargetData *TD = TM.getTargetData();
872
873   if (!GVar->hasInitializer())
874     return;   // External global require no code
875
876   // Check to see if this is a special global used by LLVM, if so, emit it.
877   if (EmitSpecialLLVMGlobal(GVar)) {
878     if (TM.getRelocationModel() == Reloc::Static) {
879       if (GVar->getName() == "llvm.global_ctors")
880         O << ".reference .constructors_used\n";
881       else if (GVar->getName() == "llvm.global_dtors")
882         O << ".reference .destructors_used\n";
883     }
884     return;
885   }
886
887   std::string name = Mang->getMangledName(GVar);
888   printVisibility(name, GVar->getVisibility());
889
890   Constant *C = GVar->getInitializer();
891   const Type *Type = C->getType();
892   unsigned Size = TD->getTypeAllocSize(Type);
893   unsigned Align = TD->getPreferredAlignmentLog(GVar);
894
895   const Section *TheSection = getObjFileLowering().SectionForGlobal(GVar, TM);
896   SwitchToSection(TheSection);
897
898   if (C->isNullValue() && /* FIXME: Verify correct */
899       !GVar->hasSection() &&
900       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
901        GVar->isWeakForLinker()) &&
902       // Don't put things that should go in the cstring section into "comm".
903       !TheSection->getKind().isMergeableCString()) {
904     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
905
906     if (GVar->hasExternalLinkage()) {
907       O << "\t.globl " << name << '\n';
908       O << "\t.zerofill __DATA, __common, " << name << ", "
909         << Size << ", " << Align;
910     } else if (GVar->hasLocalLinkage()) {
911       O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
912     } else if (!GVar->hasCommonLinkage()) {
913       O << "\t.globl " << name << '\n'
914         << TAI->getWeakDefDirective() << name << '\n';
915       EmitAlignment(Align, GVar);
916       O << name << ":";
917       if (VerboseAsm) {
918         O << "\t\t\t\t" << TAI->getCommentString() << " ";
919         PrintUnmangledNameSafely(GVar, O);
920       }
921       O << '\n';
922       EmitGlobalConstant(C);
923       return;
924     } else {
925       O << ".comm " << name << ',' << Size;
926       // Darwin 9 and above support aligned common data.
927       if (Subtarget.isDarwin9())
928         O << ',' << Align;
929     }
930     if (VerboseAsm) {
931       O << "\t\t" << TAI->getCommentString() << " '";
932       PrintUnmangledNameSafely(GVar, O);
933       O << "'";
934     }
935     O << '\n';
936     return;
937   }
938
939   switch (GVar->getLinkage()) {
940    case GlobalValue::LinkOnceAnyLinkage:
941    case GlobalValue::LinkOnceODRLinkage:
942    case GlobalValue::WeakAnyLinkage:
943    case GlobalValue::WeakODRLinkage:
944    case GlobalValue::CommonLinkage:
945     O << "\t.globl " << name << '\n'
946       << "\t.weak_definition " << name << '\n';
947     break;
948    case GlobalValue::AppendingLinkage:
949     // FIXME: appending linkage variables should go into a section of
950     // their name or something.  For now, just emit them as external.
951    case GlobalValue::ExternalLinkage:
952     // If external or appending, declare as a global symbol
953     O << "\t.globl " << name << '\n';
954     // FALL THROUGH
955    case GlobalValue::InternalLinkage:
956    case GlobalValue::PrivateLinkage:
957    case GlobalValue::LinkerPrivateLinkage:
958     break;
959    default:
960     llvm_unreachable("Unknown linkage type!");
961   }
962
963   EmitAlignment(Align, GVar);
964   O << name << ":";
965   if (VerboseAsm) {
966     O << "\t\t\t\t" << TAI->getCommentString() << " '";
967     PrintUnmangledNameSafely(GVar, O);
968     O << "'";
969   }
970   O << '\n';
971
972   EmitGlobalConstant(C);
973   O << '\n';
974 }
975
976 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
977   const TargetData *TD = TM.getTargetData();
978
979   bool isPPC64 = TD->getPointerSizeInBits() == 64;
980
981   // Output stubs for dynamically-linked functions
982   if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
983     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
984          I != E; ++I) {
985       SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
986                           "pure_instructions,32");
987       EmitAlignment(4);
988       const FnStubInfo &Info = I->second;
989       O << Info.Stub << ":\n";
990       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
991       O << "\tmflr r0\n";
992       O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
993       O << Info.AnonSymbol << ":\n";
994       O << "\tmflr r11\n";
995       O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
996       O << ")\n";
997       O << "\tmtlr r0\n";
998       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
999       O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1000       O << "\tmtctr r12\n";
1001       O << "\tbctr\n";
1002       
1003       SwitchToDataSection(".lazy_symbol_pointer");
1004       O << Info.LazyPtr << ":\n";
1005       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1006       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1007     }
1008   } else if (!FnStubs.empty()) {
1009     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1010          I != E; ++I) {
1011       SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1012                           "pure_instructions,16");
1013       EmitAlignment(4);
1014       const FnStubInfo &Info = I->second;
1015       O << Info.Stub << ":\n";
1016       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1017       O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1018       O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(";
1019       O << Info.LazyPtr << ")(r11)\n";
1020       O << "\tmtctr r12\n";
1021       O << "\tbctr\n";
1022       SwitchToDataSection(".lazy_symbol_pointer");
1023       O << Info.LazyPtr << ":\n";
1024       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1025       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1026     }
1027   }
1028
1029   O << '\n';
1030
1031   if (TAI->doesSupportExceptionHandling() && MMI) {
1032     // Add the (possibly multiple) personalities to the set of global values.
1033     // Only referenced functions get into the Personalities list.
1034     const std::vector<Function *> &Personalities = MMI->getPersonalities();
1035     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1036          E = Personalities.end(); I != E; ++I) {
1037       if (*I)
1038         GVStubs[Mang->getMangledName(*I)] =
1039           Mang->getMangledName(*I, "$non_lazy_ptr", true);
1040     }
1041   }
1042
1043   // Output stubs for external and common global variables.
1044   if (!GVStubs.empty()) {
1045     SwitchToDataSection(".non_lazy_symbol_pointer");
1046     for (StringMap<std::string>::iterator I = GVStubs.begin(),
1047          E = GVStubs.end(); I != E; ++I) {
1048       O << I->second << ":\n";
1049       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1050       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1051     }
1052   }
1053
1054   if (!HiddenGVStubs.empty()) {
1055     SwitchToSection(getObjFileLowering().getDataSection());
1056     EmitAlignment(isPPC64 ? 3 : 2);
1057     for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1058          E = HiddenGVStubs.end(); I != E; ++I) {
1059       O << I->second << ":\n";
1060       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1061     }
1062   }
1063
1064   // Funny Darwin hack: This flag tells the linker that no global symbols
1065   // contain code that falls through to other global symbols (e.g. the obvious
1066   // implementation of multiple entry points).  If this doesn't occur, the
1067   // linker can safely perform dead code stripping.  Since LLVM never generates
1068   // code that does this, it is always safe to set.
1069   O << "\t.subsections_via_symbols\n";
1070
1071   return AsmPrinter::doFinalization(M);
1072 }
1073
1074
1075
1076 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1077 /// for a MachineFunction to the given output stream, in a format that the
1078 /// Darwin assembler can deal with.
1079 ///
1080 static FunctionPass *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1081                                             TargetMachine &tm,
1082                                             bool verbose) {
1083   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1084
1085   if (Subtarget->isDarwin())
1086     return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1087   return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1088 }
1089
1090 // Force static initialization.
1091 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1092   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1093
1094   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1095 }