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