Add newline at end of file.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/MachineDebugInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/MRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <iostream>
45 #include <set>
46 using namespace llvm;
47
48 namespace {
49   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
50
51   struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
52     std::set<std::string> FnStubs, GVStubs;
53     const PPCSubtarget &Subtarget;
54     
55     PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
56       : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
57     }
58
59     virtual const char *getPassName() const {
60       return "PowerPC Assembly Printer";
61     }
62
63     PPCTargetMachine &getTM() {
64       return static_cast<PPCTargetMachine&>(TM);
65     }
66
67     unsigned enumRegToMachineReg(unsigned enumReg) {
68       switch (enumReg) {
69       default: assert(0 && "Unhandled register!"); break;
70       case PPC::CR0:  return  0;
71       case PPC::CR1:  return  1;
72       case PPC::CR2:  return  2;
73       case PPC::CR3:  return  3;
74       case PPC::CR4:  return  4;
75       case PPC::CR5:  return  5;
76       case PPC::CR6:  return  6;
77       case PPC::CR7:  return  7;
78       }
79       abort();
80     }
81
82     /// printInstruction - This method is automatically generated by tablegen
83     /// from the instruction set description.  This method returns true if the
84     /// machine instruction was sufficiently described to print it, otherwise it
85     /// returns false.
86     bool printInstruction(const MachineInstr *MI);
87
88     void printMachineInstruction(const MachineInstr *MI);
89     void printOp(const MachineOperand &MO);
90
91     void printOperand(const MachineInstr *MI, unsigned OpNo) {
92       const MachineOperand &MO = MI->getOperand(OpNo);
93       if (MO.isRegister()) {
94         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
95         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
96       } else if (MO.isImmediate()) {
97         O << MO.getImmedValue();
98       } else {
99         printOp(MO);
100       }
101     }
102     
103     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
104                          unsigned AsmVariant, const char *ExtraCode);
105     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
106                                unsigned AsmVariant, const char *ExtraCode);
107     
108     
109     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
110       char value = MI->getOperand(OpNo).getImmedValue();
111       value = (value << (32-5)) >> (32-5);
112       O << (int)value;
113     }
114     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
115       unsigned char value = MI->getOperand(OpNo).getImmedValue();
116       assert(value <= 31 && "Invalid u5imm argument!");
117       O << (unsigned int)value;
118     }
119     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
120       unsigned char value = MI->getOperand(OpNo).getImmedValue();
121       assert(value <= 63 && "Invalid u6imm argument!");
122       O << (unsigned int)value;
123     }
124     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
125       O << (short)MI->getOperand(OpNo).getImmedValue();
126     }
127     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
128       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
129     }
130     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
131       if (MI->getOperand(OpNo).isImmediate()) {
132         O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
133       } else {
134         O << "lo16(";
135         printOp(MI->getOperand(OpNo));
136         if (TM.getRelocationModel() == Reloc::PIC_)
137           O << "-\"L" << getFunctionNumber() << "$pb\")";
138         else
139           O << ')';
140       }
141     }
142     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
143       // Branches can take an immediate operand.  This is used by the branch
144       // selection pass to print $+8, an eight byte displacement from the PC.
145       if (MI->getOperand(OpNo).isImmediate()) {
146         O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
147       } else {
148         printOp(MI->getOperand(OpNo));
149       }
150     }
151     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
152       const MachineOperand &MO = MI->getOperand(OpNo);
153       if (TM.getRelocationModel() != Reloc::Static) {
154         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
155           GlobalValue *GV = MO.getGlobal();
156           if (((GV->isExternal() || GV->hasWeakLinkage() ||
157                 GV->hasLinkOnceLinkage()))) {
158             // Dynamically-resolved functions need a stub for the function.
159             std::string Name = Mang->getValueName(GV);
160             FnStubs.insert(Name);
161             O << "L" << Name << "$stub";
162             return;
163           }
164         }
165         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
166           std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
167           FnStubs.insert(Name);
168           O << "L" << Name << "$stub";
169           return;
170         }
171       }
172       
173       printOp(MI->getOperand(OpNo));
174     }
175     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
176      O << (int)MI->getOperand(OpNo).getImmedValue()*4;
177     }
178     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
179       O << "\"L" << getFunctionNumber() << "$pb\"\n";
180       O << "\"L" << getFunctionNumber() << "$pb\":";
181     }
182     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
183       if (MI->getOperand(OpNo).isImmediate()) {
184         printS16ImmOperand(MI, OpNo);
185       } else {
186         O << "ha16(";
187         printOp(MI->getOperand(OpNo));
188         if (TM.getRelocationModel() == Reloc::PIC_)
189           O << "-\"L" << getFunctionNumber() << "$pb\")";
190         else
191           O << ')';
192       }
193     }
194     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
195       if (MI->getOperand(OpNo).isImmediate()) {
196         printS16ImmOperand(MI, OpNo);
197       } else {
198         O << "lo16(";
199         printOp(MI->getOperand(OpNo));
200         if (TM.getRelocationModel() == Reloc::PIC_)
201           O << "-\"L" << getFunctionNumber() << "$pb\")";
202         else
203           O << ')';
204       }
205     }
206     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
207       unsigned CCReg = MI->getOperand(OpNo).getReg();
208       unsigned RegNo = enumRegToMachineReg(CCReg);
209       O << (0x80 >> RegNo);
210     }
211     // The new addressing mode printers.
212     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
213       printSymbolLo(MI, OpNo);
214       O << '(';
215       if (MI->getOperand(OpNo+1).isRegister() && 
216           MI->getOperand(OpNo+1).getReg() == PPC::R0)
217         O << "0";
218       else
219         printOperand(MI, OpNo+1);
220       O << ')';
221     }
222     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
223       if (MI->getOperand(OpNo).isImmediate())
224         printS16X4ImmOperand(MI, OpNo);
225       else 
226         printSymbolLo(MI, OpNo);
227       O << '(';
228       if (MI->getOperand(OpNo+1).isRegister() && 
229           MI->getOperand(OpNo+1).getReg() == PPC::R0)
230         O << "0";
231       else
232         printOperand(MI, OpNo+1);
233       O << ')';
234     }
235     
236     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
237       // When used as the base register, r0 reads constant zero rather than
238       // the value contained in the register.  For this reason, the darwin
239       // assembler requires that we print r0 as 0 (no r) when used as the base.
240       const MachineOperand &MO = MI->getOperand(OpNo);
241       if (MO.getReg() == PPC::R0)
242         O << '0';
243       else
244         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
245       O << ", ";
246       printOperand(MI, OpNo+1);
247     }
248     
249     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
250                                const char *Modifier);
251     
252     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
253     virtual bool doFinalization(Module &M) = 0;
254   };
255
256   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
257   /// X
258   struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
259   
260     DwarfWriter DW;
261
262     DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
263                      const TargetAsmInfo *T)
264       : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
265     }
266
267     virtual const char *getPassName() const {
268       return "Darwin PPC Assembly Printer";
269     }
270     
271     bool runOnMachineFunction(MachineFunction &F);
272     bool doInitialization(Module &M);
273     bool doFinalization(Module &M);
274     
275     void getAnalysisUsage(AnalysisUsage &AU) const {
276       AU.setPreservesAll();
277       AU.addRequired<MachineDebugInfo>();
278       PPCAsmPrinter::getAnalysisUsage(AU);
279     }
280
281     /// getSectionForFunction - Return the section that we should emit the
282     /// specified function body into.
283     virtual std::string getSectionForFunction(const Function &F) const;
284   };
285 } // end of anonymous namespace
286
287 // Include the auto-generated portion of the assembly writer
288 #include "PPCGenAsmWriter.inc"
289
290 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
291   switch (MO.getType()) {
292   case MachineOperand::MO_Immediate:
293     std::cerr << "printOp() does not handle immediate values\n";
294     abort();
295     return;
296
297   case MachineOperand::MO_MachineBasicBlock:
298     printBasicBlockLabel(MO.getMachineBasicBlock());
299     return;
300   case MachineOperand::MO_JumpTableIndex:
301     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
302       << '_' << MO.getJumpTableIndex();
303     // FIXME: PIC relocation model
304     return;
305   case MachineOperand::MO_ConstantPoolIndex:
306     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
307       << '_' << MO.getConstantPoolIndex();
308     return;
309   case MachineOperand::MO_ExternalSymbol:
310     // Computing the address of an external symbol, not calling it.
311     if (TM.getRelocationModel() != Reloc::Static) {
312       std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
313       GVStubs.insert(Name);
314       O << "L" << Name << "$non_lazy_ptr";
315       return;
316     }
317     O << TAI->getGlobalPrefix() << MO.getSymbolName();
318     return;
319   case MachineOperand::MO_GlobalAddress: {
320     // Computing the address of a global symbol, not calling it.
321     GlobalValue *GV = MO.getGlobal();
322     std::string Name = Mang->getValueName(GV);
323
324     // External or weakly linked global variables need non-lazily-resolved stubs
325     if (TM.getRelocationModel() != Reloc::Static) {
326       if (((GV->isExternal() || GV->hasWeakLinkage() ||
327             GV->hasLinkOnceLinkage()))) {
328         GVStubs.insert(Name);
329         O << "L" << Name << "$non_lazy_ptr";
330         return;
331       }
332     }
333
334     O << Name;
335     return;
336   }
337
338   default:
339     O << "<unknown operand type: " << MO.getType() << ">";
340     return;
341   }
342 }
343
344 /// PrintAsmOperand - Print out an operand for an inline asm expression.
345 ///
346 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
347                                     unsigned AsmVariant, 
348                                     const char *ExtraCode) {
349   // Does this asm operand have a single letter operand modifier?
350   if (ExtraCode && ExtraCode[0]) {
351     if (ExtraCode[1] != 0) return true; // Unknown modifier.
352     
353     switch (ExtraCode[0]) {
354     default: return true;  // Unknown modifier.
355     case 'L': // Write second word of DImode reference.  
356       // Verify that this operand has two consecutive registers.
357       if (!MI->getOperand(OpNo).isRegister() ||
358           OpNo+1 == MI->getNumOperands() ||
359           !MI->getOperand(OpNo+1).isRegister())
360         return true;
361       ++OpNo;   // Return the high-part.
362       break;
363     }
364   }
365   
366   printOperand(MI, OpNo);
367   return false;
368 }
369
370 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
371                                           unsigned AsmVariant, 
372                                           const char *ExtraCode) {
373   if (ExtraCode && ExtraCode[0])
374     return true; // Unknown modifier.
375   printMemRegReg(MI, OpNo);
376   return false;
377 }
378
379 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
380                                           const char *Modifier) {
381   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
382   unsigned Code = MI->getOperand(OpNo).getImm();
383   if (!strcmp(Modifier, "cc")) {
384     switch ((PPC::Predicate)Code) {
385     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
386     case PPC::PRED_LT: O << "lt"; return;
387     case PPC::PRED_LE: O << "le"; return;
388     case PPC::PRED_EQ: O << "eq"; return;
389     case PPC::PRED_GE: O << "ge"; return;
390     case PPC::PRED_GT: O << "gt"; return;
391     case PPC::PRED_NE: O << "ne"; return;
392     case PPC::PRED_UN: O << "un"; return;
393     case PPC::PRED_NU: O << "nu"; return;
394     }
395       
396   } else {
397     assert(!strcmp(Modifier, "reg") &&
398            "Need to specify 'cc' or 'reg' as predicate op modifier!");
399     // Don't print the register for 'always'.
400     if (Code == PPC::PRED_ALWAYS) return;
401     printOperand(MI, OpNo+1);
402   }
403 }
404
405
406 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
407 /// the current output stream.
408 ///
409 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
410   ++EmittedInsts;
411
412   // Check for slwi/srwi mnemonics.
413   if (MI->getOpcode() == PPC::RLWINM) {
414     bool FoundMnemonic = false;
415     unsigned char SH = MI->getOperand(2).getImmedValue();
416     unsigned char MB = MI->getOperand(3).getImmedValue();
417     unsigned char ME = MI->getOperand(4).getImmedValue();
418     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
419       O << "slwi "; FoundMnemonic = true;
420     }
421     if (SH <= 31 && MB == (32-SH) && ME == 31) {
422       O << "srwi "; FoundMnemonic = true;
423       SH = 32-SH;
424     }
425     if (FoundMnemonic) {
426       printOperand(MI, 0);
427       O << ", ";
428       printOperand(MI, 1);
429       O << ", " << (unsigned int)SH << "\n";
430       return;
431     }
432   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
433     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
434       O << "mr ";
435       printOperand(MI, 0);
436       O << ", ";
437       printOperand(MI, 1);
438       O << "\n";
439       return;
440     }
441   } else if (MI->getOpcode() == PPC::RLDICR) {
442     unsigned char SH = MI->getOperand(2).getImmedValue();
443     unsigned char ME = MI->getOperand(3).getImmedValue();
444     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
445     if (63-SH == ME) {
446       O << "sldi ";
447       printOperand(MI, 0);
448       O << ", ";
449       printOperand(MI, 1);
450       O << ", " << (unsigned int)SH << "\n";
451       return;
452     }
453   }
454
455   if (printInstruction(MI))
456     return; // Printer was automatically generated
457
458   assert(0 && "Unhandled instruction in asm writer!");
459   abort();
460   return;
461 }
462
463
464
465 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
466   switch (F.getLinkage()) {
467   default: assert(0 && "Unknown linkage type!");
468   case Function::ExternalLinkage:
469   case Function::InternalLinkage: return TAI->getTextSection();
470   case Function::WeakLinkage:
471   case Function::LinkOnceLinkage:
472     return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
473   }
474 }
475
476 /// runOnMachineFunction - This uses the printMachineInstruction()
477 /// method to print assembly for each instruction.
478 ///
479 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
480   DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
481
482   SetupMachineFunction(MF);
483   O << "\n\n";
484   
485   // Print out constants referenced by the function
486   EmitConstantPool(MF.getConstantPool());
487
488   // Print out labels for the function.
489   const Function *F = MF.getFunction();
490   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
491   
492   switch (F->getLinkage()) {
493   default: assert(0 && "Unknown linkage type!");
494   case Function::InternalLinkage:  // Symbols default to internal.
495     break;
496   case Function::ExternalLinkage:
497     O << "\t.globl\t" << CurrentFnName << "\n";
498     break;
499   case Function::WeakLinkage:
500   case Function::LinkOnceLinkage:
501     O << "\t.globl\t" << CurrentFnName << "\n";
502     O << "\t.weak_definition\t" << CurrentFnName << "\n";
503     break;
504   }
505   EmitAlignment(4, F);
506   O << CurrentFnName << ":\n";
507
508   // Emit pre-function debug information.
509   DW.BeginFunction(&MF);
510
511   // Print out code for the function.
512   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
513        I != E; ++I) {
514     // Print a label for the basic block.
515     if (I != MF.begin()) {
516       printBasicBlockLabel(I, true);
517       O << '\n';
518     }
519     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
520          II != E; ++II) {
521       // Print the assembly for the instruction.
522       O << "\t";
523       printMachineInstruction(II);
524     }
525   }
526
527   // Print out jump tables referenced by the function.
528   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
529   
530   // Emit post-function debug information.
531   DW.EndFunction();
532   
533   // We didn't modify anything.
534   return false;
535 }
536
537
538 bool DarwinAsmPrinter::doInitialization(Module &M) {
539   if (Subtarget.isGigaProcessor())
540     O << "\t.machine ppc970\n";
541   AsmPrinter::doInitialization(M);
542   
543   // Darwin wants symbols to be quoted if they have complex names.
544   Mang->setUseQuotes(true);
545   
546   // Emit initial debug information.
547   DW.BeginModule(&M);
548   return false;
549 }
550
551 bool DarwinAsmPrinter::doFinalization(Module &M) {
552   const TargetData *TD = TM.getTargetData();
553
554   // Print out module-level global variables here.
555   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
556        I != E; ++I) {
557     if (!I->hasInitializer()) continue;   // External global require no code
558     
559     // Check to see if this is a special global used by LLVM, if so, emit it.
560     if (EmitSpecialLLVMGlobal(I))
561       continue;
562     
563     std::string name = Mang->getValueName(I);
564     Constant *C = I->getInitializer();
565     unsigned Size = TD->getTypeSize(C->getType());
566     unsigned Align = TD->getPreferredAlignmentLog(I);
567
568     if (C->isNullValue() && /* FIXME: Verify correct */
569         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
570          I->hasLinkOnceLinkage() ||
571          (I->hasExternalLinkage() && !I->hasSection()))) {
572       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
573       if (I->hasExternalLinkage()) {
574         O << "\t.globl " << name << '\n';
575         O << "\t.zerofill __DATA, __common, " << name << ", "
576           << Size << ", " << Align;
577       } else if (I->hasInternalLinkage()) {
578         SwitchToDataSection("\t.data", I);
579         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
580       } else {
581         SwitchToDataSection("\t.data", I);
582         O << ".comm " << name << "," << Size;
583       }
584       O << "\t\t; '" << I->getName() << "'\n";
585     } else {
586       switch (I->getLinkage()) {
587       case GlobalValue::LinkOnceLinkage:
588       case GlobalValue::WeakLinkage:
589         O << "\t.globl " << name << '\n'
590           << "\t.weak_definition " << name << '\n';
591         SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
592         break;
593       case GlobalValue::AppendingLinkage:
594         // FIXME: appending linkage variables should go into a section of
595         // their name or something.  For now, just emit them as external.
596       case GlobalValue::ExternalLinkage:
597         // If external or appending, declare as a global symbol
598         O << "\t.globl " << name << "\n";
599         // FALL THROUGH
600       case GlobalValue::InternalLinkage:
601         if (I->isConstant()) {
602           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
603           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
604             SwitchToDataSection(TAI->getCStringSection(), I);
605             break;
606           }
607         }
608
609         SwitchToDataSection("\t.data", I);
610         break;
611       default:
612         std::cerr << "Unknown linkage type!";
613         abort();
614       }
615
616       EmitAlignment(Align, I);
617       O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
618       EmitGlobalConstant(C);
619       O << '\n';
620     }
621   }
622
623   bool isPPC64 = TD->getPointerSizeInBits() == 64;
624
625   // Output stubs for dynamically-linked functions
626   if (TM.getRelocationModel() == Reloc::PIC_) {
627     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
628          i != e; ++i) {
629       SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
630                           "pure_instructions,32");
631       EmitAlignment(4);
632       O << "L" << *i << "$stub:\n";
633       O << "\t.indirect_symbol " << *i << "\n";
634       O << "\tmflr r0\n";
635       O << "\tbcl 20,31,L0$" << *i << "\n";
636       O << "L0$" << *i << ":\n";
637       O << "\tmflr r11\n";
638       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
639       O << "\tmtlr r0\n";
640       if (isPPC64)
641         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
642       else
643         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
644       O << "\tmtctr r12\n";
645       O << "\tbctr\n";
646       SwitchToDataSection(".lazy_symbol_pointer");
647       O << "L" << *i << "$lazy_ptr:\n";
648       O << "\t.indirect_symbol " << *i << "\n";
649       if (isPPC64)
650         O << "\t.quad dyld_stub_binding_helper\n";
651       else
652         O << "\t.long dyld_stub_binding_helper\n";
653     }
654   } else {
655     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
656          i != e; ++i) {
657       SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
658                           "pure_instructions,16");
659       EmitAlignment(4);
660       O << "L" << *i << "$stub:\n";
661       O << "\t.indirect_symbol " << *i << "\n";
662       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
663       if (isPPC64)
664         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
665       else
666         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
667       O << "\tmtctr r12\n";
668       O << "\tbctr\n";
669       SwitchToDataSection(".lazy_symbol_pointer");
670       O << "L" << *i << "$lazy_ptr:\n";
671       O << "\t.indirect_symbol " << *i << "\n";
672       if (isPPC64)
673         O << "\t.quad dyld_stub_binding_helper\n";
674       else
675         O << "\t.long dyld_stub_binding_helper\n";
676     }
677   }
678
679   O << "\n";
680
681   // Output stubs for external and common global variables.
682   if (GVStubs.begin() != GVStubs.end()) {
683     SwitchToDataSection(".non_lazy_symbol_pointer");
684     for (std::set<std::string>::iterator I = GVStubs.begin(),
685          E = GVStubs.end(); I != E; ++I) {
686       O << "L" << *I << "$non_lazy_ptr:\n";
687       O << "\t.indirect_symbol " << *I << "\n";
688       if (isPPC64)
689         O << "\t.quad\t0\n";
690       else
691         O << "\t.long\t0\n";
692         
693     }
694   }
695
696   // Emit initial debug information.
697   DW.EndModule();
698
699   // Funny Darwin hack: This flag tells the linker that no global symbols
700   // contain code that falls through to other global symbols (e.g. the obvious
701   // implementation of multiple entry points).  If this doesn't occur, the
702   // linker can safely perform dead code stripping.  Since LLVM never generates
703   // code that does this, it is always safe to set.
704   O << "\t.subsections_via_symbols\n";
705
706   AsmPrinter::doFinalization(M);
707   return false; // success
708 }
709
710
711
712 /// createDarwinCodePrinterPass - Returns a pass that prints the PPC assembly
713 /// code for a MachineFunction to the given output stream, in a format that the
714 /// Darwin assembler can deal with.
715 ///
716 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
717                                             PPCTargetMachine &tm) {
718   return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
719 }
720