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