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