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