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