Momentous day: remove the "O" member from AsmPrinter. Now all
[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.setPreservesAll();
348       AU.addRequired<MachineModuleInfo>();
349       AU.addRequired<DwarfWriter>();
350       PPCAsmPrinter::getAnalysisUsage(AU);
351     }
352   };
353
354   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
355   /// OS X
356   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
357   public:
358     explicit PPCDarwinAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
359       : PPCAsmPrinter(TM, Streamer) {}
360
361     virtual const char *getPassName() const {
362       return "Darwin PPC Assembly Printer";
363     }
364
365     bool doFinalization(Module &M);
366     void EmitStartOfAsmFile(Module &M);
367
368     void EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs);
369     
370     void getAnalysisUsage(AnalysisUsage &AU) const {
371       AU.setPreservesAll();
372       AU.addRequired<MachineModuleInfo>();
373       AU.addRequired<DwarfWriter>();
374       PPCAsmPrinter::getAnalysisUsage(AU);
375     }
376   };
377 } // end of anonymous namespace
378
379 // Include the auto-generated portion of the assembly writer
380 #include "PPCGenAsmWriter.inc"
381
382 void PPCAsmPrinter::printOp(const MachineOperand &MO, raw_ostream &O) {
383   switch (MO.getType()) {
384   case MachineOperand::MO_Immediate:
385     llvm_unreachable("printOp() does not handle immediate values");
386
387   case MachineOperand::MO_MachineBasicBlock:
388     O << *MO.getMBB()->getSymbol();
389     return;
390   case MachineOperand::MO_JumpTableIndex:
391     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
392       << '_' << MO.getIndex();
393     // FIXME: PIC relocation model
394     return;
395   case MachineOperand::MO_ConstantPoolIndex:
396     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
397       << '_' << MO.getIndex();
398     return;
399   case MachineOperand::MO_BlockAddress:
400     O << *GetBlockAddressSymbol(MO.getBlockAddress());
401     return;
402   case MachineOperand::MO_ExternalSymbol: {
403     // Computing the address of an external symbol, not calling it.
404     if (TM.getRelocationModel() == Reloc::Static) {
405       O << *GetExternalSymbolSymbol(MO.getSymbolName());
406       return;
407     }
408
409     MCSymbol *NLPSym = 
410       OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
411                                    MO.getSymbolName()+"$non_lazy_ptr");
412     MachineModuleInfoImpl::StubValueTy &StubSym = 
413       MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(NLPSym);
414     if (StubSym.getPointer() == 0)
415       StubSym = MachineModuleInfoImpl::
416         StubValueTy(GetExternalSymbolSymbol(MO.getSymbolName()), true);
417     
418     O << *NLPSym;
419     return;
420   }
421   case MachineOperand::MO_GlobalAddress: {
422     // Computing the address of a global symbol, not calling it.
423     GlobalValue *GV = MO.getGlobal();
424     MCSymbol *SymToPrint;
425
426     // External or weakly linked global variables need non-lazily-resolved stubs
427     if (TM.getRelocationModel() != Reloc::Static &&
428         (GV->isDeclaration() || GV->isWeakForLinker())) {
429       if (!GV->hasHiddenVisibility()) {
430         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
431         MachineModuleInfoImpl::StubValueTy &StubSym = 
432           MMI->getObjFileInfo<MachineModuleInfoMachO>()
433             .getGVStubEntry(SymToPrint);
434         if (StubSym.getPointer() == 0)
435           StubSym = MachineModuleInfoImpl::
436             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
437       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
438                  GV->hasAvailableExternallyLinkage()) {
439         SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
440         
441         MachineModuleInfoImpl::StubValueTy &StubSym = 
442           MMI->getObjFileInfo<MachineModuleInfoMachO>().
443                     getHiddenGVStubEntry(SymToPrint);
444         if (StubSym.getPointer() == 0)
445           StubSym = MachineModuleInfoImpl::
446             StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
447       } else {
448         SymToPrint = Mang->getSymbol(GV);
449       }
450     } else {
451       SymToPrint = Mang->getSymbol(GV);
452     }
453     
454     O << *SymToPrint;
455
456     printOffset(MO.getOffset(), O);
457     return;
458   }
459
460   default:
461     O << "<unknown operand type: " << MO.getType() << ">";
462     return;
463   }
464 }
465
466 /// PrintAsmOperand - Print out an operand for an inline asm expression.
467 ///
468 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
469                                     unsigned AsmVariant,
470                                     const char *ExtraCode, raw_ostream &O) {
471   // Does this asm operand have a single letter operand modifier?
472   if (ExtraCode && ExtraCode[0]) {
473     if (ExtraCode[1] != 0) return true; // Unknown modifier.
474
475     switch (ExtraCode[0]) {
476     default: return true;  // Unknown modifier.
477     case 'c': // Don't print "$" before a global var name or constant.
478       // PPC never has a prefix.
479       printOperand(MI, OpNo, O);
480       return false;
481     case 'L': // Write second word of DImode reference.
482       // Verify that this operand has two consecutive registers.
483       if (!MI->getOperand(OpNo).isReg() ||
484           OpNo+1 == MI->getNumOperands() ||
485           !MI->getOperand(OpNo+1).isReg())
486         return true;
487       ++OpNo;   // Return the high-part.
488       break;
489     case 'I':
490       // Write 'i' if an integer constant, otherwise nothing.  Used to print
491       // addi vs add, etc.
492       if (MI->getOperand(OpNo).isImm())
493         O << "i";
494       return false;
495     }
496   }
497
498   printOperand(MI, OpNo, O);
499   return false;
500 }
501
502 // At the moment, all inline asm memory operands are a single register.
503 // In any case, the output of this routine should always be just one
504 // assembler operand.
505
506 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
507                                           unsigned AsmVariant,
508                                           const char *ExtraCode,
509                                           raw_ostream &O) {
510   if (ExtraCode && ExtraCode[0])
511     return true; // Unknown modifier.
512   assert (MI->getOperand(OpNo).isReg());
513   O << "0(";
514   printOperand(MI, OpNo, O);
515   O << ")";
516   return false;
517 }
518
519 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
520                                           raw_ostream &O, const char *Modifier){
521   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
522   unsigned Code = MI->getOperand(OpNo).getImm();
523   if (!strcmp(Modifier, "cc")) {
524     switch ((PPC::Predicate)Code) {
525     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
526     case PPC::PRED_LT: O << "lt"; return;
527     case PPC::PRED_LE: O << "le"; return;
528     case PPC::PRED_EQ: O << "eq"; return;
529     case PPC::PRED_GE: O << "ge"; return;
530     case PPC::PRED_GT: O << "gt"; return;
531     case PPC::PRED_NE: O << "ne"; return;
532     case PPC::PRED_UN: O << "un"; return;
533     case PPC::PRED_NU: O << "nu"; return;
534     }
535
536   } else {
537     assert(!strcmp(Modifier, "reg") &&
538            "Need to specify 'cc' or 'reg' as predicate op modifier!");
539     // Don't print the register for 'always'.
540     if (Code == PPC::PRED_ALWAYS) return;
541     printOperand(MI, OpNo+1, O);
542   }
543 }
544
545
546 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
547 /// the current output stream.
548 ///
549 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
550   SmallString<128> Str;
551   raw_svector_ostream O(Str);
552
553   // Check for slwi/srwi mnemonics.
554   if (MI->getOpcode() == PPC::RLWINM) {
555     unsigned char SH = MI->getOperand(2).getImm();
556     unsigned char MB = MI->getOperand(3).getImm();
557     unsigned char ME = MI->getOperand(4).getImm();
558     bool useSubstituteMnemonic = false;
559     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
560       O << "\tslwi "; useSubstituteMnemonic = true;
561     }
562     if (SH <= 31 && MB == (32-SH) && ME == 31) {
563       O << "\tsrwi "; useSubstituteMnemonic = true;
564       SH = 32-SH;
565     }
566     if (useSubstituteMnemonic) {
567       printOperand(MI, 0, O);
568       O << ", ";
569       printOperand(MI, 1, O);
570       O << ", " << (unsigned int)SH;
571       OutStreamer.EmitRawText(O.str());
572       return;
573     }
574   }
575   
576   if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) &&
577       MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
578     O << "\tmr ";
579     printOperand(MI, 0, O);
580     O << ", ";
581     printOperand(MI, 1, O);
582     OutStreamer.EmitRawText(O.str());
583     return;
584   }
585   
586   if (MI->getOpcode() == PPC::RLDICR) {
587     unsigned char SH = MI->getOperand(2).getImm();
588     unsigned char ME = MI->getOperand(3).getImm();
589     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
590     if (63-SH == ME) {
591       O << "\tsldi ";
592       printOperand(MI, 0, O);
593       O << ", ";
594       printOperand(MI, 1, O);
595       O << ", " << (unsigned int)SH;
596       OutStreamer.EmitRawText(O.str());
597       return;
598     }
599   }
600
601   printInstruction(MI, O);
602   OutStreamer.EmitRawText(O.str());
603 }
604
605 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
606   if (!Subtarget.isPPC64())  // linux/ppc32 - Normal entry label.
607     return AsmPrinter::EmitFunctionEntryLabel();
608     
609   // Emit an official procedure descriptor.
610   // FIXME 64-bit SVR4: Use MCSection here!
611   OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
612   OutStreamer.EmitRawText(StringRef("\t.align 3"));
613   OutStreamer.EmitLabel(CurrentFnSym);
614   OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
615                           ",.TOC.@tocbase");
616   OutStreamer.EmitRawText(StringRef("\t.previous"));
617   OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
618 }
619
620
621 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
622   const TargetData *TD = TM.getTargetData();
623
624   bool isPPC64 = TD->getPointerSizeInBits() == 64;
625
626   if (isPPC64 && !TOC.empty()) {
627     // FIXME 64-bit SVR4: Use MCSection here?
628     OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
629
630     // FIXME: This is nondeterminstic!
631     for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
632          E = TOC.end(); I != E; ++I) {
633       OutStreamer.EmitLabel(I->second);
634       OutStreamer.EmitRawText("\t.tc " + Twine(I->first->getName()) +
635                               "[TC]," + I->first->getName());
636     }
637   }
638
639   return AsmPrinter::doFinalization(M);
640 }
641
642 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
643   static const char *const CPUDirectives[] = {
644     "",
645     "ppc",
646     "ppc601",
647     "ppc602",
648     "ppc603",
649     "ppc7400",
650     "ppc750",
651     "ppc970",
652     "ppc64"
653   };
654
655   unsigned Directive = Subtarget.getDarwinDirective();
656   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
657     Directive = PPC::DIR_970;
658   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
659     Directive = PPC::DIR_7400;
660   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
661     Directive = PPC::DIR_64;
662   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
663   OutStreamer.EmitRawText("\t.machine " + Twine(CPUDirectives[Directive]));
664
665   // Prime text sections so they are adjacent.  This reduces the likelihood a
666   // large data or debug section causes a branch to exceed 16M limit.
667   TargetLoweringObjectFileMachO &TLOFMacho = 
668     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
669   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
670   if (TM.getRelocationModel() == Reloc::PIC_) {
671     OutStreamer.SwitchSection(
672             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
673                                       MCSectionMachO::S_SYMBOL_STUBS |
674                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
675                                       32, SectionKind::getText()));
676   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
677     OutStreamer.SwitchSection(
678             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
679                                       MCSectionMachO::S_SYMBOL_STUBS |
680                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
681                                       16, SectionKind::getText()));
682   }
683   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
684 }
685
686 static MCSymbol *GetLazyPtr(MCSymbol *Sym, MCContext &Ctx) {
687   // Remove $stub suffix, add $lazy_ptr.
688   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end()-5);
689   TmpStr += "$lazy_ptr";
690   return Ctx.GetOrCreateSymbol(TmpStr.str());
691 }
692
693 static MCSymbol *GetAnonSym(MCSymbol *Sym, MCContext &Ctx) {
694   // Add $tmp suffix to $stub, yielding $stub$tmp.
695   SmallString<128> TmpStr(Sym->getName().begin(), Sym->getName().end());
696   TmpStr += "$tmp";
697   return Ctx.GetOrCreateSymbol(TmpStr.str());
698 }
699
700 void PPCDarwinAsmPrinter::
701 EmitFunctionStubs(const MachineModuleInfoMachO::SymbolListTy &Stubs) {
702   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
703   
704   TargetLoweringObjectFileMachO &TLOFMacho = 
705     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
706
707   // .lazy_symbol_pointer
708   const MCSection *LSPSection = TLOFMacho.getLazySymbolPointerSection();
709   
710   // Output stubs for dynamically-linked functions
711   if (TM.getRelocationModel() == Reloc::PIC_) {
712     const MCSection *StubSection = 
713     TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
714                               MCSectionMachO::S_SYMBOL_STUBS |
715                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
716                               32, SectionKind::getText());
717     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
718       OutStreamer.SwitchSection(StubSection);
719       EmitAlignment(4);
720       
721       MCSymbol *Stub = Stubs[i].first;
722       MCSymbol *RawSym = Stubs[i].second.getPointer();
723       MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
724       MCSymbol *AnonSymbol = GetAnonSym(Stub, OutContext);
725                                            
726       OutStreamer.EmitLabel(Stub);
727       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
728       // FIXME: MCize this.
729       OutStreamer.EmitRawText(StringRef("\tmflr r0"));
730       OutStreamer.EmitRawText("\tbcl 20,31," + Twine(AnonSymbol->getName()));
731       OutStreamer.EmitLabel(AnonSymbol);
732       OutStreamer.EmitRawText(StringRef("\tmflr r11"));
733       OutStreamer.EmitRawText("\taddis r11,r11,ha16("+Twine(LazyPtr->getName())+
734                               "-" + AnonSymbol->getName() + ")");
735       OutStreamer.EmitRawText(StringRef("\tmtlr r0"));
736       
737       if (isPPC64)
738         OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
739                                 "-" + AnonSymbol->getName() + ")(r11)");
740       else
741         OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
742                                 "-" + AnonSymbol->getName() + ")(r11)");
743       OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
744       OutStreamer.EmitRawText(StringRef("\tbctr"));
745       
746       OutStreamer.SwitchSection(LSPSection);
747       OutStreamer.EmitLabel(LazyPtr);
748       OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
749       
750       if (isPPC64)
751         OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
752       else
753         OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
754     }
755     OutStreamer.AddBlankLine();
756     return;
757   }
758   
759   const MCSection *StubSection =
760     TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
761                               MCSectionMachO::S_SYMBOL_STUBS |
762                               MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
763                               16, SectionKind::getText());
764   for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
765     MCSymbol *Stub = Stubs[i].first;
766     MCSymbol *RawSym = Stubs[i].second.getPointer();
767     MCSymbol *LazyPtr = GetLazyPtr(Stub, OutContext);
768
769     OutStreamer.SwitchSection(StubSection);
770     EmitAlignment(4);
771     OutStreamer.EmitLabel(Stub);
772     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
773     OutStreamer.EmitRawText("\tlis r11,ha16(" + Twine(LazyPtr->getName()) +")");
774     if (isPPC64)
775       OutStreamer.EmitRawText("\tldu r12,lo16(" + Twine(LazyPtr->getName()) +
776                               ")(r11)");
777     else
778       OutStreamer.EmitRawText("\tlwzu r12,lo16(" + Twine(LazyPtr->getName()) +
779                               ")(r11)");
780     OutStreamer.EmitRawText(StringRef("\tmtctr r12"));
781     OutStreamer.EmitRawText(StringRef("\tbctr"));
782     OutStreamer.SwitchSection(LSPSection);
783     OutStreamer.EmitLabel(LazyPtr);
784     OutStreamer.EmitSymbolAttribute(RawSym, MCSA_IndirectSymbol);
785     
786     if (isPPC64)
787       OutStreamer.EmitRawText(StringRef("\t.quad dyld_stub_binding_helper"));
788     else
789       OutStreamer.EmitRawText(StringRef("\t.long dyld_stub_binding_helper"));
790   }
791   
792   OutStreamer.AddBlankLine();
793 }
794
795
796 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
797   bool isPPC64 = TM.getTargetData()->getPointerSizeInBits() == 64;
798
799   // Darwin/PPC always uses mach-o.
800   TargetLoweringObjectFileMachO &TLOFMacho = 
801     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
802   MachineModuleInfoMachO &MMIMacho =
803     MMI->getObjFileInfo<MachineModuleInfoMachO>();
804   
805   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetFnStubList();
806   if (!Stubs.empty())
807     EmitFunctionStubs(Stubs);
808
809   if (MAI->doesSupportExceptionHandling() && MMI) {
810     // Add the (possibly multiple) personalities to the set of global values.
811     // Only referenced functions get into the Personalities list.
812     const std::vector<Function *> &Personalities = MMI->getPersonalities();
813     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
814          E = Personalities.end(); I != E; ++I) {
815       if (*I) {
816         MCSymbol *NLPSym = GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
817         MachineModuleInfoImpl::StubValueTy &StubSym =
818           MMIMacho.getGVStubEntry(NLPSym);
819         StubSym = MachineModuleInfoImpl::StubValueTy(Mang->getSymbol(*I), true);
820       }
821     }
822   }
823
824   // Output stubs for dynamically-linked functions.
825   Stubs = MMIMacho.GetGVStubList();
826   
827   // Output macho stubs for external and common global variables.
828   if (!Stubs.empty()) {
829     // Switch with ".non_lazy_symbol_pointer" directive.
830     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
831     EmitAlignment(isPPC64 ? 3 : 2);
832     
833     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
834       // L_foo$stub:
835       OutStreamer.EmitLabel(Stubs[i].first);
836       //   .indirect_symbol _foo
837       MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
838       OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
839
840       if (MCSym.getInt())
841         // External to current translation unit.
842         OutStreamer.EmitIntValue(0, isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
843       else
844         // Internal to current translation unit.
845         //
846         // When we place the LSDA into the TEXT section, the type info pointers
847         // need to be indirect and pc-rel. We accomplish this by using NLPs.
848         // However, sometimes the types are local to the file. So we need to
849         // fill in the value for the NLP in those cases.
850         OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
851                                                       OutContext),
852                               isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
853     }
854
855     Stubs.clear();
856     OutStreamer.AddBlankLine();
857   }
858
859   Stubs = MMIMacho.GetHiddenGVStubList();
860   if (!Stubs.empty()) {
861     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
862     EmitAlignment(isPPC64 ? 3 : 2);
863     
864     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
865       // L_foo$stub:
866       OutStreamer.EmitLabel(Stubs[i].first);
867       //   .long _foo
868       OutStreamer.EmitValue(MCSymbolRefExpr::
869                             Create(Stubs[i].second.getPointer(),
870                                    OutContext),
871                             isPPC64 ? 8 : 4/*size*/, 0/*addrspace*/);
872     }
873
874     Stubs.clear();
875     OutStreamer.AddBlankLine();
876   }
877
878   // Funny Darwin hack: This flag tells the linker that no global symbols
879   // contain code that falls through to other global symbols (e.g. the obvious
880   // implementation of multiple entry points).  If this doesn't occur, the
881   // linker can safely perform dead code stripping.  Since LLVM never generates
882   // code that does this, it is always safe to set.
883   OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
884
885   return AsmPrinter::doFinalization(M);
886 }
887
888 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
889 /// for a MachineFunction to the given output stream, in a format that the
890 /// Darwin assembler can deal with.
891 ///
892 static AsmPrinter *createPPCAsmPrinterPass(TargetMachine &tm,
893                                            MCStreamer &Streamer) {
894   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
895
896   if (Subtarget->isDarwin())
897     return new PPCDarwinAsmPrinter(tm, Streamer);
898   return new PPCLinuxAsmPrinter(tm, Streamer);
899 }
900
901 // Force static initialization.
902 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
903   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
904   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
905 }