eliminate the PPC backend's implementation of EmitExternalGlobal
[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 VISIBILITY_HIDDEN 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 VISIBILITY_HIDDEN 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 VISIBILITY_HIDDEN 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 doInitialization(Module &M);
385     bool doFinalization(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->getDebugLoc());
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
600 /// runOnMachineFunction - This uses the printMachineInstruction()
601 /// method to print assembly for each instruction.
602 ///
603 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
604   this->MF = &MF;
605
606   SetupMachineFunction(MF);
607   O << "\n\n";
608
609   // Print out constants referenced by the function
610   EmitConstantPool(MF.getConstantPool());
611
612   // Print out labels for the function.
613   const Function *F = MF.getFunction();
614   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
615
616   switch (F->getLinkage()) {
617   default: llvm_unreachable("Unknown linkage type!");
618   case Function::PrivateLinkage:
619   case Function::InternalLinkage:  // Symbols default to internal.
620     break;
621   case Function::ExternalLinkage:
622     O << "\t.global\t" << CurrentFnName << '\n'
623       << "\t.type\t" << CurrentFnName << ", @function\n";
624     break;
625   case Function::LinkerPrivateLinkage:
626   case Function::WeakAnyLinkage:
627   case Function::WeakODRLinkage:
628   case Function::LinkOnceAnyLinkage:
629   case Function::LinkOnceODRLinkage:
630     O << "\t.global\t" << CurrentFnName << '\n';
631     O << "\t.weak\t" << CurrentFnName << '\n';
632     break;
633   }
634
635   printVisibility(CurrentFnName, F->getVisibility());
636
637   EmitAlignment(MF.getAlignment(), F);
638
639   if (Subtarget.isPPC64()) {
640     // Emit an official procedure descriptor.
641     // FIXME 64-bit SVR4: Use MCSection here?
642     O << "\t.section\t\".opd\",\"aw\"\n";
643     O << "\t.align 3\n";
644     O << CurrentFnName << ":\n";
645     O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
646     O << "\t.previous\n";
647     O << ".L." << CurrentFnName << ":\n";
648   } else {
649     O << CurrentFnName << ":\n";
650   }
651
652   // Emit pre-function debug information.
653   DW->BeginFunction(&MF);
654
655   // Print out code for the function.
656   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
657        I != E; ++I) {
658     // Print a label for the basic block.
659     if (I != MF.begin()) {
660       EmitBasicBlockStart(I);
661       O << '\n';
662     }
663     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
664          II != E; ++II) {
665       // Print the assembly for the instruction.
666       printMachineInstruction(II);
667     }
668   }
669
670   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
671
672   // Print out jump tables referenced by the function.
673   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
674
675   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
676
677   // Emit post-function debug information.
678   DW->EndFunction(&MF);
679
680   // We didn't modify anything.
681   return false;
682 }
683
684 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
685   const TargetData *TD = TM.getTargetData();
686
687   if (!GVar->hasInitializer())
688     return;   // External global require no code
689
690   // Check to see if this is a special global used by LLVM, if so, emit it.
691   if (EmitSpecialLLVMGlobal(GVar))
692     return;
693
694   std::string name = Mang->getMangledName(GVar);
695
696   printVisibility(name, GVar->getVisibility());
697
698   Constant *C = GVar->getInitializer();
699   const Type *Type = C->getType();
700   unsigned Size = TD->getTypeAllocSize(Type);
701   unsigned Align = TD->getPreferredAlignmentLog(GVar);
702
703   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
704                                                                   TM));
705
706   if (C->isNullValue() && /* FIXME: Verify correct */
707       !GVar->hasSection() &&
708       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
709        GVar->isWeakForLinker())) {
710       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
711
712       if (GVar->hasExternalLinkage()) {
713         O << "\t.global " << name << '\n';
714         O << "\t.type " << name << ", @object\n";
715         O << name << ":\n";
716         O << "\t.zero " << Size << '\n';
717       } else if (GVar->hasLocalLinkage()) {
718         O << MAI->getLCOMMDirective() << name << ',' << Size;
719       } else {
720         O << ".comm " << name << ',' << Size;
721       }
722       if (VerboseAsm) {
723         O << "\t\t" << MAI->getCommentString() << " '";
724         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
725         O << "'";
726       }
727       O << '\n';
728       return;
729   }
730
731   switch (GVar->getLinkage()) {
732    case GlobalValue::LinkOnceAnyLinkage:
733    case GlobalValue::LinkOnceODRLinkage:
734    case GlobalValue::WeakAnyLinkage:
735    case GlobalValue::WeakODRLinkage:
736    case GlobalValue::CommonLinkage:
737    case GlobalValue::LinkerPrivateLinkage:
738     O << "\t.global " << name << '\n'
739       << "\t.type " << name << ", @object\n"
740       << "\t.weak " << name << '\n';
741     break;
742    case GlobalValue::AppendingLinkage:
743     // FIXME: appending linkage variables should go into a section of
744     // their name or something.  For now, just emit them as external.
745    case GlobalValue::ExternalLinkage:
746     // If external or appending, declare as a global symbol
747     O << "\t.global " << name << '\n'
748       << "\t.type " << name << ", @object\n";
749     // FALL THROUGH
750    case GlobalValue::InternalLinkage:
751    case GlobalValue::PrivateLinkage:
752     break;
753    default:
754     llvm_unreachable("Unknown linkage type!");
755   }
756
757   EmitAlignment(Align, GVar);
758   O << name << ":";
759   if (VerboseAsm) {
760     O << "\t\t\t\t" << MAI->getCommentString() << " '";
761     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
762     O << "'";
763   }
764   O << '\n';
765
766   EmitGlobalConstant(C);
767   O << '\n';
768 }
769
770 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
771   const TargetData *TD = TM.getTargetData();
772
773   bool isPPC64 = TD->getPointerSizeInBits() == 64;
774
775   if (isPPC64 && !TOC.empty()) {
776     // FIXME 64-bit SVR4: Use MCSection here?
777     O << "\t.section\t\".toc\",\"aw\"\n";
778
779     for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
780          I != E; ++I) {
781       O << I->second << ":\n";
782       O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
783     }
784   }
785
786   return AsmPrinter::doFinalization(M);
787 }
788
789 /// runOnMachineFunction - This uses the printMachineInstruction()
790 /// method to print assembly for each instruction.
791 ///
792 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
793   this->MF = &MF;
794
795   SetupMachineFunction(MF);
796   O << "\n\n";
797
798   // Print out constants referenced by the function
799   EmitConstantPool(MF.getConstantPool());
800
801   // Print out labels for the function.
802   const Function *F = MF.getFunction();
803   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
804
805   switch (F->getLinkage()) {
806   default: llvm_unreachable("Unknown linkage type!");
807   case Function::PrivateLinkage:
808   case Function::InternalLinkage:  // Symbols default to internal.
809     break;
810   case Function::ExternalLinkage:
811     O << "\t.globl\t" << CurrentFnName << '\n';
812     break;
813   case Function::WeakAnyLinkage:
814   case Function::WeakODRLinkage:
815   case Function::LinkOnceAnyLinkage:
816   case Function::LinkOnceODRLinkage:
817   case Function::LinkerPrivateLinkage:
818     O << "\t.globl\t" << CurrentFnName << '\n';
819     O << "\t.weak_definition\t" << CurrentFnName << '\n';
820     break;
821   }
822
823   printVisibility(CurrentFnName, F->getVisibility());
824
825   EmitAlignment(MF.getAlignment(), F);
826   O << CurrentFnName << ":\n";
827
828   // Emit pre-function debug information.
829   DW->BeginFunction(&MF);
830
831   // If the function is empty, then we need to emit *something*. Otherwise, the
832   // function's label might be associated with something that it wasn't meant to
833   // be associated with. We emit a noop in this situation.
834   MachineFunction::iterator I = MF.begin();
835
836   if (++I == MF.end() && MF.front().empty())
837     O << "\tnop\n";
838
839   // Print out code for the function.
840   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
841        I != E; ++I) {
842     // Print a label for the basic block.
843     if (I != MF.begin()) {
844       EmitBasicBlockStart(I);
845       O << '\n';
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 bool PPCDarwinAsmPrinter::doInitialization(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   bool Result = AsmPrinter::doInitialization(M);
889   assert(MMI);
890
891   // Prime text sections so they are adjacent.  This reduces the likelihood a
892   // large data or debug section causes a branch to exceed 16M limit.
893   TargetLoweringObjectFileMachO &TLOFMacho = 
894     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
895   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
896   if (TM.getRelocationModel() == Reloc::PIC_) {
897     OutStreamer.SwitchSection(
898             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
899                                       MCSectionMachO::S_SYMBOL_STUBS |
900                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
901                                       32, SectionKind::getText()));
902   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
903     OutStreamer.SwitchSection(
904             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
905                                       MCSectionMachO::S_SYMBOL_STUBS |
906                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
907                                       16, SectionKind::getText()));
908   }
909   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
910
911   return Result;
912 }
913
914 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
915   const TargetData *TD = TM.getTargetData();
916
917   if (!GVar->hasInitializer())
918     return;   // External global require no code
919
920   // Check to see if this is a special global used by LLVM, if so, emit it.
921   if (EmitSpecialLLVMGlobal(GVar)) {
922     if (TM.getRelocationModel() == Reloc::Static) {
923       if (GVar->getName() == "llvm.global_ctors")
924         O << ".reference .constructors_used\n";
925       else if (GVar->getName() == "llvm.global_dtors")
926         O << ".reference .destructors_used\n";
927     }
928     return;
929   }
930
931   std::string name = Mang->getMangledName(GVar);
932   printVisibility(name, GVar->getVisibility());
933
934   Constant *C = GVar->getInitializer();
935   const Type *Type = C->getType();
936   unsigned Size = TD->getTypeAllocSize(Type);
937   unsigned Align = TD->getPreferredAlignmentLog(GVar);
938
939   const MCSection *TheSection =
940     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
941   OutStreamer.SwitchSection(TheSection);
942
943   /// FIXME: Drive this off the section!
944   if (C->isNullValue() && /* FIXME: Verify correct */
945       !GVar->hasSection() &&
946       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
947        GVar->isWeakForLinker()) &&
948       // Don't put things that should go in the cstring section into "comm".
949       !TheSection->getKind().isMergeableCString()) {
950     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
951
952     if (GVar->hasExternalLinkage()) {
953       O << "\t.globl " << name << '\n';
954       O << "\t.zerofill __DATA, __common, " << name << ", "
955         << Size << ", " << Align;
956     } else if (GVar->hasLocalLinkage()) {
957       O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
958     } else if (!GVar->hasCommonLinkage()) {
959       O << "\t.globl " << name << '\n'
960         << MAI->getWeakDefDirective() << name << '\n';
961       EmitAlignment(Align, GVar);
962       O << name << ":";
963       if (VerboseAsm) {
964         O << "\t\t\t\t" << MAI->getCommentString() << " ";
965         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
966       }
967       O << '\n';
968       EmitGlobalConstant(C);
969       return;
970     } else {
971       O << ".comm " << name << ',' << Size;
972       // Darwin 9 and above support aligned common data.
973       if (Subtarget.isDarwin9())
974         O << ',' << Align;
975     }
976     if (VerboseAsm) {
977       O << "\t\t" << MAI->getCommentString() << " '";
978       WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
979       O << "'";
980     }
981     O << '\n';
982     return;
983   }
984
985   switch (GVar->getLinkage()) {
986    case GlobalValue::LinkOnceAnyLinkage:
987    case GlobalValue::LinkOnceODRLinkage:
988    case GlobalValue::WeakAnyLinkage:
989    case GlobalValue::WeakODRLinkage:
990    case GlobalValue::CommonLinkage:
991    case GlobalValue::LinkerPrivateLinkage:
992     O << "\t.globl " << name << '\n'
993       << "\t.weak_definition " << name << '\n';
994     break;
995    case GlobalValue::AppendingLinkage:
996     // FIXME: appending linkage variables should go into a section of
997     // their name or something.  For now, just emit them as external.
998    case GlobalValue::ExternalLinkage:
999     // If external or appending, declare as a global symbol
1000     O << "\t.globl " << name << '\n';
1001     // FALL THROUGH
1002    case GlobalValue::InternalLinkage:
1003    case GlobalValue::PrivateLinkage:
1004     break;
1005    default:
1006     llvm_unreachable("Unknown linkage type!");
1007   }
1008
1009   EmitAlignment(Align, GVar);
1010   O << name << ":";
1011   if (VerboseAsm) {
1012     O << "\t\t\t\t" << MAI->getCommentString() << " '";
1013     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1014     O << "'";
1015   }
1016   O << '\n';
1017
1018   EmitGlobalConstant(C);
1019   O << '\n';
1020 }
1021
1022 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1023   const TargetData *TD = TM.getTargetData();
1024
1025   bool isPPC64 = TD->getPointerSizeInBits() == 64;
1026
1027   // Darwin/PPC always uses mach-o.
1028   TargetLoweringObjectFileMachO &TLOFMacho = 
1029     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1030
1031   
1032   const MCSection *LSPSection = 0;
1033   if (!FnStubs.empty()) // .lazy_symbol_pointer
1034     LSPSection = TLOFMacho.getLazySymbolPointerSection();
1035     
1036   
1037   // Output stubs for dynamically-linked functions
1038   if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1039     const MCSection *StubSection = 
1040       TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1041                                 MCSectionMachO::S_SYMBOL_STUBS |
1042                                 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1043                                 32, SectionKind::getText());
1044      for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1045          I != E; ++I) {
1046       OutStreamer.SwitchSection(StubSection);
1047       EmitAlignment(4);
1048       const FnStubInfo &Info = I->second;
1049       O << Info.Stub << ":\n";
1050       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1051       O << "\tmflr r0\n";
1052       O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1053       O << Info.AnonSymbol << ":\n";
1054       O << "\tmflr r11\n";
1055       O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1056       O << ")\n";
1057       O << "\tmtlr r0\n";
1058       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1059       O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1060       O << "\tmtctr r12\n";
1061       O << "\tbctr\n";
1062       
1063       OutStreamer.SwitchSection(LSPSection);
1064       O << Info.LazyPtr << ":\n";
1065       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1066       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1067     }
1068   } else if (!FnStubs.empty()) {
1069     const MCSection *StubSection =
1070       TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1071                                 MCSectionMachO::S_SYMBOL_STUBS |
1072                                 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1073                                 16, SectionKind::getText());
1074     
1075     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1076          I != E; ++I) {
1077       OutStreamer.SwitchSection(StubSection);
1078       EmitAlignment(4);
1079       const FnStubInfo &Info = I->second;
1080       O << Info.Stub << ":\n";
1081       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1082       O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1083       O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(";
1084       O << Info.LazyPtr << ")(r11)\n";
1085       O << "\tmtctr r12\n";
1086       O << "\tbctr\n";
1087       OutStreamer.SwitchSection(LSPSection);
1088       O << Info.LazyPtr << ":\n";
1089       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1090       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1091     }
1092   }
1093
1094   O << '\n';
1095
1096   if (MAI->doesSupportExceptionHandling() && MMI) {
1097     // Add the (possibly multiple) personalities to the set of global values.
1098     // Only referenced functions get into the Personalities list.
1099     const std::vector<Function *> &Personalities = MMI->getPersonalities();
1100     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1101          E = Personalities.end(); I != E; ++I) {
1102       if (*I)
1103         GVStubs[Mang->getMangledName(*I)] =
1104           Mang->getMangledName(*I, "$non_lazy_ptr", true);
1105     }
1106   }
1107
1108   // Output macho stubs for external and common global variables.
1109   if (!GVStubs.empty()) {
1110     // Switch with ".non_lazy_symbol_pointer" directive.
1111     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1112     EmitAlignment(isPPC64 ? 3 : 2);
1113     
1114     for (StringMap<std::string>::iterator I = GVStubs.begin(),
1115          E = GVStubs.end(); I != E; ++I) {
1116       O << I->second << ":\n";
1117       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1118       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1119     }
1120   }
1121
1122   if (!HiddenGVStubs.empty()) {
1123     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1124     EmitAlignment(isPPC64 ? 3 : 2);
1125     for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1126          E = HiddenGVStubs.end(); I != E; ++I) {
1127       O << I->second << ":\n";
1128       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1129     }
1130   }
1131
1132   // Funny Darwin hack: This flag tells the linker that no global symbols
1133   // contain code that falls through to other global symbols (e.g. the obvious
1134   // implementation of multiple entry points).  If this doesn't occur, the
1135   // linker can safely perform dead code stripping.  Since LLVM never generates
1136   // code that does this, it is always safe to set.
1137   O << "\t.subsections_via_symbols\n";
1138
1139   return AsmPrinter::doFinalization(M);
1140 }
1141
1142
1143
1144 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1145 /// for a MachineFunction to the given output stream, in a format that the
1146 /// Darwin assembler can deal with.
1147 ///
1148 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1149                                            TargetMachine &tm,
1150                                            const MCAsmInfo *tai,
1151                                            bool verbose) {
1152   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1153
1154   if (Subtarget->isDarwin())
1155     return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1156   return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1157 }
1158
1159 // Force static initialization.
1160 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1161   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1162   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1163 }