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