bac735a17b6b6ac6a031525e84a4675d950df77a
[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     MachineModuleInfo *MMI;
326
327     DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
328                      const TargetAsmInfo *T)
329       : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
330     }
331
332     virtual const char *getPassName() const {
333       return "Darwin PPC Assembly Printer";
334     }
335     
336     bool runOnMachineFunction(MachineFunction &F);
337     bool doInitialization(Module &M);
338     bool doFinalization(Module &M);
339     
340     void getAnalysisUsage(AnalysisUsage &AU) const {
341       AU.setPreservesAll();
342       AU.addRequired<MachineModuleInfo>();
343       PPCAsmPrinter::getAnalysisUsage(AU);
344     }
345
346     /// getSectionForFunction - Return the section that we should emit the
347     /// specified function body into.
348     virtual std::string getSectionForFunction(const Function &F) const;
349   };
350 } // end of anonymous namespace
351
352 // Include the auto-generated portion of the assembly writer
353 #include "PPCGenAsmWriter.inc"
354
355 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
356   switch (MO.getType()) {
357   case MachineOperand::MO_Immediate:
358     cerr << "printOp() does not handle immediate values\n";
359     abort();
360     return;
361
362   case MachineOperand::MO_MachineBasicBlock:
363     printBasicBlockLabel(MO.getMachineBasicBlock());
364     return;
365   case MachineOperand::MO_JumpTableIndex:
366     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
367       << '_' << MO.getJumpTableIndex();
368     // FIXME: PIC relocation model
369     return;
370   case MachineOperand::MO_ConstantPoolIndex:
371     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
372       << '_' << MO.getConstantPoolIndex();
373     return;
374   case MachineOperand::MO_ExternalSymbol:
375     // Computing the address of an external symbol, not calling it.
376     if (TM.getRelocationModel() != Reloc::Static) {
377       std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
378       GVStubs.insert(Name);
379       O << "L" << Name << "$non_lazy_ptr";
380       return;
381     }
382     O << TAI->getGlobalPrefix() << MO.getSymbolName();
383     return;
384   case MachineOperand::MO_GlobalAddress: {
385     // Computing the address of a global symbol, not calling it.
386     GlobalValue *GV = MO.getGlobal();
387     std::string Name = Mang->getValueName(GV);
388
389     // External or weakly linked global variables need non-lazily-resolved stubs
390     if (TM.getRelocationModel() != Reloc::Static) {
391       if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
392             GV->hasLinkOnceLinkage()))) {
393         GVStubs.insert(Name);
394         O << "L" << Name << "$non_lazy_ptr";
395         return;
396       }
397     }
398     O << Name;
399     
400     if (MO.getOffset() > 0)
401       O << "+" << MO.getOffset();
402     else if (MO.getOffset() < 0)
403       O << MO.getOffset();
404     
405     if (GV->hasExternalWeakLinkage())
406       ExtWeakSymbols.insert(GV);
407     return;
408   }
409
410   default:
411     O << "<unknown operand type: " << MO.getType() << ">";
412     return;
413   }
414 }
415
416 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
417 ///
418 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
419   std::string Name = getGlobalLinkName(GV);
420   if (TM.getRelocationModel() != Reloc::Static) {
421     GVStubs.insert(Name);
422     O << "L" << Name << "$non_lazy_ptr";
423     return;
424   }
425   O << Name;
426 }
427
428 /// PrintAsmOperand - Print out an operand for an inline asm expression.
429 ///
430 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
431                                     unsigned AsmVariant, 
432                                     const char *ExtraCode) {
433   // Does this asm operand have a single letter operand modifier?
434   if (ExtraCode && ExtraCode[0]) {
435     if (ExtraCode[1] != 0) return true; // Unknown modifier.
436     
437     switch (ExtraCode[0]) {
438     default: return true;  // Unknown modifier.
439     case 'c': // Don't print "$" before a global var name or constant.
440       // PPC never has a prefix.
441       printOperand(MI, OpNo);
442       return false;
443     case 'L': // Write second word of DImode reference.  
444       // Verify that this operand has two consecutive registers.
445       if (!MI->getOperand(OpNo).isRegister() ||
446           OpNo+1 == MI->getNumOperands() ||
447           !MI->getOperand(OpNo+1).isRegister())
448         return true;
449       ++OpNo;   // Return the high-part.
450       break;
451     case 'I':
452       // Write 'i' if an integer constant, otherwise nothing.  Used to print
453       // addi vs add, etc.
454       if (MI->getOperand(OpNo).isImmediate())
455         O << "i";
456       return false;
457     }
458   }
459   
460   printOperand(MI, OpNo);
461   return false;
462 }
463
464 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
465                                           unsigned AsmVariant, 
466                                           const char *ExtraCode) {
467   if (ExtraCode && ExtraCode[0])
468     return true; // Unknown modifier.
469   if (MI->getOperand(OpNo).isRegister())
470     printMemRegReg(MI, OpNo);
471   else
472     printMemRegImm(MI, OpNo);
473   return false;
474 }
475
476 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
477                                           const char *Modifier) {
478   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
479   unsigned Code = MI->getOperand(OpNo).getImm();
480   if (!strcmp(Modifier, "cc")) {
481     switch ((PPC::Predicate)Code) {
482     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
483     case PPC::PRED_LT: O << "lt"; return;
484     case PPC::PRED_LE: O << "le"; return;
485     case PPC::PRED_EQ: O << "eq"; return;
486     case PPC::PRED_GE: O << "ge"; return;
487     case PPC::PRED_GT: O << "gt"; return;
488     case PPC::PRED_NE: O << "ne"; return;
489     case PPC::PRED_UN: O << "un"; return;
490     case PPC::PRED_NU: O << "nu"; return;
491     }
492       
493   } else {
494     assert(!strcmp(Modifier, "reg") &&
495            "Need to specify 'cc' or 'reg' as predicate op modifier!");
496     // Don't print the register for 'always'.
497     if (Code == PPC::PRED_ALWAYS) return;
498     printOperand(MI, OpNo+1);
499   }
500 }
501
502
503 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
504 /// the current output stream.
505 ///
506 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
507   ++EmittedInsts;
508
509   // Check for slwi/srwi mnemonics.
510   if (MI->getOpcode() == PPC::RLWINM) {
511     bool FoundMnemonic = false;
512     unsigned char SH = MI->getOperand(2).getImmedValue();
513     unsigned char MB = MI->getOperand(3).getImmedValue();
514     unsigned char ME = MI->getOperand(4).getImmedValue();
515     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
516       O << "slwi "; FoundMnemonic = true;
517     }
518     if (SH <= 31 && MB == (32-SH) && ME == 31) {
519       O << "srwi "; FoundMnemonic = true;
520       SH = 32-SH;
521     }
522     if (FoundMnemonic) {
523       printOperand(MI, 0);
524       O << ", ";
525       printOperand(MI, 1);
526       O << ", " << (unsigned int)SH << "\n";
527       return;
528     }
529   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
530     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
531       O << "mr ";
532       printOperand(MI, 0);
533       O << ", ";
534       printOperand(MI, 1);
535       O << "\n";
536       return;
537     }
538   } else if (MI->getOpcode() == PPC::RLDICR) {
539     unsigned char SH = MI->getOperand(2).getImmedValue();
540     unsigned char ME = MI->getOperand(3).getImmedValue();
541     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
542     if (63-SH == ME) {
543       O << "sldi ";
544       printOperand(MI, 0);
545       O << ", ";
546       printOperand(MI, 1);
547       O << ", " << (unsigned int)SH << "\n";
548       return;
549     }
550   }
551
552   if (printInstruction(MI))
553     return; // Printer was automatically generated
554
555   assert(0 && "Unhandled instruction in asm writer!");
556   abort();
557   return;
558 }
559
560 /// runOnMachineFunction - This uses the printMachineInstruction()
561 /// method to print assembly for each instruction.
562 ///
563 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
564   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
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   SwitchToTextSection(getSectionForFunction(*F).c_str(), 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   if (F->hasHiddenVisibility())
592     if (const char *Directive = TAI->getHiddenDirective())
593       O << Directive << CurrentFnName << "\n";
594   
595   EmitAlignment(2, F);
596   O << CurrentFnName << ":\n";
597
598   // Emit pre-function debug information.
599   DW.BeginFunction(&MF);
600
601   // Print out code for the function.
602   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
603        I != E; ++I) {
604     // Print a label for the basic block.
605     if (I != MF.begin()) {
606       printBasicBlockLabel(I, true);
607       O << '\n';
608     }
609     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
610          II != E; ++II) {
611       // Print the assembly for the instruction.
612       O << "\t";
613       printMachineInstruction(II);
614     }
615   }
616
617   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
618
619   // Print out jump tables referenced by the function.
620   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
621   
622   // Emit post-function debug information.
623   DW.EndFunction();
624   
625   // We didn't modify anything.
626   return false;
627 }
628
629 bool LinuxAsmPrinter::doInitialization(Module &M) {
630   bool Result = AsmPrinter::doInitialization(M);
631   
632   // GNU as handles section names wrapped in quotes
633   Mang->setUseQuotes(true);
634
635   SwitchToTextSection(TAI->getTextSection());
636   
637   // Emit initial debug information.
638   DW.BeginModule(&M);
639   return Result;
640 }
641
642 bool LinuxAsmPrinter::doFinalization(Module &M) {
643   const TargetData *TD = TM.getTargetData();
644
645   // Print out module-level global variables here.
646   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
647        I != E; ++I) {
648     if (!I->hasInitializer()) continue;   // 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(I))
652       continue;
653
654     std::string name = Mang->getValueName(I);
655
656     if (I->hasHiddenVisibility())
657       if (const char *Directive = TAI->getHiddenDirective())
658         O << Directive << name << "\n";
659     
660     Constant *C = I->getInitializer();
661     unsigned Size = TD->getABITypeSize(C->getType());
662     unsigned Align = TD->getPreferredAlignmentLog(I);
663
664     if (C->isNullValue() && /* FIXME: Verify correct */
665         !I->hasSection() &&
666         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
667          I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
668       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
669       if (I->hasExternalLinkage()) {
670         O << "\t.global " << name << '\n';
671         O << "\t.type " << name << ", @object\n";
672         if (TAI->getBSSSection())
673           SwitchToDataSection(TAI->getBSSSection(), I);
674         O << name << ":\n";
675         O << "\t.zero " << Size << "\n";
676       } else if (I->hasInternalLinkage()) {
677         SwitchToDataSection("\t.data", I);
678         O << TAI->getLCOMMDirective() << name << "," << Size;
679       } else {
680         SwitchToDataSection("\t.data", I);
681         O << ".comm " << name << "," << Size;
682       }
683       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
684     } else {
685       switch (I->getLinkage()) {
686       case GlobalValue::LinkOnceLinkage:
687       case GlobalValue::WeakLinkage:
688         O << "\t.global " << name << '\n'
689           << "\t.type " << name << ", @object\n"
690           << "\t.weak " << name << '\n';
691         SwitchToDataSection("\t.data", I);
692         break;
693       case GlobalValue::AppendingLinkage:
694         // FIXME: appending linkage variables should go into a section of
695         // their name or something.  For now, just emit them as external.
696       case GlobalValue::ExternalLinkage:
697         // If external or appending, declare as a global symbol
698         O << "\t.global " << name << "\n"
699           << "\t.type " << name << ", @object\n";
700         // FALL THROUGH
701       case GlobalValue::InternalLinkage:
702         if (I->isConstant()) {
703           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
704           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
705             SwitchToDataSection(TAI->getCStringSection(), I);
706             break;
707           }
708         }
709
710         // FIXME: special handling for ".ctors" & ".dtors" sections
711         if (I->hasSection() &&
712             (I->getSection() == ".ctors" ||
713              I->getSection() == ".dtors")) {
714           std::string SectionName = ".section " + I->getSection()
715                                                 + ",\"aw\",@progbits";
716           SwitchToDataSection(SectionName.c_str());
717         } else {
718           if (I->isConstant() && TAI->getReadOnlySection())
719             SwitchToDataSection(TAI->getReadOnlySection(), I);
720           else
721             SwitchToDataSection(TAI->getDataSection(), I);
722         }
723         break;
724       default:
725         cerr << "Unknown linkage type!";
726         abort();
727       }
728
729       EmitAlignment(Align, I);
730       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
731         << I->getName() << "'\n";
732
733       // If the initializer is a extern weak symbol, remember to emit the weak
734       // reference!
735       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
736         if (GV->hasExternalWeakLinkage())
737           ExtWeakSymbols.insert(GV);
738
739       EmitGlobalConstant(C);
740       O << '\n';
741     }
742   }
743
744   // TODO
745
746   // Emit initial debug information.
747   DW.EndModule();
748
749   return AsmPrinter::doFinalization(M);
750 }
751
752 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
753   switch (F.getLinkage()) {
754   default: assert(0 && "Unknown linkage type!");
755   case Function::ExternalLinkage:
756   case Function::InternalLinkage: return TAI->getTextSection();
757   case Function::WeakLinkage:
758   case Function::LinkOnceLinkage:
759     return ".text";
760   }
761 }
762
763 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
764   switch (F.getLinkage()) {
765   default: assert(0 && "Unknown linkage type!");
766   case Function::ExternalLinkage:
767   case Function::InternalLinkage: return TAI->getTextSection();
768   case Function::WeakLinkage:
769   case Function::LinkOnceLinkage:
770     return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
771   }
772 }
773
774 /// runOnMachineFunction - This uses the printMachineInstruction()
775 /// method to print assembly for each instruction.
776 ///
777 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
778   // We need this for Personality functions.
779   MMI = &getAnalysis<MachineModuleInfo>();
780   DW.SetModuleInfo(MMI);
781
782   SetupMachineFunction(MF);
783   O << "\n\n";
784
785   // Print out constants referenced by the function
786   EmitConstantPool(MF.getConstantPool());
787
788   // Print out labels for the function.
789   const Function *F = MF.getFunction();
790   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
791   
792   switch (F->getLinkage()) {
793   default: assert(0 && "Unknown linkage type!");
794   case Function::InternalLinkage:  // Symbols default to internal.
795     break;
796   case Function::ExternalLinkage:
797     O << "\t.globl\t" << CurrentFnName << "\n";
798     break;
799   case Function::WeakLinkage:
800   case Function::LinkOnceLinkage:
801     O << "\t.globl\t" << CurrentFnName << "\n";
802     O << "\t.weak_definition\t" << CurrentFnName << "\n";
803     break;
804   }
805   
806   if (F->hasHiddenVisibility())
807     if (const char *Directive = TAI->getHiddenDirective())
808       O << Directive << CurrentFnName << "\n";
809   
810   EmitAlignment(4, F);
811   O << CurrentFnName << ":\n";
812
813   // Emit pre-function debug information.
814   DW.BeginFunction(&MF);
815
816   // Print out code for the function.
817   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
818        I != E; ++I) {
819     // Print a label for the basic block.
820     if (I != MF.begin()) {
821       printBasicBlockLabel(I, true);
822       O << '\n';
823     }
824     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
825          II != E; ++II) {
826       // Print the assembly for the instruction.
827       O << "\t";
828       printMachineInstruction(II);
829     }
830   }
831
832   // Print out jump tables referenced by the function.
833   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
834   
835   // Emit post-function debug information.
836   DW.EndFunction();
837   
838   // We didn't modify anything.
839   return false;
840 }
841
842
843 bool DarwinAsmPrinter::doInitialization(Module &M) {
844   static const char *CPUDirectives[] = {
845     "ppc",
846     "ppc601",
847     "ppc602",
848     "ppc603",
849     "ppc7400",
850     "ppc750",
851     "ppc970",
852     "ppc64"
853   };
854
855   unsigned Directive = Subtarget.getDarwinDirective();
856   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
857     Directive = PPC::DIR_970;
858   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
859     Directive = PPC::DIR_7400;
860   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
861     Directive = PPC::DIR_64;
862   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
863   O << "\t.machine " << CPUDirectives[Directive] << "\n";
864      
865   bool Result = AsmPrinter::doInitialization(M);
866   
867   // Darwin wants symbols to be quoted if they have complex names.
868   Mang->setUseQuotes(true);
869   
870   // Prime text sections so they are adjacent.  This reduces the likelihood a
871   // large data or debug section causes a branch to exceed 16M limit.
872   SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
873                       "pure_instructions");
874   if (TM.getRelocationModel() == Reloc::PIC_) {
875     SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
876                           "pure_instructions,32");
877   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
878     SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
879                         "pure_instructions,16");
880   }
881   SwitchToTextSection(TAI->getTextSection());
882   
883   // Emit initial debug information.
884   DW.BeginModule(&M);
885   return Result;
886 }
887
888 bool DarwinAsmPrinter::doFinalization(Module &M) {
889   const TargetData *TD = TM.getTargetData();
890
891   // Print out module-level global variables here.
892   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
893        I != E; ++I) {
894     if (!I->hasInitializer()) continue;   // External global require no code
895     
896     // Check to see if this is a special global used by LLVM, if so, emit it.
897     if (EmitSpecialLLVMGlobal(I)) {
898       if (TM.getRelocationModel() == Reloc::Static) {
899         if (I->getName() == "llvm.global_ctors")
900           O << ".reference .constructors_used\n";
901         else if (I->getName() == "llvm.global_dtors")
902           O << ".reference .destructors_used\n";
903       }
904       continue;
905     }
906     
907     std::string name = Mang->getValueName(I);
908     
909     if (I->hasHiddenVisibility())
910       if (const char *Directive = TAI->getHiddenDirective())
911         O << Directive << name << "\n";
912     
913     Constant *C = I->getInitializer();
914     const Type *Type = C->getType();
915     unsigned Size = TD->getABITypeSize(Type);
916     unsigned Align = TD->getPreferredAlignmentLog(I);
917
918     if (C->isNullValue() && /* FIXME: Verify correct */
919         !I->hasSection() &&
920         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
921          I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
922       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
923       if (I->hasExternalLinkage()) {
924         O << "\t.globl " << name << '\n';
925         O << "\t.zerofill __DATA, __common, " << name << ", "
926           << Size << ", " << Align;
927       } else if (I->hasInternalLinkage()) {
928         SwitchToDataSection("\t.data", I);
929         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
930       } else {
931         SwitchToDataSection("\t.data", I);
932         O << ".comm " << name << "," << Size;
933       }
934       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
935     } else {
936       switch (I->getLinkage()) {
937       case GlobalValue::LinkOnceLinkage:
938       case GlobalValue::WeakLinkage:
939         O << "\t.globl " << name << '\n'
940           << "\t.weak_definition " << name << '\n';
941         SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
942         break;
943       case GlobalValue::AppendingLinkage:
944         // FIXME: appending linkage variables should go into a section of
945         // their name or something.  For now, just emit them as external.
946       case GlobalValue::ExternalLinkage:
947         // If external or appending, declare as a global symbol
948         O << "\t.globl " << name << "\n";
949         // FALL THROUGH
950       case GlobalValue::InternalLinkage:
951         if (I->isConstant()) {
952           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
953           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
954             SwitchToDataSection(TAI->getCStringSection(), I);
955             break;
956           }
957         }
958
959         if (!I->isConstant())
960           SwitchToDataSection(TAI->getDataSection(), I);
961         else {
962           // Read-only data.
963           bool HasReloc = C->ContainsRelocations();
964           if (HasReloc &&
965               TM.getRelocationModel() != Reloc::Static)
966             SwitchToDataSection("\t.const_data\n");
967           else if (!HasReloc && Size == 4 &&
968                    TAI->getFourByteConstantSection())
969             SwitchToDataSection(TAI->getFourByteConstantSection(), I);
970           else if (!HasReloc && Size == 8 &&
971                    TAI->getEightByteConstantSection())
972             SwitchToDataSection(TAI->getEightByteConstantSection(), I);
973           else if (!HasReloc && Size == 16 &&
974                    TAI->getSixteenByteConstantSection())
975             SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
976           else if (TAI->getReadOnlySection())
977             SwitchToDataSection(TAI->getReadOnlySection(), I);
978           else
979             SwitchToDataSection(TAI->getDataSection(), I);
980         }
981         break;
982       default:
983         cerr << "Unknown linkage type!";
984         abort();
985       }
986
987       EmitAlignment(Align, I);
988       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
989         << I->getName() << "'\n";
990
991       // If the initializer is a extern weak symbol, remember to emit the weak
992       // reference!
993       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
994         if (GV->hasExternalWeakLinkage())
995           ExtWeakSymbols.insert(GV);
996
997       EmitGlobalConstant(C);
998       O << '\n';
999     }
1000   }
1001
1002   bool isPPC64 = TD->getPointerSizeInBits() == 64;
1003
1004   // Output stubs for dynamically-linked functions
1005   if (TM.getRelocationModel() == Reloc::PIC_) {
1006     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1007          i != e; ++i) {
1008       SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
1009                           "pure_instructions,32");
1010       EmitAlignment(4);
1011       O << "L" << *i << "$stub:\n";
1012       O << "\t.indirect_symbol " << *i << "\n";
1013       O << "\tmflr r0\n";
1014       O << "\tbcl 20,31,L0$" << *i << "\n";
1015       O << "L0$" << *i << ":\n";
1016       O << "\tmflr r11\n";
1017       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
1018       O << "\tmtlr r0\n";
1019       if (isPPC64)
1020         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1021       else
1022         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1023       O << "\tmtctr r12\n";
1024       O << "\tbctr\n";
1025       SwitchToDataSection(".lazy_symbol_pointer");
1026       O << "L" << *i << "$lazy_ptr:\n";
1027       O << "\t.indirect_symbol " << *i << "\n";
1028       if (isPPC64)
1029         O << "\t.quad dyld_stub_binding_helper\n";
1030       else
1031         O << "\t.long dyld_stub_binding_helper\n";
1032     }
1033   } else {
1034     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1035          i != e; ++i) {
1036       SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
1037                           "pure_instructions,16");
1038       EmitAlignment(4);
1039       O << "L" << *i << "$stub:\n";
1040       O << "\t.indirect_symbol " << *i << "\n";
1041       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
1042       if (isPPC64)
1043         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1044       else
1045         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1046       O << "\tmtctr r12\n";
1047       O << "\tbctr\n";
1048       SwitchToDataSection(".lazy_symbol_pointer");
1049       O << "L" << *i << "$lazy_ptr:\n";
1050       O << "\t.indirect_symbol " << *i << "\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 (ExceptionHandling && TAI->doesSupportExceptionHandling() && MMI) {
1061     // Add the (possibly multiple) personalities to the set of global values.
1062     const std::vector<Function *>& Personalities = MMI->getPersonalities();
1063
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 (std::set<std::string>::iterator I = GVStubs.begin(),
1073          E = GVStubs.end(); I != E; ++I) {
1074       O << "L" << *I << "$non_lazy_ptr:\n";
1075       O << "\t.indirect_symbol " << *I << "\n";
1076       if (isPPC64)
1077         O << "\t.quad\t0\n";
1078       else
1079         O << "\t.long\t0\n";
1080         
1081     }
1082   }
1083
1084   // Emit initial debug information.
1085   DW.EndModule();
1086
1087   // Funny Darwin hack: This flag tells the linker that no global symbols
1088   // contain code that falls through to other global symbols (e.g. the obvious
1089   // implementation of multiple entry points).  If this doesn't occur, the
1090   // linker can safely perform dead code stripping.  Since LLVM never generates
1091   // code that does this, it is always safe to set.
1092   O << "\t.subsections_via_symbols\n";
1093
1094   return AsmPrinter::doFinalization(M);
1095 }
1096
1097
1098
1099 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1100 /// for a MachineFunction to the given output stream, in a format that the
1101 /// Darwin assembler can deal with.
1102 ///
1103 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1104                                             PPCTargetMachine &tm) {
1105   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1106
1107   if (Subtarget->isDarwin()) {
1108     return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1109   } else {
1110     return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1111   }
1112 }
1113