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