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