add a new MachineBasicBlock::getSymbol method, replacing
[oota-llvm.git] / lib / Target / PowerPC / AsmPrinter / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly --------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "asmprinter"
20 #include "PPC.h"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
54 using namespace llvm;
55
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
57
58 namespace {
59   class PPCAsmPrinter : public AsmPrinter {
60   protected:
61     DenseMap<const MCSymbol*, const MCSymbol*> TOC;
62     const PPCSubtarget &Subtarget;
63     uint64_t LabelID;
64   public:
65     explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
66                            const MCAsmInfo *T, bool V)
67       : AsmPrinter(O, TM, T, V),
68         Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
69
70     virtual const char *getPassName() const {
71       return "PowerPC Assembly Printer";
72     }
73
74     PPCTargetMachine &getTM() {
75       return static_cast<PPCTargetMachine&>(TM);
76     }
77
78     unsigned enumRegToMachineReg(unsigned enumReg) {
79       switch (enumReg) {
80       default: llvm_unreachable("Unhandled register!");
81       case PPC::CR0:  return  0;
82       case PPC::CR1:  return  1;
83       case PPC::CR2:  return  2;
84       case PPC::CR3:  return  3;
85       case PPC::CR4:  return  4;
86       case PPC::CR5:  return  5;
87       case PPC::CR6:  return  6;
88       case PPC::CR7:  return  7;
89       }
90       llvm_unreachable(0);
91     }
92
93     /// printInstruction - This method is automatically generated by tablegen
94     /// from the instruction set description.  This method returns true if the
95     /// machine instruction was sufficiently described to print it, otherwise it
96     /// returns false.
97     void printInstruction(const MachineInstr *MI);
98     static const char *getRegisterName(unsigned RegNo);
99
100
101     void printMachineInstruction(const MachineInstr *MI);
102     void printOp(const MachineOperand &MO);
103
104     /// stripRegisterPrefix - This method strips the character prefix from a
105     /// register name so that only the number is left.  Used by for linux asm.
106     const char *stripRegisterPrefix(const char *RegName) {
107       switch (RegName[0]) {
108       case 'r':
109       case 'f':
110       case 'v': return RegName + 1;
111       case 'c': if (RegName[1] == 'r') return RegName + 2;
112       }
113
114       return RegName;
115     }
116
117     /// printRegister - Print register according to target requirements.
118     ///
119     void printRegister(const MachineOperand &MO, bool R0AsZero) {
120       unsigned RegNo = MO.getReg();
121       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
122
123       // If we should use 0 for R0.
124       if (R0AsZero && RegNo == PPC::R0) {
125         O << "0";
126         return;
127       }
128
129       const char *RegName = getRegisterName(RegNo);
130       // Linux assembler (Others?) does not take register mnemonics.
131       // FIXME - What about special registers used in mfspr/mtspr?
132       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
133       O << RegName;
134     }
135
136     void printOperand(const MachineInstr *MI, unsigned OpNo) {
137       const MachineOperand &MO = MI->getOperand(OpNo);
138       if (MO.isReg()) {
139         printRegister(MO, false);
140       } else if (MO.isImm()) {
141         O << MO.getImm();
142       } else {
143         printOp(MO);
144       }
145     }
146
147     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
148                          unsigned AsmVariant, const char *ExtraCode);
149     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
150                                unsigned AsmVariant, const char *ExtraCode);
151
152
153     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
154       char value = MI->getOperand(OpNo).getImm();
155       value = (value << (32-5)) >> (32-5);
156       O << (int)value;
157     }
158     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
159       unsigned char value = MI->getOperand(OpNo).getImm();
160       assert(value <= 31 && "Invalid u5imm argument!");
161       O << (unsigned int)value;
162     }
163     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
164       unsigned char value = MI->getOperand(OpNo).getImm();
165       assert(value <= 63 && "Invalid u6imm argument!");
166       O << (unsigned int)value;
167     }
168     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
169       O << (short)MI->getOperand(OpNo).getImm();
170     }
171     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
172       O << (unsigned short)MI->getOperand(OpNo).getImm();
173     }
174     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
175       if (MI->getOperand(OpNo).isImm()) {
176         O << (short)(MI->getOperand(OpNo).getImm()*4);
177       } else {
178         O << "lo16(";
179         printOp(MI->getOperand(OpNo));
180         if (TM.getRelocationModel() == Reloc::PIC_)
181           O << "-\"L" << getFunctionNumber() << "$pb\")";
182         else
183           O << ')';
184       }
185     }
186     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
187       // Branches can take an immediate operand.  This is used by the branch
188       // selection pass to print $+8, an eight byte displacement from the PC.
189       if (MI->getOperand(OpNo).isImm()) {
190         O << "$+" << MI->getOperand(OpNo).getImm()*4;
191       } else {
192         printOp(MI->getOperand(OpNo));
193       }
194     }
195     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
196       const MachineOperand &MO = MI->getOperand(OpNo);
197       if (TM.getRelocationModel() != Reloc::Static) {
198         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
199           GlobalValue *GV = MO.getGlobal();
200           if (GV->isDeclaration() || GV->isWeakForLinker()) {
201             // Dynamically-resolved functions need a stub for the function.
202             MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
203             const MCSymbol *&StubSym =
204               MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
205             if (StubSym == 0)
206               StubSym = GetGlobalValueSymbol(GV);
207             O << *Sym;
208             return;
209           }
210         }
211         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
212           SmallString<128> TempNameStr;
213           TempNameStr += StringRef(MO.getSymbolName());
214           TempNameStr += StringRef("$stub");
215           
216           const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
217           const MCSymbol *&StubSym =
218             MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
219           if (StubSym == 0)
220             StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
221           O << *Sym;
222           return;
223         }
224       }
225
226       printOp(MI->getOperand(OpNo));
227     }
228     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
229      O << (int)MI->getOperand(OpNo).getImm()*4;
230     }
231     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
232       O << "\"L" << getFunctionNumber() << "$pb\"\n";
233       O << "\"L" << getFunctionNumber() << "$pb\":";
234     }
235     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
236       if (MI->getOperand(OpNo).isImm()) {
237         printS16ImmOperand(MI, OpNo);
238       } else {
239         if (Subtarget.isDarwin()) O << "ha16(";
240         printOp(MI->getOperand(OpNo));
241         if (TM.getRelocationModel() == Reloc::PIC_)
242           O << "-\"L" << getFunctionNumber() << "$pb\"";
243         if (Subtarget.isDarwin())
244           O << ')';
245         else
246           O << "@ha";
247       }
248     }
249     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
250       if (MI->getOperand(OpNo).isImm()) {
251         printS16ImmOperand(MI, OpNo);
252       } else {
253         if (Subtarget.isDarwin()) O << "lo16(";
254         printOp(MI->getOperand(OpNo));
255         if (TM.getRelocationModel() == Reloc::PIC_)
256           O << "-\"L" << getFunctionNumber() << "$pb\"";
257         if (Subtarget.isDarwin())
258           O << ')';
259         else
260           O << "@l";
261       }
262     }
263     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
264       unsigned CCReg = MI->getOperand(OpNo).getReg();
265       unsigned RegNo = enumRegToMachineReg(CCReg);
266       O << (0x80 >> RegNo);
267     }
268     // The new addressing mode printers.
269     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
270       printSymbolLo(MI, OpNo);
271       O << '(';
272       if (MI->getOperand(OpNo+1).isReg() &&
273           MI->getOperand(OpNo+1).getReg() == PPC::R0)
274         O << "0";
275       else
276         printOperand(MI, OpNo+1);
277       O << ')';
278     }
279     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
280       if (MI->getOperand(OpNo).isImm())
281         printS16X4ImmOperand(MI, OpNo);
282       else
283         printSymbolLo(MI, OpNo);
284       O << '(';
285       if (MI->getOperand(OpNo+1).isReg() &&
286           MI->getOperand(OpNo+1).getReg() == PPC::R0)
287         O << "0";
288       else
289         printOperand(MI, OpNo+1);
290       O << ')';
291     }
292
293     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
294       // When used as the base register, r0 reads constant zero rather than
295       // the value contained in the register.  For this reason, the darwin
296       // assembler requires that we print r0 as 0 (no r) when used as the base.
297       const MachineOperand &MO = MI->getOperand(OpNo);
298       printRegister(MO, true);
299       O << ", ";
300       printOperand(MI, OpNo+1);
301     }
302
303     void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
304       const MachineOperand &MO = MI->getOperand(OpNo);
305
306       assert(MO.getType() == MachineOperand::MO_GlobalAddress);
307
308       const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
309
310       // Map symbol -> label of TOC entry.
311       const MCSymbol *&TOCEntry = TOC[Sym];
312       if (TOCEntry == 0)
313         TOCEntry = OutContext.
314           GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
315                             Twine(LabelID++));
316
317       O << *TOCEntry << "@toc";
318     }
319
320     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
321                                const char *Modifier);
322
323     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
324   };
325
326   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
327   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
328   public:
329     explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
330                                 const MCAsmInfo *T, bool V)
331       : PPCAsmPrinter(O, TM, T, V){}
332
333     virtual const char *getPassName() const {
334       return "Linux PPC Assembly Printer";
335     }
336
337     bool runOnMachineFunction(MachineFunction &F);
338     bool doFinalization(Module &M);
339
340     void getAnalysisUsage(AnalysisUsage &AU) const {
341       AU.setPreservesAll();
342       AU.addRequired<MachineModuleInfo>();
343       AU.addRequired<DwarfWriter>();
344       PPCAsmPrinter::getAnalysisUsage(AU);
345     }
346   };
347
348   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
349   /// OS X
350   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
351     formatted_raw_ostream &OS;
352   public:
353     explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
354                                  const MCAsmInfo *T, bool V)
355       : PPCAsmPrinter(O, TM, T, V), OS(O) {}
356
357     virtual const char *getPassName() const {
358       return "Darwin PPC Assembly Printer";
359     }
360
361     bool runOnMachineFunction(MachineFunction &F);
362     bool doFinalization(Module &M);
363     void EmitStartOfAsmFile(Module &M);
364
365     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
366     
367     void getAnalysisUsage(AnalysisUsage &AU) const {
368       AU.setPreservesAll();
369       AU.addRequired<MachineModuleInfo>();
370       AU.addRequired<DwarfWriter>();
371       PPCAsmPrinter::getAnalysisUsage(AU);
372     }
373   };
374 } // end of anonymous namespace
375
376 // Include the auto-generated portion of the assembly writer
377 #include "PPCGenAsmWriter.inc"
378
379 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
380   switch (MO.getType()) {
381   case MachineOperand::MO_Immediate:
382     llvm_unreachable("printOp() does not handle immediate values");
383
384   case MachineOperand::MO_MachineBasicBlock:
385     O << *MO.getMBB()->getSymbol(OutContext);
386     return;
387   case MachineOperand::MO_JumpTableIndex:
388     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
389       << '_' << MO.getIndex();
390     // FIXME: PIC relocation model
391     return;
392   case MachineOperand::MO_ConstantPoolIndex:
393     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
394       << '_' << MO.getIndex();
395     return;
396   case MachineOperand::MO_BlockAddress:
397     O << *GetBlockAddressSymbol(MO.getBlockAddress());
398     return;
399   case MachineOperand::MO_ExternalSymbol: {
400     // Computing the address of an external symbol, not calling it.
401     if (TM.getRelocationModel() == Reloc::Static) {
402       O << *GetExternalSymbolSymbol(MO.getSymbolName());
403       return;
404     }
405
406     const MCSymbol *NLPSym = 
407       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
408                                    MO.getSymbolName()+"$non_lazy_ptr");
409     const MCSymbol *&StubSym = 
410       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
411     if (StubSym == 0)
412       StubSym = GetExternalSymbolSymbol(MO.getSymbolName());
413     
414     O << *NLPSym;
415     return;
416   }
417   case MachineOperand::MO_GlobalAddress: {
418     // Computing the address of a global symbol, not calling it.
419     GlobalValue *GV = MO.getGlobal();
420     MCSymbol *SymToPrint;
421
422     // External or weakly linked global variables need non-lazily-resolved stubs
423     if (TM.getRelocationModel() != Reloc::Static &&
424         (GV->isDeclaration() || GV->isWeakForLinker())) {
425       if (!GV->hasHiddenVisibility()) {
426         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
427         const MCSymbol *&StubSym = 
428        MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(SymToPrint);
429         if (StubSym == 0)
430           StubSym = GetGlobalValueSymbol(GV);
431       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
432                  GV->hasAvailableExternallyLinkage()) {
433         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
434         
435         const MCSymbol *&StubSym = 
436           MMI->getObjFileInfo<MachineModuleInfoMachO>().
437                     getHiddenGVStubEntry(SymToPrint);
438         if (StubSym == 0)
439           StubSym = GetGlobalValueSymbol(GV);
440       } else {
441         SymToPrint = GetGlobalValueSymbol(GV);
442       }
443     } else {
444       SymToPrint = GetGlobalValueSymbol(GV);
445     }
446     
447     O << *SymToPrint;
448
449     printOffset(MO.getOffset());
450     return;
451   }
452
453   default:
454     O << "<unknown operand type: " << MO.getType() << ">";
455     return;
456   }
457 }
458
459 /// PrintAsmOperand - Print out an operand for an inline asm expression.
460 ///
461 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
462                                     unsigned AsmVariant,
463                                     const char *ExtraCode) {
464   // Does this asm operand have a single letter operand modifier?
465   if (ExtraCode && ExtraCode[0]) {
466     if (ExtraCode[1] != 0) return true; // Unknown modifier.
467
468     switch (ExtraCode[0]) {
469     default: return true;  // Unknown modifier.
470     case 'c': // Don't print "$" before a global var name or constant.
471       // PPC never has a prefix.
472       printOperand(MI, OpNo);
473       return false;
474     case 'L': // Write second word of DImode reference.
475       // Verify that this operand has two consecutive registers.
476       if (!MI->getOperand(OpNo).isReg() ||
477           OpNo+1 == MI->getNumOperands() ||
478           !MI->getOperand(OpNo+1).isReg())
479         return true;
480       ++OpNo;   // Return the high-part.
481       break;
482     case 'I':
483       // Write 'i' if an integer constant, otherwise nothing.  Used to print
484       // addi vs add, etc.
485       if (MI->getOperand(OpNo).isImm())
486         O << "i";
487       return false;
488     }
489   }
490
491   printOperand(MI, OpNo);
492   return false;
493 }
494
495 // At the moment, all inline asm memory operands are a single register.
496 // In any case, the output of this routine should always be just one
497 // assembler operand.
498
499 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
500                                           unsigned AsmVariant,
501                                           const char *ExtraCode) {
502   if (ExtraCode && ExtraCode[0])
503     return true; // Unknown modifier.
504   assert (MI->getOperand(OpNo).isReg());
505   O << "0(";
506   printOperand(MI, OpNo);
507   O << ")";
508   return false;
509 }
510
511 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
512                                           const char *Modifier) {
513   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
514   unsigned Code = MI->getOperand(OpNo).getImm();
515   if (!strcmp(Modifier, "cc")) {
516     switch ((PPC::Predicate)Code) {
517     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
518     case PPC::PRED_LT: O << "lt"; return;
519     case PPC::PRED_LE: O << "le"; return;
520     case PPC::PRED_EQ: O << "eq"; return;
521     case PPC::PRED_GE: O << "ge"; return;
522     case PPC::PRED_GT: O << "gt"; return;
523     case PPC::PRED_NE: O << "ne"; return;
524     case PPC::PRED_UN: O << "un"; return;
525     case PPC::PRED_NU: O << "nu"; return;
526     }
527
528   } else {
529     assert(!strcmp(Modifier, "reg") &&
530            "Need to specify 'cc' or 'reg' as predicate op modifier!");
531     // Don't print the register for 'always'.
532     if (Code == PPC::PRED_ALWAYS) return;
533     printOperand(MI, OpNo+1);
534   }
535 }
536
537
538 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
539 /// the current output stream.
540 ///
541 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
542   ++EmittedInsts;
543   
544   processDebugLoc(MI, true);
545
546   // Check for slwi/srwi mnemonics.
547   bool useSubstituteMnemonic = false;
548   if (MI->getOpcode() == PPC::RLWINM) {
549     unsigned char SH = MI->getOperand(2).getImm();
550     unsigned char MB = MI->getOperand(3).getImm();
551     unsigned char ME = MI->getOperand(4).getImm();
552     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
553       O << "\tslwi "; useSubstituteMnemonic = true;
554     }
555     if (SH <= 31 && MB == (32-SH) && ME == 31) {
556       O << "\tsrwi "; useSubstituteMnemonic = true;
557       SH = 32-SH;
558     }
559     if (useSubstituteMnemonic) {
560       printOperand(MI, 0);
561       O << ", ";
562       printOperand(MI, 1);
563       O << ", " << (unsigned int)SH;
564     }
565   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
566     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
567       useSubstituteMnemonic = true;
568       O << "\tmr ";
569       printOperand(MI, 0);
570       O << ", ";
571       printOperand(MI, 1);
572     }
573   } else if (MI->getOpcode() == PPC::RLDICR) {
574     unsigned char SH = MI->getOperand(2).getImm();
575     unsigned char ME = MI->getOperand(3).getImm();
576     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
577     if (63-SH == ME) {
578       useSubstituteMnemonic = true;
579       O << "\tsldi ";
580       printOperand(MI, 0);
581       O << ", ";
582       printOperand(MI, 1);
583       O << ", " << (unsigned int)SH;
584     }
585   }
586
587   if (!useSubstituteMnemonic)
588     printInstruction(MI);
589
590   if (VerboseAsm)
591     EmitComments(*MI);
592   O << '\n';
593
594   processDebugLoc(MI, false);
595 }
596
597 /// runOnMachineFunction - This uses the printMachineInstruction()
598 /// method to print assembly for each instruction.
599 ///
600 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
601   SetupMachineFunction(MF);
602   O << "\n\n";
603
604   // Print out constants referenced by the function
605   EmitConstantPool(MF.getConstantPool());
606
607   // Print out labels for the function.
608   const Function *F = MF.getFunction();
609   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
610
611   switch (F->getLinkage()) {
612   default: llvm_unreachable("Unknown linkage type!");
613   case Function::PrivateLinkage:
614   case Function::InternalLinkage:  // Symbols default to internal.
615     break;
616   case Function::ExternalLinkage:
617     O << "\t.global\t" << *CurrentFnSym << '\n' << "\t.type\t";
618     O << *CurrentFnSym << ", @function\n";
619     break;
620   case Function::LinkerPrivateLinkage:
621   case Function::WeakAnyLinkage:
622   case Function::WeakODRLinkage:
623   case Function::LinkOnceAnyLinkage:
624   case Function::LinkOnceODRLinkage:
625     O << "\t.global\t" << *CurrentFnSym << '\n';
626     O << "\t.weak\t" << *CurrentFnSym << '\n';
627     break;
628   }
629
630   printVisibility(CurrentFnSym, F->getVisibility());
631
632   EmitAlignment(MF.getAlignment(), F);
633
634   if (Subtarget.isPPC64()) {
635     // Emit an official procedure descriptor.
636     // FIXME 64-bit SVR4: Use MCSection here!
637     O << "\t.section\t\".opd\",\"aw\"\n";
638     O << "\t.align 3\n";
639     O << *CurrentFnSym << ":\n";
640     O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
641     O << "\t.previous\n";
642     O << ".L." << *CurrentFnSym << ":\n";
643   } else {
644     O << *CurrentFnSym << ":\n";
645   }
646
647   // Emit pre-function debug information.
648   DW->BeginFunction(&MF);
649
650   // Print out code for the function.
651   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
652        I != E; ++I) {
653     // Print a label for the basic block.
654     if (I != MF.begin()) {
655       EmitBasicBlockStart(I);
656     }
657     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
658          II != E; ++II) {
659       // Print the assembly for the instruction.
660       printMachineInstruction(II);
661     }
662   }
663
664   O << "\t.size\t" << *CurrentFnSym << ",.-" << *CurrentFnSym << '\n';
665
666   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
667
668   // Emit post-function debug information.
669   DW->EndFunction(&MF);
670
671   // Print out jump tables referenced by the function.
672   EmitJumpTableInfo(MF);
673
674   // We didn't modify anything.
675   return false;
676 }
677
678 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
679   const TargetData *TD = TM.getTargetData();
680
681   bool isPPC64 = TD->getPointerSizeInBits() == 64;
682
683   if (isPPC64 && !TOC.empty()) {
684     // FIXME 64-bit SVR4: Use MCSection here?
685     O << "\t.section\t\".toc\",\"aw\"\n";
686
687     // FIXME: This is nondeterminstic!
688     for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
689          E = TOC.end(); I != E; ++I) {
690       O << *I->second << ":\n";
691       O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
692     }
693   }
694
695   return AsmPrinter::doFinalization(M);
696 }
697
698 /// runOnMachineFunction - This uses the printMachineInstruction()
699 /// method to print assembly for each instruction.
700 ///
701 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
702   SetupMachineFunction(MF);
703   O << "\n\n";
704
705   // Print out constants referenced by the function
706   EmitConstantPool(MF.getConstantPool());
707
708   // Print out labels for the function.
709   const Function *F = MF.getFunction();
710   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
711
712   switch (F->getLinkage()) {
713   default: llvm_unreachable("Unknown linkage type!");
714   case Function::PrivateLinkage:
715   case Function::InternalLinkage:  // Symbols default to internal.
716     break;
717   case Function::ExternalLinkage:
718     O << "\t.globl\t" << *CurrentFnSym << '\n';
719     break;
720   case Function::WeakAnyLinkage:
721   case Function::WeakODRLinkage:
722   case Function::LinkOnceAnyLinkage:
723   case Function::LinkOnceODRLinkage:
724   case Function::LinkerPrivateLinkage:
725     O << "\t.globl\t" << *CurrentFnSym << '\n';
726     O << "\t.weak_definition\t" << *CurrentFnSym << '\n';
727     break;
728   }
729
730   printVisibility(CurrentFnSym, F->getVisibility());
731
732   EmitAlignment(MF.getAlignment(), F);
733   O << *CurrentFnSym << ":\n";
734
735   // Emit pre-function debug information.
736   DW->BeginFunction(&MF);
737
738   // If the function is empty, then we need to emit *something*. Otherwise, the
739   // function's label might be associated with something that it wasn't meant to
740   // be associated with. We emit a noop in this situation.
741   MachineFunction::iterator I = MF.begin();
742
743   if (++I == MF.end() && MF.front().empty())
744     O << "\tnop\n";
745
746   // Print out code for the function.
747   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
748        I != E; ++I) {
749     // Print a label for the basic block.
750     if (I != MF.begin()) {
751       EmitBasicBlockStart(I);
752     }
753     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
754          II != IE; ++II) {
755       // Print the assembly for the instruction.
756       printMachineInstruction(II);
757     }
758   }
759
760   // Emit post-function debug information.
761   DW->EndFunction(&MF);
762
763   // Print out jump tables referenced by the function.
764   EmitJumpTableInfo(MF);
765
766   // We didn't modify anything.
767   return false;
768 }
769
770
771 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
772   static const char *const CPUDirectives[] = {
773     "",
774     "ppc",
775     "ppc601",
776     "ppc602",
777     "ppc603",
778     "ppc7400",
779     "ppc750",
780     "ppc970",
781     "ppc64"
782   };
783
784   unsigned Directive = Subtarget.getDarwinDirective();
785   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
786     Directive = PPC::DIR_970;
787   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
788     Directive = PPC::DIR_7400;
789   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
790     Directive = PPC::DIR_64;
791   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
792   O << "\t.machine " << CPUDirectives[Directive] << '\n';
793
794   // Prime text sections so they are adjacent.  This reduces the likelihood a
795   // large data or debug section causes a branch to exceed 16M limit.
796   TargetLoweringObjectFileMachO &TLOFMacho = 
797     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
798   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
799   if (TM.getRelocationModel() == Reloc::PIC_) {
800     OutStreamer.SwitchSection(
801             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
802                                       MCSectionMachO::S_SYMBOL_STUBS |
803                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
804                                       32, SectionKind::getText()));
805   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
806     OutStreamer.SwitchSection(
807             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
808                                       MCSectionMachO::S_SYMBOL_STUBS |
809                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
810                                       16, SectionKind::getText()));
811   }
812   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
813 }
814
815 static const MCSymbol *GetLazyPtr(const MCSymbol *Sym, MCContext &Ctx) {
816   // Remove $stub suffix, add $lazy_ptr.
817   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
818   TmpStr += "$lazy_ptr";
819   return Ctx.GetOrCreateSymbol(TmpStr.str());
820 }
821
822 static const MCSymbol *GetAnonSym(const MCSymbol *Sym, MCContext &Ctx) {
823   // Add $tmp suffix to $stub, yielding $stub$tmp.
824   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
825   TmpStr += "$tmp";
826   return Ctx.GetOrCreateSymbol(TmpStr.str());
827 }
828
829 void PPCDarwinAsmPrinter::
830 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
831   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
832   
833   TargetLoweringObjectFileMachO &TLOFMacho = 
834     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
835
836   // .lazy_symbol_pointer
837   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
838   
839   // Output stubs for dynamically-linked functions
840   if (TM.getRelocationModel() == Reloc::PIC_) {
841     const MCSection *StubSection = 
842     TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
843                               MCSectionMachO::S_SYMBOL_STUBS |
844                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
845                               32, SectionKind::getText());
846     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
847       OutStreamer.SwitchSection(StubSection);
848       EmitAlignment(4);
849       
850       const MCSymbol *Stub = Stubs[i].first;
851       const MCSymbol *RawSym = Stubs[i].second;
852       const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
853       const MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
854                                            
855       O << *Stub << ":\n";
856       O << "\t.indirect_symbol " << *RawSym << '\n';
857       O << "\tmflr r0\n";
858       O << "\tbcl 20,31," << *AnonSymbol << '\n';
859       O << *AnonSymbol << ":\n";
860       O << "\tmflr r11\n";
861       O << "\taddis r11,r11,ha16(" << *LazyPtr << '-' << *AnonSymbol
862       << ")\n";
863       O << "\tmtlr r0\n";
864       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *LazyPtr
865       << '-' << *AnonSymbol << ")(r11)\n";
866       O << "\tmtctr r12\n";
867       O << "\tbctr\n";
868       
869       OutStreamer.SwitchSection(LSPSection);
870       O << *LazyPtr << ":\n";
871       O << "\t.indirect_symbol " << *RawSym << '\n';
872       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
873     }
874     O << '\n';
875     return;
876   }
877   
878   const MCSection *StubSection =
879     TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
880                               MCSectionMachO::S_SYMBOL_STUBS |
881                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
882                               16, SectionKind::getText());
883   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
884     const MCSymbol *Stub = Stubs[i].first;
885     const MCSymbol *RawSym = Stubs[i].second;
886     const MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
887
888     OutStreamer.SwitchSection(StubSection);
889     EmitAlignment(4);
890     O << *Stub << ":\n";
891     O << "\t.indirect_symbol " << *RawSym << '\n';
892     O << "\tlis r11,ha16(" << *LazyPtr << ")\n";
893     O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(" << *LazyPtr
894     << ")(r11)\n";
895     O << "\tmtctr r12\n";
896     O << "\tbctr\n";
897     OutStreamer.SwitchSection(LSPSection);
898     O << *LazyPtr << ":\n";
899     O << "\t.indirect_symbol " << *RawSym << '\n';
900     O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
901   }
902   
903   O << '\n';
904 }
905
906
907 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
908   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
909
910   // Darwin/PPC always uses mach-o.
911   TargetLoweringObjectFileMachO &TLOFMacho = 
912     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
913   MachineModuleInfoMachO &MMIMacho =
914     MMI->getObjFileInfo<MachineModuleInfoMachO>();
915   
916   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
917   if (!Stubs.empty())
918     EmitFunctionStubs(Stubs);
919
920   if (MAI->doesSupportExceptionHandling() && MMI) {
921     // Add the (possibly multiple) personalities to the set of global values.
922     // Only referenced functions get into the Personalities list.
923     const std::vector<Function *> &Personalities = MMI->getPersonalities();
924     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
925          E = Personalities.end(); I != E; ++I) {
926       if (*I) {
927         const MCSymbol *NLPSym = 
928           GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
929         const MCSymbol *&StubSym = MMIMacho.getGVStubEntry(NLPSym);
930         StubSym = GetGlobalValueSymbol(*I);
931       }
932     }
933   }
934
935   // Output stubs for dynamically-linked functions.
936   Stubs = MMIMacho.GetGVStubList();
937   
938   // Output macho stubs for external and common global variables.
939   if (!Stubs.empty()) {
940     // Switch with ".non_lazy_symbol_pointer" directive.
941     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
942     EmitAlignment(isPPC64 ? 3 : 2);
943     
944     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
945       O << *Stubs[i].first << ":\n";
946       O << "\t.indirect_symbol " << *Stubs[i].second << '\n';
947       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
948     }
949   }
950
951   Stubs = MMIMacho.GetHiddenGVStubList();
952   if (!Stubs.empty()) {
953     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
954     EmitAlignment(isPPC64 ? 3 : 2);
955     
956     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
957       O << *Stubs[i].first << ":\n";
958       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *Stubs[i].second << '\n';
959     }
960   }
961
962   // Funny Darwin hack: This flag tells the linker that no global symbols
963   // contain code that falls through to other global symbols (e.g. the obvious
964   // implementation of multiple entry points).  If this doesn't occur, the
965   // linker can safely perform dead code stripping.  Since LLVM never generates
966   // code that does this, it is always safe to set.
967   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
968
969   return AsmPrinter::doFinalization(M);
970 }
971
972
973
974 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
975 /// for a MachineFunction to the given output stream, in a format that the
976 /// Darwin assembler can deal with.
977 ///
978 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
979                                            TargetMachine &tm,
980                                            const MCAsmInfo *tai,
981                                            bool verbose) {
982   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
983
984   if (Subtarget->isDarwin())
985     return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
986   return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
987 }
988
989 // Force static initialization.
990 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
991   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
992   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
993 }