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