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