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