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