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