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