Add explicit #includes of <iostream>
[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 "PPCTargetMachine.h"
22 #include "PPCSubtarget.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/AsmPrinter.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/CodeGen/MachineDebugInfo.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Target/MRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include <iostream>
41 #include <set>
42 using namespace llvm;
43
44 namespace {
45   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
46
47   class PPCAsmPrinter : public AsmPrinter {
48   public:
49     std::set<std::string> FnStubs, GVStubs;
50     
51     PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
52       : AsmPrinter(O, TM) {}
53
54     virtual const char *getPassName() const {
55       return "PowerPC Assembly Printer";
56     }
57
58     PPCTargetMachine &getTM() {
59       return static_cast<PPCTargetMachine&>(TM);
60     }
61
62     unsigned enumRegToMachineReg(unsigned enumReg) {
63       switch (enumReg) {
64       default: assert(0 && "Unhandled register!"); break;
65       case PPC::CR0:  return  0;
66       case PPC::CR1:  return  1;
67       case PPC::CR2:  return  2;
68       case PPC::CR3:  return  3;
69       case PPC::CR4:  return  4;
70       case PPC::CR5:  return  5;
71       case PPC::CR6:  return  6;
72       case PPC::CR7:  return  7;
73       }
74       abort();
75     }
76
77     /// printInstruction - This method is automatically generated by tablegen
78     /// from the instruction set description.  This method returns true if the
79     /// machine instruction was sufficiently described to print it, otherwise it
80     /// returns false.
81     bool printInstruction(const MachineInstr *MI);
82
83     void printMachineInstruction(const MachineInstr *MI);
84     void printOp(const MachineOperand &MO);
85
86     void printOperand(const MachineInstr *MI, unsigned OpNo){
87       const MachineOperand &MO = MI->getOperand(OpNo);
88       if (MO.getType() == MachineOperand::MO_MachineRegister) {
89         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
90         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
91       } else if (MO.isImmediate()) {
92         O << MO.getImmedValue();
93       } else {
94         printOp(MO);
95       }
96     }
97
98     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
99       unsigned char value = MI->getOperand(OpNo).getImmedValue();
100       assert(value <= 31 && "Invalid u5imm argument!");
101       O << (unsigned int)value;
102     }
103     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
104       unsigned char value = MI->getOperand(OpNo).getImmedValue();
105       assert(value <= 63 && "Invalid u6imm argument!");
106       O << (unsigned int)value;
107     }
108     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
109       O << (short)MI->getOperand(OpNo).getImmedValue();
110     }
111     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
112       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
113     }
114     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
115       O << (short)MI->getOperand(OpNo).getImmedValue()*4;
116     }
117     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
118       // Branches can take an immediate operand.  This is used by the branch
119       // selection pass to print $+8, an eight byte displacement from the PC.
120       if (MI->getOperand(OpNo).isImmediate()) {
121         O << "$+" << MI->getOperand(OpNo).getImmedValue();
122       } else {
123         printOp(MI->getOperand(OpNo));
124       }
125     }
126     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
127       const MachineOperand &MO = MI->getOperand(OpNo);
128       if (!PPCGenerateStaticCode) {
129         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
130           GlobalValue *GV = MO.getGlobal();
131           if (((GV->isExternal() || GV->hasWeakLinkage() ||
132                 GV->hasLinkOnceLinkage()))) {
133             // Dynamically-resolved functions need a stub for the function.
134             std::string Name = Mang->getValueName(GV);
135             FnStubs.insert(Name);
136             O << "L" << Name << "$stub";
137             return;
138           }
139         }
140         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
141           std::string Name(GlobalPrefix); Name += MO.getSymbolName();
142           FnStubs.insert(Name);
143           O << "L" << Name << "$stub";
144           return;
145         }
146       }
147       
148       printOp(MI->getOperand(OpNo));
149     }
150     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
151      O << (int)MI->getOperand(OpNo).getImmedValue()*4;
152     }
153     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
154       O << "\"L" << getFunctionNumber() << "$pb\"\n";
155       O << "\"L" << getFunctionNumber() << "$pb\":";
156     }
157     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
158       if (MI->getOperand(OpNo).isImmediate()) {
159         printS16ImmOperand(MI, OpNo);
160       } else {
161         O << "ha16(";
162         printOp(MI->getOperand(OpNo));
163         if (PICEnabled)
164           O << "-\"L" << getFunctionNumber() << "$pb\")";
165         else
166           O << ')';
167       }
168     }
169     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
170       if (MI->getOperand(OpNo).isImmediate()) {
171         printS16ImmOperand(MI, OpNo);
172       } else {
173         O << "lo16(";
174         printOp(MI->getOperand(OpNo));
175         if (PICEnabled)
176           O << "-\"L" << getFunctionNumber() << "$pb\")";
177         else
178           O << ')';
179       }
180     }
181     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
182       unsigned CCReg = MI->getOperand(OpNo).getReg();
183       unsigned RegNo = enumRegToMachineReg(CCReg);
184       O << (0x80 >> RegNo);
185     }
186     // The new addressing mode printers, currently empty
187     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
188       printSymbolLo(MI, OpNo);
189       O << '(';
190       printOperand(MI, OpNo+1);
191       O << ')';
192     }
193     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
194       // When used as the base register, r0 reads constant zero rather than
195       // the value contained in the register.  For this reason, the darwin
196       // assembler requires that we print r0 as 0 (no r) when used as the base.
197       const MachineOperand &MO = MI->getOperand(OpNo);
198       if (MO.getReg() == PPC::R0)
199         O << '0';
200       else
201         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
202       O << ", ";
203       printOperand(MI, OpNo+1);
204     }
205     
206     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
207     virtual bool doFinalization(Module &M) = 0;
208     
209   };
210
211   /// DarwinDwarfWriter - Dwarf debug info writer customized for Darwin/Mac OS X
212   ///
213   struct DarwinDwarfWriter : public DwarfWriter {
214     // Ctor.
215     DarwinDwarfWriter(std::ostream &o, AsmPrinter *ap)
216     : DwarfWriter(o, ap)
217     {
218       needsSet = true;
219       DwarfAbbrevSection = ".section __DWARFA,__debug_abbrev";
220       DwarfInfoSection = ".section __DWARFA,__debug_info";
221       DwarfLineSection = ".section __DWARFA,__debug_line";
222       DwarfFrameSection =
223           ".section __DWARFA,__debug_frame,,coalesced,no_toc+strip_static_syms";
224       DwarfPubNamesSection = ".section __DWARFA,__debug_pubnames";
225       DwarfPubTypesSection = ".section __DWARFA,__debug_pubtypes";
226       DwarfStrSection = ".section __DWARFA,__debug_str";
227       DwarfLocSection = ".section __DWARFA,__debug_loc";
228       DwarfARangesSection = ".section __DWARFA,__debug_aranges";
229       DwarfRangesSection = ".section __DWARFA,__debug_ranges";
230       DwarfMacInfoSection = ".section __DWARFA,__debug_macinfo";
231       TextSection = ".text";
232       DataSection = ".data";
233     }
234   };
235
236   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
237   /// X
238   struct DarwinAsmPrinter : public PPCAsmPrinter {
239   
240     DarwinDwarfWriter DW;
241
242     DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
243       : PPCAsmPrinter(O, TM), DW(O, this)      
244       {
245       CommentString = ";";
246       GlobalPrefix = "_";
247       PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
248       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
249       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
250       AlignmentIsInBytes = false;    // Alignment is by power of 2.
251       ConstantPoolSection = "\t.const\t";
252       LCOMMDirective = "\t.lcomm\t";
253       StaticCtorsSection = ".mod_init_func";
254       StaticDtorsSection = ".mod_term_func";
255     }
256
257     virtual const char *getPassName() const {
258       return "Darwin PPC Assembly Printer";
259     }
260     
261     bool runOnMachineFunction(MachineFunction &F);
262     bool doInitialization(Module &M);
263     bool doFinalization(Module &M);
264     
265     void getAnalysisUsage(AnalysisUsage &AU) const {
266       AU.setPreservesAll();
267       AU.addRequired<MachineDebugInfo>();
268       PPCAsmPrinter::getAnalysisUsage(AU);
269     }
270
271   };
272
273   /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
274   ///
275   struct AIXAsmPrinter : public PPCAsmPrinter {
276     /// Map for labels corresponding to global variables
277     ///
278     std::map<const GlobalVariable*,std::string> GVToLabelMap;
279
280     AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
281       : PPCAsmPrinter(O, TM) {
282       CommentString = "#";
283       GlobalPrefix = ".";
284       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
285       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
286       AlignmentIsInBytes = false;    // Alignment is by power of 2.
287       ConstantPoolSection = "\t.const\t";
288     }
289
290     virtual const char *getPassName() const {
291       return "AIX PPC Assembly Printer";
292     }
293
294     bool runOnMachineFunction(MachineFunction &F);
295     bool doInitialization(Module &M);
296     bool doFinalization(Module &M);
297   };
298 } // end of anonymous namespace
299
300 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
301 /// code for a MachineFunction to the given output stream, in a format that the
302 /// Darwin assembler can deal with.
303 ///
304 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
305   return new DarwinAsmPrinter(o, tm);
306 }
307
308 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
309 /// for a MachineFunction to the given output stream, in a format that the
310 /// AIX 5L assembler can deal with.
311 ///
312 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
313   return new AIXAsmPrinter(o, tm);
314 }
315
316 // Include the auto-generated portion of the assembly writer
317 #include "PPCGenAsmWriter.inc"
318
319 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
320   const MRegisterInfo &RI = *TM.getRegisterInfo();
321   int new_symbol;
322
323   switch (MO.getType()) {
324   case MachineOperand::MO_VirtualRegister:
325     if (Value *V = MO.getVRegValueOrNull()) {
326       O << "<" << V->getName() << ">";
327       return;
328     }
329     // FALLTHROUGH
330   case MachineOperand::MO_MachineRegister:
331   case MachineOperand::MO_CCRegister:
332     O << RI.get(MO.getReg()).Name;
333     return;
334
335   case MachineOperand::MO_SignExtendedImmed:
336   case MachineOperand::MO_UnextendedImmed:
337     std::cerr << "printOp() does not handle immediate values\n";
338     abort();
339     return;
340
341   case MachineOperand::MO_PCRelativeDisp:
342     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
343     abort();
344     return;
345
346   case MachineOperand::MO_MachineBasicBlock: {
347     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
348     O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << "_"
349       << MBBOp->getNumber() << "\t; " << MBBOp->getBasicBlock()->getName();
350     return;
351   }
352
353   case MachineOperand::MO_ConstantPoolIndex:
354     O << PrivateGlobalPrefix << "CPI" << getFunctionNumber()
355       << '_' << MO.getConstantPoolIndex();
356     return;
357   case MachineOperand::MO_ExternalSymbol:
358     // Computing the address of an external symbol, not calling it.
359     if (!PPCGenerateStaticCode) {
360       std::string Name(GlobalPrefix); Name += MO.getSymbolName();
361       GVStubs.insert(Name);
362       O << "L" << Name << "$non_lazy_ptr";
363       return;
364     }
365     O << GlobalPrefix << MO.getSymbolName();
366     return;
367   case MachineOperand::MO_GlobalAddress: {
368     // Computing the address of a global symbol, not calling it.
369     GlobalValue *GV = MO.getGlobal();
370     std::string Name = Mang->getValueName(GV);
371     int offset = MO.getOffset();
372
373     // External or weakly linked global variables need non-lazily-resolved stubs
374     if (!PPCGenerateStaticCode) {
375       if (((GV->isExternal() || GV->hasWeakLinkage() ||
376             GV->hasLinkOnceLinkage()))) {
377         GVStubs.insert(Name);
378         O << "L" << Name << "$non_lazy_ptr";
379         return;
380       }
381     }
382
383     O << Name;
384     return;
385   }
386
387   default:
388     O << "<unknown operand type: " << MO.getType() << ">";
389     return;
390   }
391 }
392
393 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
394 /// the current output stream.
395 ///
396 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
397   ++EmittedInsts;
398
399   // Check for slwi/srwi mnemonics.
400   if (MI->getOpcode() == PPC::RLWINM) {
401     bool FoundMnemonic = false;
402     unsigned char SH = MI->getOperand(2).getImmedValue();
403     unsigned char MB = MI->getOperand(3).getImmedValue();
404     unsigned char ME = MI->getOperand(4).getImmedValue();
405     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
406       O << "slwi "; FoundMnemonic = true;
407     }
408     if (SH <= 31 && MB == (32-SH) && ME == 31) {
409       O << "srwi "; FoundMnemonic = true;
410       SH = 32-SH;
411     }
412     if (FoundMnemonic) {
413       printOperand(MI, 0);
414       O << ", ";
415       printOperand(MI, 1);
416       O << ", " << (unsigned int)SH << "\n";
417       return;
418     }
419   }
420
421   if (printInstruction(MI))
422     return; // Printer was automatically generated
423
424   assert(0 && "Unhandled instruction in asm writer!");
425   abort();
426   return;
427 }
428
429
430 /// runOnMachineFunction - This uses the printMachineInstruction()
431 /// method to print assembly for each instruction.
432 ///
433 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
434   // FIXME - is this the earliest this can be set.
435   DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
436
437   SetupMachineFunction(MF);
438   O << "\n\n";
439   
440   // Emit pre-function debug information.
441   DW.BeginFunction();
442
443   // Print out constants referenced by the function
444   EmitConstantPool(MF.getConstantPool());
445
446   // Print out labels for the function.
447   const Function *F = MF.getFunction();
448   switch (F->getLinkage()) {
449   default: assert(0 && "Unknown linkage type!");
450   case Function::InternalLinkage:  // Symbols default to internal.
451     SwitchSection(".text", F);
452     EmitAlignment(4, F);
453     break;
454   case Function::ExternalLinkage:
455     SwitchSection(".text", F);
456     EmitAlignment(4, F);
457     O << "\t.globl\t" << CurrentFnName << "\n";
458     break;
459   case Function::WeakLinkage:
460   case Function::LinkOnceLinkage:
461     SwitchSection(".section __TEXT,__textcoal_nt,coalesced,pure_instructions",
462                   F);
463     O << "\t.globl\t" << CurrentFnName << "\n";
464     O << "\t.weak_definition\t" << CurrentFnName << "\n";
465     break;
466   }
467   O << CurrentFnName << ":\n";
468
469   // Print out code for the function.
470   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
471        I != E; ++I) {
472     // Print a label for the basic block.
473     if (I != MF.begin()) {
474       O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
475         << I->getNumber() << ":\t";
476       if (!I->getBasicBlock()->getName().empty())
477         O << CommentString << " " << I->getBasicBlock()->getName();
478       O << "\n";
479     }
480     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
481          II != E; ++II) {
482       // Print the assembly for the instruction.
483       O << "\t";
484       printMachineInstruction(II);
485     }
486   }
487
488   // Emit post-function debug information.
489   DW.EndFunction();
490
491   // We didn't modify anything.
492   return false;
493 }
494
495
496 bool DarwinAsmPrinter::doInitialization(Module &M) {
497   if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
498     O << "\t.machine ppc970\n";
499   AsmPrinter::doInitialization(M);
500   
501   // Darwin wants symbols to be quoted if they have complex names.
502   Mang->setUseQuotes(true);
503   
504   // Emit initial debug information.
505   DW.BeginModule();
506   return false;
507 }
508
509 bool DarwinAsmPrinter::doFinalization(Module &M) {
510   const TargetData &TD = TM.getTargetData();
511
512   // Print out module-level global variables here.
513   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
514        I != E; ++I) {
515     if (!I->hasInitializer()) continue;   // External global require no code
516     
517     // Check to see if this is a special global used by LLVM, if so, emit it.
518     if (I->hasAppendingLinkage() && EmitSpecialLLVMGlobal(I))
519       continue;
520     
521     std::string name = Mang->getValueName(I);
522     Constant *C = I->getInitializer();
523     unsigned Size = TD.getTypeSize(C->getType());
524     unsigned Align = TD.getTypeAlignmentShift(C->getType());
525
526     if (C->isNullValue() && /* FIXME: Verify correct */
527         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
528          I->hasLinkOnceLinkage())) {
529       SwitchSection(".data", I);
530       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
531       if (I->hasInternalLinkage())
532         O << LCOMMDirective << name << "," << Size << "," << Align;
533       else
534         O << ".comm " << name << "," << Size;
535       O << "\t\t; '" << I->getName() << "'\n";
536     } else {
537       switch (I->getLinkage()) {
538       case GlobalValue::LinkOnceLinkage:
539       case GlobalValue::WeakLinkage:
540         O << "\t.globl " << name << '\n'
541           << "\t.weak_definition " << name << '\n';
542         SwitchSection(".section __DATA,__datacoal_nt,coalesced", I);
543         break;
544       case GlobalValue::AppendingLinkage:
545         // FIXME: appending linkage variables should go into a section of
546         // their name or something.  For now, just emit them as external.
547       case GlobalValue::ExternalLinkage:
548         // If external or appending, declare as a global symbol
549         O << "\t.globl " << name << "\n";
550         // FALL THROUGH
551       case GlobalValue::InternalLinkage:
552         SwitchSection(".data", I);
553         break;
554       default:
555         std::cerr << "Unknown linkage type!";
556         abort();
557       }
558
559       EmitAlignment(Align, I);
560       O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
561       EmitGlobalConstant(C);
562       O << '\n';
563     }
564   }
565
566   // Output stubs for dynamically-linked functions
567   if (PICEnabled) {
568     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
569          i != e; ++i) {
570       SwitchSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
571                     "pure_instructions,32", 0);
572       EmitAlignment(2);
573       O << "L" << *i << "$stub:\n";
574       O << "\t.indirect_symbol " << *i << "\n";
575       O << "\tmflr r0\n";
576       O << "\tbcl 20,31,L0$" << *i << "\n";
577       O << "L0$" << *i << ":\n";
578       O << "\tmflr r11\n";
579       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
580       O << "\tmtlr r0\n";
581       O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
582       O << "\tmtctr r12\n";
583       O << "\tbctr\n";
584       SwitchSection(".lazy_symbol_pointer", 0);
585       O << "L" << *i << "$lazy_ptr:\n";
586       O << "\t.indirect_symbol " << *i << "\n";
587       O << "\t.long dyld_stub_binding_helper\n";
588     }
589   } else {
590     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
591          i != e; ++i) {
592       SwitchSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
593                     "pure_instructions,16", 0);
594       EmitAlignment(4);
595       O << "L" << *i << "$stub:\n";
596       O << "\t.indirect_symbol " << *i << "\n";
597       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
598       O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
599       O << "\tmtctr r12\n";
600       O << "\tbctr\n";
601       SwitchSection(".lazy_symbol_pointer", 0);
602       O << "L" << *i << "$lazy_ptr:\n";
603       O << "\t.indirect_symbol " << *i << "\n";
604       O << "\t.long dyld_stub_binding_helper\n";
605     }
606   }
607
608   O << "\n";
609
610   // Output stubs for external and common global variables.
611   if (GVStubs.begin() != GVStubs.end()) {
612     SwitchSection(".non_lazy_symbol_pointer", 0);
613     for (std::set<std::string>::iterator I = GVStubs.begin(),
614          E = GVStubs.end(); I != E; ++I) {
615       O << "L" << *I << "$non_lazy_ptr:\n";
616       O << "\t.indirect_symbol " << *I << "\n";
617       O << "\t.long\t0\n";
618     }
619   }
620
621   // Emit initial debug information.
622   DW.EndModule();
623
624   // Funny Darwin hack: This flag tells the linker that no global symbols
625   // contain code that falls through to other global symbols (e.g. the obvious
626   // implementation of multiple entry points).  If this doesn't occur, the
627   // linker can safely perform dead code stripping.  Since LLVM never generates
628   // code that does this, it is always safe to set.
629   O << "\t.subsections_via_symbols\n";
630
631   AsmPrinter::doFinalization(M);
632   return false; // success
633 }
634
635 /// runOnMachineFunction - This uses the e()
636 /// method to print assembly for each instruction.
637 ///
638 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
639   SetupMachineFunction(MF);
640   
641   // Print out constants referenced by the function
642   EmitConstantPool(MF.getConstantPool());
643
644   // Print out header for the function.
645   O << "\t.csect .text[PR]\n"
646     << "\t.align 2\n"
647     << "\t.globl "  << CurrentFnName << '\n'
648     << "\t.globl ." << CurrentFnName << '\n'
649     << "\t.csect "  << CurrentFnName << "[DS],3\n"
650     << CurrentFnName << ":\n"
651     << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
652     << "\t.csect .text[PR]\n"
653     << '.' << CurrentFnName << ":\n";
654
655   // Print out code for the function.
656   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
657        I != E; ++I) {
658     // Print a label for the basic block.
659     O << PrivateGlobalPrefix << "BB" << getFunctionNumber() << '_'
660       << I->getNumber()
661       << ":\t" << CommentString << I->getBasicBlock()->getName() << '\n';
662     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
663       II != E; ++II) {
664       // Print the assembly for the instruction.
665       O << "\t";
666       printMachineInstruction(II);
667     }
668   }
669
670   O << "LT.." << CurrentFnName << ":\n"
671     << "\t.long 0\n"
672     << "\t.byte 0,0,32,65,128,0,0,0\n"
673     << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
674     << "\t.short 3\n"
675     << "\t.byte \"" << CurrentFnName << "\"\n"
676     << "\t.align 2\n";
677
678   // We didn't modify anything.
679   return false;
680 }
681
682 bool AIXAsmPrinter::doInitialization(Module &M) {
683   SwitchSection("", 0);
684   const TargetData &TD = TM.getTargetData();
685
686   O << "\t.machine \"ppc64\"\n"
687     << "\t.toc\n"
688     << "\t.csect .text[PR]\n";
689
690   // Print out module-level global variables
691   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
692        I != E; ++I) {
693     if (!I->hasInitializer())
694       continue;
695
696     std::string Name = I->getName();
697     Constant *C = I->getInitializer();
698     // N.B.: We are defaulting to writable strings
699     if (I->hasExternalLinkage()) {
700       O << "\t.globl " << Name << '\n'
701         << "\t.csect .data[RW],3\n";
702     } else {
703       O << "\t.csect _global.rw_c[RW],3\n";
704     }
705     O << Name << ":\n";
706     EmitGlobalConstant(C);
707   }
708
709   // Output labels for globals
710   if (M.global_begin() != M.global_end()) O << "\t.toc\n";
711   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
712        I != E; ++I) {
713     const GlobalVariable *GV = I;
714     // Do not output labels for unused variables
715     if (GV->isExternal() && GV->use_begin() == GV->use_end())
716       continue;
717
718     IncrementFunctionNumber();
719     std::string Name = GV->getName();
720     std::string Label = "LC.." + utostr(getFunctionNumber());
721     GVToLabelMap[GV] = Label;
722     O << Label << ":\n"
723       << "\t.tc " << Name << "[TC]," << Name;
724     if (GV->isExternal()) O << "[RW]";
725     O << '\n';
726    }
727
728   AsmPrinter::doInitialization(M);
729   return false; // success
730 }
731
732 bool AIXAsmPrinter::doFinalization(Module &M) {
733   const TargetData &TD = TM.getTargetData();
734   // Print out module-level global variables
735   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
736        I != E; ++I) {
737     if (I->hasInitializer() || I->hasExternalLinkage())
738       continue;
739
740     std::string Name = I->getName();
741     if (I->hasInternalLinkage()) {
742       O << "\t.lcomm " << Name << ",16,_global.bss_c";
743     } else {
744       O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
745         << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
746     }
747     O << "\t\t" << CommentString << " ";
748     WriteAsOperand(O, I, false, true, &M);
749     O << "\n";
750   }
751
752   O << "_section_.text:\n"
753     << "\t.csect .data[RW],3\n"
754     << "\t.llong _section_.text\n";
755   AsmPrinter::doFinalization(M);
756   return false; // success
757 }