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