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