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