eliminate some uses of Mangler::makeNameProper.
[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/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSectionMachO.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Support/Mangler.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/FormattedStream.h"
49 #include "llvm/ADT/Statistic.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 STATISTIC(EmittedInsts, "Number of machine instrs printed");
56
57 namespace {
58   class PPCAsmPrinter : public AsmPrinter {
59   protected:
60     struct FnStubInfo {
61       std::string Stub, LazyPtr, AnonSymbol;
62       
63       FnStubInfo() {}
64       
65       void Init(const GlobalValue *GV, Mangler *Mang) {
66         // Already initialized.
67         if (!Stub.empty()) return;
68         Stub = Mang->getMangledName(GV, "$stub", true);
69         LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
70         AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
71       }
72
73       void Init(StringRef GVName, Mangler *Mang) {
74         assert(!GVName.empty());
75         if (!Stub.empty()) return; // Already initialized.
76         // Get the names for the external symbol name.
77         SmallString<128> TmpStr;
78         Mang->getNameWithPrefix(TmpStr, GVName + "$stub", Mangler::Private);
79         Stub = TmpStr.str();
80         TmpStr.clear();
81         
82         Mang->getNameWithPrefix(TmpStr, GVName + "$lazy_ptr", Mangler::Private);
83         LazyPtr = TmpStr.str();
84         TmpStr.clear();
85         
86         Mang->getNameWithPrefix(TmpStr, GVName + "$stub$tmp", Mangler::Private);
87         AnonSymbol = TmpStr.str();
88       }
89     };
90     
91     StringMap<FnStubInfo> FnStubs;
92     StringMap<std::string> GVStubs, HiddenGVStubs, TOC;
93     const PPCSubtarget &Subtarget;
94     uint64_t LabelID;
95   public:
96     explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
97                            const MCAsmInfo *T, bool V)
98       : AsmPrinter(O, TM, T, V),
99         Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
100
101     virtual const char *getPassName() const {
102       return "PowerPC Assembly Printer";
103     }
104
105     PPCTargetMachine &getTM() {
106       return static_cast<PPCTargetMachine&>(TM);
107     }
108
109     unsigned enumRegToMachineReg(unsigned enumReg) {
110       switch (enumReg) {
111       default: llvm_unreachable("Unhandled register!");
112       case PPC::CR0:  return  0;
113       case PPC::CR1:  return  1;
114       case PPC::CR2:  return  2;
115       case PPC::CR3:  return  3;
116       case PPC::CR4:  return  4;
117       case PPC::CR5:  return  5;
118       case PPC::CR6:  return  6;
119       case PPC::CR7:  return  7;
120       }
121       llvm_unreachable(0);
122     }
123
124     /// printInstruction - This method is automatically generated by tablegen
125     /// from the instruction set description.  This method returns true if the
126     /// machine instruction was sufficiently described to print it, otherwise it
127     /// returns false.
128     void printInstruction(const MachineInstr *MI);
129     static const char *getRegisterName(unsigned RegNo);
130
131
132     void printMachineInstruction(const MachineInstr *MI);
133     void printOp(const MachineOperand &MO);
134
135     /// stripRegisterPrefix - This method strips the character prefix from a
136     /// register name so that only the number is left.  Used by for linux asm.
137     const char *stripRegisterPrefix(const char *RegName) {
138       switch (RegName[0]) {
139       case 'r':
140       case 'f':
141       case 'v': return RegName + 1;
142       case 'c': if (RegName[1] == 'r') return RegName + 2;
143       }
144
145       return RegName;
146     }
147
148     /// printRegister - Print register according to target requirements.
149     ///
150     void printRegister(const MachineOperand &MO, bool R0AsZero) {
151       unsigned RegNo = MO.getReg();
152       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
153
154       // If we should use 0 for R0.
155       if (R0AsZero && RegNo == PPC::R0) {
156         O << "0";
157         return;
158       }
159
160       const char *RegName = getRegisterName(RegNo);
161       // Linux assembler (Others?) does not take register mnemonics.
162       // FIXME - What about special registers used in mfspr/mtspr?
163       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
164       O << RegName;
165     }
166
167     void printOperand(const MachineInstr *MI, unsigned OpNo) {
168       const MachineOperand &MO = MI->getOperand(OpNo);
169       if (MO.isReg()) {
170         printRegister(MO, false);
171       } else if (MO.isImm()) {
172         O << MO.getImm();
173       } else {
174         printOp(MO);
175       }
176     }
177
178     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
179                          unsigned AsmVariant, const char *ExtraCode);
180     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
181                                unsigned AsmVariant, const char *ExtraCode);
182
183
184     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
185       char value = MI->getOperand(OpNo).getImm();
186       value = (value << (32-5)) >> (32-5);
187       O << (int)value;
188     }
189     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
190       unsigned char value = MI->getOperand(OpNo).getImm();
191       assert(value <= 31 && "Invalid u5imm argument!");
192       O << (unsigned int)value;
193     }
194     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
195       unsigned char value = MI->getOperand(OpNo).getImm();
196       assert(value <= 63 && "Invalid u6imm argument!");
197       O << (unsigned int)value;
198     }
199     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
200       O << (short)MI->getOperand(OpNo).getImm();
201     }
202     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
203       O << (unsigned short)MI->getOperand(OpNo).getImm();
204     }
205     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
206       if (MI->getOperand(OpNo).isImm()) {
207         O << (short)(MI->getOperand(OpNo).getImm()*4);
208       } else {
209         O << "lo16(";
210         printOp(MI->getOperand(OpNo));
211         if (TM.getRelocationModel() == Reloc::PIC_)
212           O << "-\"L" << getFunctionNumber() << "$pb\")";
213         else
214           O << ')';
215       }
216     }
217     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
218       // Branches can take an immediate operand.  This is used by the branch
219       // selection pass to print $+8, an eight byte displacement from the PC.
220       if (MI->getOperand(OpNo).isImm()) {
221         O << "$+" << MI->getOperand(OpNo).getImm()*4;
222       } else {
223         printOp(MI->getOperand(OpNo));
224       }
225     }
226     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
227       const MachineOperand &MO = MI->getOperand(OpNo);
228       if (TM.getRelocationModel() != Reloc::Static) {
229         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
230           GlobalValue *GV = MO.getGlobal();
231           if (GV->isDeclaration() || GV->isWeakForLinker()) {
232             // Dynamically-resolved functions need a stub for the function.
233             FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
234             FnInfo.Init(GV, Mang);
235             O << FnInfo.Stub;
236             return;
237           }
238         }
239         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
240           SmallString<128> MangledName;
241           Mang->getNameWithPrefix(MangledName, MO.getSymbolName());
242           FnStubInfo &FnInfo = FnStubs[MangledName.str()];
243           FnInfo.Init(MO.getSymbolName(), Mang);
244           O << FnInfo.Stub;
245           return;
246         }
247       }
248
249       printOp(MI->getOperand(OpNo));
250     }
251     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
252      O << (int)MI->getOperand(OpNo).getImm()*4;
253     }
254     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
255       O << "\"L" << getFunctionNumber() << "$pb\"\n";
256       O << "\"L" << getFunctionNumber() << "$pb\":";
257     }
258     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
259       if (MI->getOperand(OpNo).isImm()) {
260         printS16ImmOperand(MI, OpNo);
261       } else {
262         if (Subtarget.isDarwin()) O << "ha16(";
263         printOp(MI->getOperand(OpNo));
264         if (TM.getRelocationModel() == Reloc::PIC_)
265           O << "-\"L" << getFunctionNumber() << "$pb\"";
266         if (Subtarget.isDarwin())
267           O << ')';
268         else
269           O << "@ha";
270       }
271     }
272     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
273       if (MI->getOperand(OpNo).isImm()) {
274         printS16ImmOperand(MI, OpNo);
275       } else {
276         if (Subtarget.isDarwin()) O << "lo16(";
277         printOp(MI->getOperand(OpNo));
278         if (TM.getRelocationModel() == Reloc::PIC_)
279           O << "-\"L" << getFunctionNumber() << "$pb\"";
280         if (Subtarget.isDarwin())
281           O << ')';
282         else
283           O << "@l";
284       }
285     }
286     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
287       unsigned CCReg = MI->getOperand(OpNo).getReg();
288       unsigned RegNo = enumRegToMachineReg(CCReg);
289       O << (0x80 >> RegNo);
290     }
291     // The new addressing mode printers.
292     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
293       printSymbolLo(MI, OpNo);
294       O << '(';
295       if (MI->getOperand(OpNo+1).isReg() &&
296           MI->getOperand(OpNo+1).getReg() == PPC::R0)
297         O << "0";
298       else
299         printOperand(MI, OpNo+1);
300       O << ')';
301     }
302     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
303       if (MI->getOperand(OpNo).isImm())
304         printS16X4ImmOperand(MI, OpNo);
305       else
306         printSymbolLo(MI, OpNo);
307       O << '(';
308       if (MI->getOperand(OpNo+1).isReg() &&
309           MI->getOperand(OpNo+1).getReg() == PPC::R0)
310         O << "0";
311       else
312         printOperand(MI, OpNo+1);
313       O << ')';
314     }
315
316     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
317       // When used as the base register, r0 reads constant zero rather than
318       // the value contained in the register.  For this reason, the darwin
319       // assembler requires that we print r0 as 0 (no r) when used as the base.
320       const MachineOperand &MO = MI->getOperand(OpNo);
321       printRegister(MO, true);
322       O << ", ";
323       printOperand(MI, OpNo+1);
324     }
325
326     void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
327       const MachineOperand &MO = MI->getOperand(OpNo);
328
329       assert(MO.getType() == MachineOperand::MO_GlobalAddress);
330
331       GlobalValue *GV = MO.getGlobal();
332
333       std::string Name = Mang->getMangledName(GV);
334
335       // Map symbol -> label of TOC entry.
336       if (TOC.count(Name) == 0) {
337         std::string Label;
338         Label += MAI->getPrivateGlobalPrefix();
339         Label += "C";
340         Label += utostr(LabelID++);
341
342         TOC[Name] = Label;
343       }
344
345       O << TOC[Name] << "@toc";
346     }
347
348     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
349                                const char *Modifier);
350
351     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
352   };
353
354   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
355   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
356   public:
357     explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
358                                 const MCAsmInfo *T, bool V)
359       : PPCAsmPrinter(O, TM, T, V){}
360
361     virtual const char *getPassName() const {
362       return "Linux PPC Assembly Printer";
363     }
364
365     bool runOnMachineFunction(MachineFunction &F);
366     bool doFinalization(Module &M);
367
368     void getAnalysisUsage(AnalysisUsage &AU) const {
369       AU.setPreservesAll();
370       AU.addRequired<MachineModuleInfo>();
371       AU.addRequired<DwarfWriter>();
372       PPCAsmPrinter::getAnalysisUsage(AU);
373     }
374
375     void PrintGlobalVariable(const GlobalVariable *GVar);
376   };
377
378   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
379   /// OS X
380   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
381     formatted_raw_ostream &OS;
382   public:
383     explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
384                                  const MCAsmInfo *T, bool V)
385       : PPCAsmPrinter(O, TM, T, V), OS(O) {}
386
387     virtual const char *getPassName() const {
388       return "Darwin PPC Assembly Printer";
389     }
390
391     bool runOnMachineFunction(MachineFunction &F);
392     bool doFinalization(Module &M);
393     void EmitStartOfAsmFile(Module &M);
394
395     void getAnalysisUsage(AnalysisUsage &AU) const {
396       AU.setPreservesAll();
397       AU.addRequired<MachineModuleInfo>();
398       AU.addRequired<DwarfWriter>();
399       PPCAsmPrinter::getAnalysisUsage(AU);
400     }
401
402     void PrintGlobalVariable(const GlobalVariable *GVar);
403   };
404 } // end of anonymous namespace
405
406 // Include the auto-generated portion of the assembly writer
407 #include "PPCGenAsmWriter.inc"
408
409 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
410   switch (MO.getType()) {
411   case MachineOperand::MO_Immediate:
412     llvm_unreachable("printOp() does not handle immediate values");
413
414   case MachineOperand::MO_MachineBasicBlock:
415     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
416     return;
417   case MachineOperand::MO_JumpTableIndex:
418     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
419       << '_' << MO.getIndex();
420     // FIXME: PIC relocation model
421     return;
422   case MachineOperand::MO_ConstantPoolIndex:
423     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
424       << '_' << MO.getIndex();
425     return;
426   case MachineOperand::MO_BlockAddress:
427     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
428     return;
429   case MachineOperand::MO_ExternalSymbol: {
430     // Computing the address of an external symbol, not calling it.
431     std::string Name(MAI->getGlobalPrefix());
432     Name += MO.getSymbolName();
433     
434     if (TM.getRelocationModel() != Reloc::Static) {
435       GVStubs[Name] = Name+"$non_lazy_ptr";
436       Name += "$non_lazy_ptr";
437     }
438     O << Name;
439     return;
440   }
441   case MachineOperand::MO_GlobalAddress: {
442     // Computing the address of a global symbol, not calling it.
443     GlobalValue *GV = MO.getGlobal();
444     std::string Name;
445
446     // External or weakly linked global variables need non-lazily-resolved stubs
447     if (TM.getRelocationModel() != Reloc::Static &&
448         (GV->isDeclaration() || GV->isWeakForLinker())) {
449       if (!GV->hasHiddenVisibility()) {
450         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
451         GVStubs[Mang->getMangledName(GV)] = Name;
452       } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
453                  GV->hasAvailableExternallyLinkage()) {
454         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
455         HiddenGVStubs[Mang->getMangledName(GV)] = Name;
456       } else {
457         Name = Mang->getMangledName(GV);
458       }
459     } else {
460       Name = Mang->getMangledName(GV);
461     }
462     O << Name;
463
464     printOffset(MO.getOffset());
465     return;
466   }
467
468   default:
469     O << "<unknown operand type: " << MO.getType() << ">";
470     return;
471   }
472 }
473
474 /// PrintAsmOperand - Print out an operand for an inline asm expression.
475 ///
476 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
477                                     unsigned AsmVariant,
478                                     const char *ExtraCode) {
479   // Does this asm operand have a single letter operand modifier?
480   if (ExtraCode && ExtraCode[0]) {
481     if (ExtraCode[1] != 0) return true; // Unknown modifier.
482
483     switch (ExtraCode[0]) {
484     default: return true;  // Unknown modifier.
485     case 'c': // Don't print "$" before a global var name or constant.
486       // PPC never has a prefix.
487       printOperand(MI, OpNo);
488       return false;
489     case 'L': // Write second word of DImode reference.
490       // Verify that this operand has two consecutive registers.
491       if (!MI->getOperand(OpNo).isReg() ||
492           OpNo+1 == MI->getNumOperands() ||
493           !MI->getOperand(OpNo+1).isReg())
494         return true;
495       ++OpNo;   // Return the high-part.
496       break;
497     case 'I':
498       // Write 'i' if an integer constant, otherwise nothing.  Used to print
499       // addi vs add, etc.
500       if (MI->getOperand(OpNo).isImm())
501         O << "i";
502       return false;
503     }
504   }
505
506   printOperand(MI, OpNo);
507   return false;
508 }
509
510 // At the moment, all inline asm memory operands are a single register.
511 // In any case, the output of this routine should always be just one
512 // assembler operand.
513
514 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
515                                           unsigned AsmVariant,
516                                           const char *ExtraCode) {
517   if (ExtraCode && ExtraCode[0])
518     return true; // Unknown modifier.
519   assert (MI->getOperand(OpNo).isReg());
520   O << "0(";
521   printOperand(MI, OpNo);
522   O << ")";
523   return false;
524 }
525
526 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
527                                           const char *Modifier) {
528   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
529   unsigned Code = MI->getOperand(OpNo).getImm();
530   if (!strcmp(Modifier, "cc")) {
531     switch ((PPC::Predicate)Code) {
532     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
533     case PPC::PRED_LT: O << "lt"; return;
534     case PPC::PRED_LE: O << "le"; return;
535     case PPC::PRED_EQ: O << "eq"; return;
536     case PPC::PRED_GE: O << "ge"; return;
537     case PPC::PRED_GT: O << "gt"; return;
538     case PPC::PRED_NE: O << "ne"; return;
539     case PPC::PRED_UN: O << "un"; return;
540     case PPC::PRED_NU: O << "nu"; return;
541     }
542
543   } else {
544     assert(!strcmp(Modifier, "reg") &&
545            "Need to specify 'cc' or 'reg' as predicate op modifier!");
546     // Don't print the register for 'always'.
547     if (Code == PPC::PRED_ALWAYS) return;
548     printOperand(MI, OpNo+1);
549   }
550 }
551
552
553 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
554 /// the current output stream.
555 ///
556 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
557   ++EmittedInsts;
558   
559   processDebugLoc(MI, true);
560
561   // Check for slwi/srwi mnemonics.
562   bool useSubstituteMnemonic = false;
563   if (MI->getOpcode() == PPC::RLWINM) {
564     unsigned char SH = MI->getOperand(2).getImm();
565     unsigned char MB = MI->getOperand(3).getImm();
566     unsigned char ME = MI->getOperand(4).getImm();
567     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
568       O << "\tslwi "; useSubstituteMnemonic = true;
569     }
570     if (SH <= 31 && MB == (32-SH) && ME == 31) {
571       O << "\tsrwi "; useSubstituteMnemonic = true;
572       SH = 32-SH;
573     }
574     if (useSubstituteMnemonic) {
575       printOperand(MI, 0);
576       O << ", ";
577       printOperand(MI, 1);
578       O << ", " << (unsigned int)SH;
579     }
580   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
581     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
582       useSubstituteMnemonic = true;
583       O << "\tmr ";
584       printOperand(MI, 0);
585       O << ", ";
586       printOperand(MI, 1);
587     }
588   } else if (MI->getOpcode() == PPC::RLDICR) {
589     unsigned char SH = MI->getOperand(2).getImm();
590     unsigned char ME = MI->getOperand(3).getImm();
591     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
592     if (63-SH == ME) {
593       useSubstituteMnemonic = true;
594       O << "\tsldi ";
595       printOperand(MI, 0);
596       O << ", ";
597       printOperand(MI, 1);
598       O << ", " << (unsigned int)SH;
599     }
600   }
601
602   if (!useSubstituteMnemonic)
603     printInstruction(MI);
604
605   if (VerboseAsm)
606     EmitComments(*MI);
607   O << '\n';
608
609   processDebugLoc(MI, false);
610 }
611
612 /// runOnMachineFunction - This uses the printMachineInstruction()
613 /// method to print assembly for each instruction.
614 ///
615 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
616   this->MF = &MF;
617
618   SetupMachineFunction(MF);
619   O << "\n\n";
620
621   // Print out constants referenced by the function
622   EmitConstantPool(MF.getConstantPool());
623
624   // Print out labels for the function.
625   const Function *F = MF.getFunction();
626   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
627
628   switch (F->getLinkage()) {
629   default: llvm_unreachable("Unknown linkage type!");
630   case Function::PrivateLinkage:
631   case Function::InternalLinkage:  // Symbols default to internal.
632     break;
633   case Function::ExternalLinkage:
634     O << "\t.global\t" << CurrentFnName << '\n'
635       << "\t.type\t" << CurrentFnName << ", @function\n";
636     break;
637   case Function::LinkerPrivateLinkage:
638   case Function::WeakAnyLinkage:
639   case Function::WeakODRLinkage:
640   case Function::LinkOnceAnyLinkage:
641   case Function::LinkOnceODRLinkage:
642     O << "\t.global\t" << CurrentFnName << '\n';
643     O << "\t.weak\t" << CurrentFnName << '\n';
644     break;
645   }
646
647   printVisibility(CurrentFnName, F->getVisibility());
648
649   EmitAlignment(MF.getAlignment(), F);
650
651   if (Subtarget.isPPC64()) {
652     // Emit an official procedure descriptor.
653     // FIXME 64-bit SVR4: Use MCSection here?
654     O << "\t.section\t\".opd\",\"aw\"\n";
655     O << "\t.align 3\n";
656     O << CurrentFnName << ":\n";
657     O << "\t.quad .L." << CurrentFnName << ",.TOC.@tocbase\n";
658     O << "\t.previous\n";
659     O << ".L." << CurrentFnName << ":\n";
660   } else {
661     O << CurrentFnName << ":\n";
662   }
663
664   // Emit pre-function debug information.
665   DW->BeginFunction(&MF);
666
667   // Print out code for the function.
668   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
669        I != E; ++I) {
670     // Print a label for the basic block.
671     if (I != MF.begin()) {
672       EmitBasicBlockStart(I);
673     }
674     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
675          II != E; ++II) {
676       // Print the assembly for the instruction.
677       printMachineInstruction(II);
678     }
679   }
680
681   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
682
683   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
684
685   // Emit post-function debug information.
686   DW->EndFunction(&MF);
687
688   // Print out jump tables referenced by the function.
689   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
690
691   // We didn't modify anything.
692   return false;
693 }
694
695 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
696   const TargetData *TD = TM.getTargetData();
697
698   if (!GVar->hasInitializer())
699     return;   // External global require no code
700
701   // Check to see if this is a special global used by LLVM, if so, emit it.
702   if (EmitSpecialLLVMGlobal(GVar))
703     return;
704
705   std::string name = Mang->getMangledName(GVar);
706
707   printVisibility(name, GVar->getVisibility());
708
709   Constant *C = GVar->getInitializer();
710   const Type *Type = C->getType();
711   unsigned Size = TD->getTypeAllocSize(Type);
712   unsigned Align = TD->getPreferredAlignmentLog(GVar);
713
714   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
715                                                                   TM));
716
717   if (C->isNullValue() && /* FIXME: Verify correct */
718       !GVar->hasSection() &&
719       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
720        GVar->isWeakForLinker())) {
721       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
722
723       if (GVar->hasExternalLinkage()) {
724         O << "\t.global " << name << '\n';
725         O << "\t.type " << name << ", @object\n";
726         O << name << ":\n";
727         O << "\t.zero " << Size << '\n';
728       } else if (GVar->hasLocalLinkage()) {
729         O << MAI->getLCOMMDirective() << name << ',' << Size;
730       } else {
731         O << ".comm " << name << ',' << Size;
732       }
733       if (VerboseAsm) {
734         O << "\t\t" << MAI->getCommentString() << " '";
735         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
736         O << "'";
737       }
738       O << '\n';
739       return;
740   }
741
742   switch (GVar->getLinkage()) {
743    case GlobalValue::LinkOnceAnyLinkage:
744    case GlobalValue::LinkOnceODRLinkage:
745    case GlobalValue::WeakAnyLinkage:
746    case GlobalValue::WeakODRLinkage:
747    case GlobalValue::CommonLinkage:
748    case GlobalValue::LinkerPrivateLinkage:
749     O << "\t.global " << name << '\n'
750       << "\t.type " << name << ", @object\n"
751       << "\t.weak " << name << '\n';
752     break;
753    case GlobalValue::AppendingLinkage:
754     // FIXME: appending linkage variables should go into a section of
755     // their name or something.  For now, just emit them as external.
756    case GlobalValue::ExternalLinkage:
757     // If external or appending, declare as a global symbol
758     O << "\t.global " << name << '\n'
759       << "\t.type " << name << ", @object\n";
760     // FALL THROUGH
761    case GlobalValue::InternalLinkage:
762    case GlobalValue::PrivateLinkage:
763     break;
764    default:
765     llvm_unreachable("Unknown linkage type!");
766   }
767
768   EmitAlignment(Align, GVar);
769   O << name << ":";
770   if (VerboseAsm) {
771     O << "\t\t\t\t" << MAI->getCommentString() << " '";
772     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
773     O << "'";
774   }
775   O << '\n';
776
777   EmitGlobalConstant(C);
778   O << '\n';
779 }
780
781 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
782   const TargetData *TD = TM.getTargetData();
783
784   bool isPPC64 = TD->getPointerSizeInBits() == 64;
785
786   if (isPPC64 && !TOC.empty()) {
787     // FIXME 64-bit SVR4: Use MCSection here?
788     O << "\t.section\t\".toc\",\"aw\"\n";
789
790     for (StringMap<std::string>::iterator I = TOC.begin(), E = TOC.end();
791          I != E; ++I) {
792       O << I->second << ":\n";
793       O << "\t.tc " << I->getKeyData() << "[TC]," << I->getKeyData() << '\n';
794     }
795   }
796
797   return AsmPrinter::doFinalization(M);
798 }
799
800 /// runOnMachineFunction - This uses the printMachineInstruction()
801 /// method to print assembly for each instruction.
802 ///
803 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
804   this->MF = &MF;
805
806   SetupMachineFunction(MF);
807   O << "\n\n";
808
809   // Print out constants referenced by the function
810   EmitConstantPool(MF.getConstantPool());
811
812   // Print out labels for the function.
813   const Function *F = MF.getFunction();
814   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
815
816   switch (F->getLinkage()) {
817   default: llvm_unreachable("Unknown linkage type!");
818   case Function::PrivateLinkage:
819   case Function::InternalLinkage:  // Symbols default to internal.
820     break;
821   case Function::ExternalLinkage:
822     O << "\t.globl\t" << CurrentFnName << '\n';
823     break;
824   case Function::WeakAnyLinkage:
825   case Function::WeakODRLinkage:
826   case Function::LinkOnceAnyLinkage:
827   case Function::LinkOnceODRLinkage:
828   case Function::LinkerPrivateLinkage:
829     O << "\t.globl\t" << CurrentFnName << '\n';
830     O << "\t.weak_definition\t" << CurrentFnName << '\n';
831     break;
832   }
833
834   printVisibility(CurrentFnName, F->getVisibility());
835
836   EmitAlignment(MF.getAlignment(), F);
837   O << CurrentFnName << ":\n";
838
839   // Emit pre-function debug information.
840   DW->BeginFunction(&MF);
841
842   // If the function is empty, then we need to emit *something*. Otherwise, the
843   // function's label might be associated with something that it wasn't meant to
844   // be associated with. We emit a noop in this situation.
845   MachineFunction::iterator I = MF.begin();
846
847   if (++I == MF.end() && MF.front().empty())
848     O << "\tnop\n";
849
850   // Print out code for the function.
851   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
852        I != E; ++I) {
853     // Print a label for the basic block.
854     if (I != MF.begin()) {
855       EmitBasicBlockStart(I);
856     }
857     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
858          II != IE; ++II) {
859       // Print the assembly for the instruction.
860       printMachineInstruction(II);
861     }
862   }
863
864   // Emit post-function debug information.
865   DW->EndFunction(&MF);
866
867   // Print out jump tables referenced by the function.
868   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
869
870   // We didn't modify anything.
871   return false;
872 }
873
874
875 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
876   static const char *const CPUDirectives[] = {
877     "",
878     "ppc",
879     "ppc601",
880     "ppc602",
881     "ppc603",
882     "ppc7400",
883     "ppc750",
884     "ppc970",
885     "ppc64"
886   };
887
888   unsigned Directive = Subtarget.getDarwinDirective();
889   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
890     Directive = PPC::DIR_970;
891   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
892     Directive = PPC::DIR_7400;
893   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
894     Directive = PPC::DIR_64;
895   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
896   O << "\t.machine " << CPUDirectives[Directive] << '\n';
897
898   // Prime text sections so they are adjacent.  This reduces the likelihood a
899   // large data or debug section causes a branch to exceed 16M limit.
900   TargetLoweringObjectFileMachO &TLOFMacho = 
901     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
902   OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
903   if (TM.getRelocationModel() == Reloc::PIC_) {
904     OutStreamer.SwitchSection(
905             TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
906                                       MCSectionMachO::S_SYMBOL_STUBS |
907                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
908                                       32, SectionKind::getText()));
909   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
910     OutStreamer.SwitchSection(
911             TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
912                                       MCSectionMachO::S_SYMBOL_STUBS |
913                                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
914                                       16, SectionKind::getText()));
915   }
916   OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
917 }
918
919 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
920   const TargetData *TD = TM.getTargetData();
921
922   if (!GVar->hasInitializer())
923     return;   // External global require no code
924
925   // Check to see if this is a special global used by LLVM, if so, emit it.
926   if (EmitSpecialLLVMGlobal(GVar)) {
927     if (TM.getRelocationModel() == Reloc::Static) {
928       if (GVar->getName() == "llvm.global_ctors")
929         O << ".reference .constructors_used\n";
930       else if (GVar->getName() == "llvm.global_dtors")
931         O << ".reference .destructors_used\n";
932     }
933     return;
934   }
935
936   std::string name = Mang->getMangledName(GVar);
937   printVisibility(name, GVar->getVisibility());
938
939   Constant *C = GVar->getInitializer();
940   const Type *Type = C->getType();
941   unsigned Size = TD->getTypeAllocSize(Type);
942   unsigned Align = TD->getPreferredAlignmentLog(GVar);
943
944   const MCSection *TheSection =
945     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
946   OutStreamer.SwitchSection(TheSection);
947
948   /// FIXME: Drive this off the section!
949   if (C->isNullValue() && /* FIXME: Verify correct */
950       !GVar->hasSection() &&
951       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
952        GVar->isWeakForLinker()) &&
953       // Don't put things that should go in the cstring section into "comm".
954       !TheSection->getKind().isMergeableCString()) {
955     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
956
957     if (GVar->hasExternalLinkage()) {
958       O << "\t.globl " << name << '\n';
959       O << "\t.zerofill __DATA, __common, " << name << ", "
960         << Size << ", " << Align;
961     } else if (GVar->hasLocalLinkage()) {
962       O << MAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
963     } else if (!GVar->hasCommonLinkage()) {
964       O << "\t.globl " << name << '\n'
965         << MAI->getWeakDefDirective() << name << '\n';
966       EmitAlignment(Align, GVar);
967       O << name << ":";
968       if (VerboseAsm) {
969         O << "\t\t\t\t" << MAI->getCommentString() << " ";
970         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
971       }
972       O << '\n';
973       EmitGlobalConstant(C);
974       return;
975     } else {
976       O << ".comm " << name << ',' << Size;
977       // Darwin 9 and above support aligned common data.
978       if (Subtarget.isDarwin9())
979         O << ',' << Align;
980     }
981     if (VerboseAsm) {
982       O << "\t\t" << MAI->getCommentString() << " '";
983       WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
984       O << "'";
985     }
986     O << '\n';
987     return;
988   }
989
990   switch (GVar->getLinkage()) {
991    case GlobalValue::LinkOnceAnyLinkage:
992    case GlobalValue::LinkOnceODRLinkage:
993    case GlobalValue::WeakAnyLinkage:
994    case GlobalValue::WeakODRLinkage:
995    case GlobalValue::CommonLinkage:
996    case GlobalValue::LinkerPrivateLinkage:
997     O << "\t.globl " << name << '\n'
998       << "\t.weak_definition " << name << '\n';
999     break;
1000    case GlobalValue::AppendingLinkage:
1001     // FIXME: appending linkage variables should go into a section of
1002     // their name or something.  For now, just emit them as external.
1003    case GlobalValue::ExternalLinkage:
1004     // If external or appending, declare as a global symbol
1005     O << "\t.globl " << name << '\n';
1006     // FALL THROUGH
1007    case GlobalValue::InternalLinkage:
1008    case GlobalValue::PrivateLinkage:
1009     break;
1010    default:
1011     llvm_unreachable("Unknown linkage type!");
1012   }
1013
1014   EmitAlignment(Align, GVar);
1015   O << name << ":";
1016   if (VerboseAsm) {
1017     O << "\t\t\t\t" << MAI->getCommentString() << " '";
1018     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1019     O << "'";
1020   }
1021   O << '\n';
1022
1023   EmitGlobalConstant(C);
1024   O << '\n';
1025 }
1026
1027 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1028   const TargetData *TD = TM.getTargetData();
1029
1030   bool isPPC64 = TD->getPointerSizeInBits() == 64;
1031
1032   // Darwin/PPC always uses mach-o.
1033   TargetLoweringObjectFileMachO &TLOFMacho = 
1034     static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1035
1036   
1037   const MCSection *LSPSection = 0;
1038   if (!FnStubs.empty()) // .lazy_symbol_pointer
1039     LSPSection = TLOFMacho.getLazySymbolPointerSection();
1040     
1041   
1042   // Output stubs for dynamically-linked functions
1043   if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1044     const MCSection *StubSection = 
1045       TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1046                                 MCSectionMachO::S_SYMBOL_STUBS |
1047                                 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1048                                 32, SectionKind::getText());
1049      for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1050          I != E; ++I) {
1051       OutStreamer.SwitchSection(StubSection);
1052       EmitAlignment(4);
1053       const FnStubInfo &Info = I->second;
1054       O << Info.Stub << ":\n";
1055       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1056       O << "\tmflr r0\n";
1057       O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1058       O << Info.AnonSymbol << ":\n";
1059       O << "\tmflr r11\n";
1060       O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1061       O << ")\n";
1062       O << "\tmtlr r0\n";
1063       O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1064       O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1065       O << "\tmtctr r12\n";
1066       O << "\tbctr\n";
1067       
1068       OutStreamer.SwitchSection(LSPSection);
1069       O << Info.LazyPtr << ":\n";
1070       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1071       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1072     }
1073   } else if (!FnStubs.empty()) {
1074     const MCSection *StubSection =
1075       TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1076                                 MCSectionMachO::S_SYMBOL_STUBS |
1077                                 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1078                                 16, SectionKind::getText());
1079     
1080     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1081          I != E; ++I) {
1082       OutStreamer.SwitchSection(StubSection);
1083       EmitAlignment(4);
1084       const FnStubInfo &Info = I->second;
1085       O << Info.Stub << ":\n";
1086       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1087       O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1088       O << (isPPC64 ? "\tldu" :  "\tlwzu") << " r12,lo16(";
1089       O << Info.LazyPtr << ")(r11)\n";
1090       O << "\tmtctr r12\n";
1091       O << "\tbctr\n";
1092       OutStreamer.SwitchSection(LSPSection);
1093       O << Info.LazyPtr << ":\n";
1094       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1095       O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1096     }
1097   }
1098
1099   O << '\n';
1100
1101   if (MAI->doesSupportExceptionHandling() && MMI) {
1102     // Add the (possibly multiple) personalities to the set of global values.
1103     // Only referenced functions get into the Personalities list.
1104     const std::vector<Function *> &Personalities = MMI->getPersonalities();
1105     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1106          E = Personalities.end(); I != E; ++I) {
1107       if (*I)
1108         GVStubs[Mang->getMangledName(*I)] =
1109           Mang->getMangledName(*I, "$non_lazy_ptr", true);
1110     }
1111   }
1112
1113   // Output macho stubs for external and common global variables.
1114   if (!GVStubs.empty()) {
1115     // Switch with ".non_lazy_symbol_pointer" directive.
1116     OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1117     EmitAlignment(isPPC64 ? 3 : 2);
1118     
1119     for (StringMap<std::string>::iterator I = GVStubs.begin(),
1120          E = GVStubs.end(); I != E; ++I) {
1121       O << I->second << ":\n";
1122       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1123       O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1124     }
1125   }
1126
1127   if (!HiddenGVStubs.empty()) {
1128     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1129     EmitAlignment(isPPC64 ? 3 : 2);
1130     for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1131          E = HiddenGVStubs.end(); I != E; ++I) {
1132       O << I->second << ":\n";
1133       O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1134     }
1135   }
1136
1137   // Funny Darwin hack: This flag tells the linker that no global symbols
1138   // contain code that falls through to other global symbols (e.g. the obvious
1139   // implementation of multiple entry points).  If this doesn't occur, the
1140   // linker can safely perform dead code stripping.  Since LLVM never generates
1141   // code that does this, it is always safe to set.
1142   OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1143
1144   return AsmPrinter::doFinalization(M);
1145 }
1146
1147
1148
1149 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1150 /// for a MachineFunction to the given output stream, in a format that the
1151 /// Darwin assembler can deal with.
1152 ///
1153 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1154                                            TargetMachine &tm,
1155                                            const MCAsmInfo *tai,
1156                                            bool verbose) {
1157   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1158
1159   if (Subtarget->isDarwin())
1160     return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1161   return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1162 }
1163
1164 // Force static initialization.
1165 extern "C" void LLVMInitializePowerPCAsmPrinter() { 
1166   TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1167   TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);
1168 }