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