Use the emitGlobalConstant defined in AsmPrinter
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPC32AsmPrinter.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 "PowerPC.h"
21 #include "PPC32TargetMachine.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "Support/CommandLine.h"
33 #include "Support/Debug.h"
34 #include "Support/Statistic.h"
35 #include "Support/StringExtras.h"
36 #include <set>
37 using namespace llvm;
38
39 namespace {
40   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
41
42   struct PPC32AsmPrinter : public AsmPrinter {
43     std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
44     std::set<std::string> Strings;
45
46     PPC32AsmPrinter(std::ostream &O, TargetMachine &TM)
47       : AsmPrinter(O, TM), LabelNumber(0) {
48       GlobalPrefix = "_";
49       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
50       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
51     }
52
53     /// Unique incrementer for label values for referencing Global values.
54     ///
55     unsigned LabelNumber;
56   
57     virtual const char *getPassName() const {
58       return "PPC32 Assembly Printer";
59     }
60
61     PPC32TargetMachine &getTM() {
62       return static_cast<PPC32TargetMachine&>(TM);
63     }
64
65     /// printInstruction - This method is automatically generated by tablegen
66     /// from the instruction set description.  This method returns true if the
67     /// machine instruction was sufficiently described to print it, otherwise it
68     /// returns false.
69     bool printInstruction(const MachineInstr *MI);
70
71     void printMachineInstruction(const MachineInstr *MI);
72     void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
73     void printImmOp(const MachineOperand &MO, unsigned ArgType);
74
75     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
76       const MachineOperand &MO = MI->getOperand(OpNo);
77       if (MO.getType() == MachineOperand::MO_MachineRegister) {
78         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
79         O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
80       } else if (MO.isImmediate()) {
81         O << MO.getImmedValue();
82       } else {
83         printOp(MO);
84       }
85     }
86
87     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
88                             MVT::ValueType VT) {
89       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
90     }
91
92     void printConstantPool(MachineConstantPool *MCP);
93     bool runOnMachineFunction(MachineFunction &F);    
94     bool doFinalization(Module &M);
95   };
96 } // end of anonymous namespace
97
98 /// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
99 /// assembly code for a MachineFunction to the given output stream,
100 /// using the given target machine description.  This should work
101 /// regardless of whether the function is in SSA form or not.
102 ///
103 FunctionPass *llvm::createPPC32AsmPrinter(std::ostream &o, TargetMachine &tm) {
104   return new PPC32AsmPrinter(o, tm);
105 }
106
107 // Include the auto-generated portion of the assembly writer
108 #include "PowerPCGenAsmWriter.inc"
109
110 /// printConstantPool - Print to the current output stream assembly
111 /// representations of the constants in the constant pool MCP. This is
112 /// used to print out constants which have been "spilled to memory" by
113 /// the code generator.
114 ///
115 void PPC32AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
116   const std::vector<Constant*> &CP = MCP->getConstants();
117   const TargetData &TD = TM.getTargetData();
118  
119   if (CP.empty()) return;
120
121   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
122     O << "\t.const\n";
123     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
124       << "\n";
125     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
126       << *CP[i] << "\n";
127     emitGlobalConstant(CP[i]);
128   }
129 }
130
131 /// runOnMachineFunction - This uses the printMachineInstruction()
132 /// method to print assembly for each instruction.
133 ///
134 bool PPC32AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
135   setupMachineFunction(MF);
136   O << "\n\n";
137
138   // Print out constants referenced by the function
139   printConstantPool(MF.getConstantPool());
140
141   // Print out labels for the function.
142   O << "\t.text\n"; 
143   O << "\t.globl\t" << CurrentFnName << "\n";
144   O << "\t.align 2\n";
145   O << CurrentFnName << ":\n";
146
147   // Print out code for the function.
148   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
149        I != E; ++I) {
150     // Print a label for the basic block.
151     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
152       << I->getBasicBlock()->getName() << "\n";
153     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
154       II != E; ++II) {
155       // Print the assembly for the instruction.
156       O << "\t";
157       printMachineInstruction(II);
158     }
159   }
160   ++LabelNumber;
161
162   // We didn't modify anything.
163   return false;
164 }
165
166 void PPC32AsmPrinter::printOp(const MachineOperand &MO,
167                               bool LoadAddrOp /* = false */) {
168   const MRegisterInfo &RI = *TM.getRegisterInfo();
169   int new_symbol;
170   
171   switch (MO.getType()) {
172   case MachineOperand::MO_VirtualRegister:
173     if (Value *V = MO.getVRegValueOrNull()) {
174       O << "<" << V->getName() << ">";
175       return;
176     }
177     // FALLTHROUGH
178   case MachineOperand::MO_MachineRegister:
179   case MachineOperand::MO_CCRegister:
180     O << LowercaseString(RI.get(MO.getReg()).Name);
181     return;
182
183   case MachineOperand::MO_SignExtendedImmed:
184   case MachineOperand::MO_UnextendedImmed:
185     std::cerr << "printOp() does not handle immediate values\n";
186     abort();
187     return;
188
189   case MachineOperand::MO_PCRelativeDisp:
190     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
191     abort();
192     return;
193     
194   case MachineOperand::MO_MachineBasicBlock: {
195     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
196     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
197       << "_" << MBBOp->getNumber() << "\t; "
198       << MBBOp->getBasicBlock()->getName();
199     return;
200   }
201
202   case MachineOperand::MO_ConstantPoolIndex:
203     O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
204     return;
205
206   case MachineOperand::MO_ExternalSymbol:
207     O << MO.getSymbolName();
208     return;
209
210   case MachineOperand::MO_GlobalAddress: {
211     GlobalValue *GV = MO.getGlobal();
212     std::string Name = Mang->getValueName(GV);
213
214     // Dynamically-resolved functions need a stub for the function.  Be
215     // wary however not to output $stub for external functions whose addresses
216     // are taken.  Those should be emitted as $non_lazy_ptr below.
217     Function *F = dyn_cast<Function>(GV);
218     if (F && F->isExternal() && !LoadAddrOp &&
219         getTM().CalledFunctions.count(F)) {
220       FnStubs.insert(Name);
221       O << "L" << Name << "$stub";
222       return;
223     }
224     
225     // External global variables need a non-lazily-resolved stub
226     if (GV->isExternal() && getTM().AddressTaken.count(GV)) {
227       GVStubs.insert(Name);
228       O << "L" << Name << "$non_lazy_ptr";
229       return;
230     }
231     
232     if (F && LoadAddrOp && getTM().AddressTaken.count(GV)) {
233       LinkOnceStubs.insert(Name);
234       O << "L" << Name << "$non_lazy_ptr";
235       return;
236     }
237             
238     O << Mang->getValueName(GV);
239     return;
240   }
241     
242   default:
243     O << "<unknown operand type: " << MO.getType() << ">";
244     return;
245   }
246 }
247
248 void PPC32AsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
249   int Imm = MO.getImmedValue();
250   if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
251     O << (short)Imm;
252   } else {
253     O << Imm;
254   }
255 }
256
257 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
258 /// the current output stream.
259 ///
260 void PPC32AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
261   ++EmittedInsts;
262   if (printInstruction(MI))
263     return; // Printer was automatically generated
264     
265   unsigned Opcode = MI->getOpcode();
266   const TargetInstrInfo &TII = *TM.getInstrInfo();
267   const TargetInstrDescriptor &Desc = TII.get(Opcode);
268   unsigned i;
269
270   unsigned ArgCount = MI->getNumOperands();
271   unsigned ArgType[] = {
272     (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
273     (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
274     (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
275     (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
276     (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
277   };
278   assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
279          "Instruction requires VMX support");
280   assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
281          "Instruction requires 64 bit support");
282
283   // CALLpcrel and CALLindirect are handled specially here to print only the
284   // appropriate number of args that the assembler expects.  This is because
285   // may have many arguments appended to record the uses of registers that are
286   // holding arguments to the called function.
287   if (Opcode == PPC::COND_BRANCH) {
288     std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
289     abort();
290   } else if (Opcode == PPC::IMPLICIT_DEF) {
291     O << "; IMPLICIT DEF ";
292     printOp(MI->getOperand(0));
293     O << "\n";
294     return;
295   } else if (Opcode == PPC::CALLpcrel) {
296     O << TII.getName(Opcode) << " ";
297     printOp(MI->getOperand(0));
298     O << "\n";
299     return;
300   } else if (Opcode == PPC::CALLindirect) {
301     O << TII.getName(Opcode) << " ";
302     printImmOp(MI->getOperand(0), ArgType[0]);
303     O << ", ";
304     printImmOp(MI->getOperand(1), ArgType[0]);
305     O << "\n";
306     return;
307   } else if (Opcode == PPC::MovePCtoLR) {
308     // FIXME: should probably be converted to cout.width and cout.fill
309     O << "bl \"L0000" << LabelNumber << "$pb\"\n";
310     O << "\"L0000" << LabelNumber << "$pb\":\n";
311     O << "\tmflr ";
312     printOp(MI->getOperand(0));
313     O << "\n";
314     return;
315   }
316
317   O << TII.getName(Opcode) << " ";
318   if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
319     printOp(MI->getOperand(0));
320     O << ", lo16(";
321     printOp(MI->getOperand(2), true /* LoadAddrOp */);
322     O << "-\"L0000" << LabelNumber << "$pb\")";
323     O << "(";
324     if (MI->getOperand(1).getReg() == PPC::R0)
325       O << "0";
326     else
327       printOp(MI->getOperand(1));
328     O << ")\n";
329   } else if (Opcode == PPC::LOADHiAddr) {
330     printOp(MI->getOperand(0));
331     O << ", ";
332     if (MI->getOperand(1).getReg() == PPC::R0)
333       O << "0";
334     else
335       printOp(MI->getOperand(1));
336     O << ", ha16(" ;
337     printOp(MI->getOperand(2), true /* LoadAddrOp */);
338      O << "-\"L0000" << LabelNumber << "$pb\")\n";
339   } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
340     printOp(MI->getOperand(0));
341     O << ", ";
342     printImmOp(MI->getOperand(1), ArgType[1]);
343     O << "(";
344     if (MI->getOperand(2).hasAllocatedReg() &&
345         MI->getOperand(2).getReg() == PPC::R0)
346       O << "0";
347     else
348       printOp(MI->getOperand(2));
349     O << ")\n";
350   } else {
351     for (i = 0; i < ArgCount; ++i) {
352       // addi and friends
353       if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
354           MI->getOperand(1).hasAllocatedReg() && 
355           MI->getOperand(1).getReg() == PPC::R0) {
356         O << "0";
357       // for long branch support, bc $+8
358       } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
359                  TII.isBranch(MI->getOpcode())) {
360         O << "$+8";
361         assert(8 == MI->getOperand(i).getImmedValue()
362           && "branch off PC not to pc+8?");
363         //printOp(MI->getOperand(i));
364       } else if (MI->getOperand(i).isImmediate()) {
365         printImmOp(MI->getOperand(i), ArgType[i]);
366       } else {
367         printOp(MI->getOperand(i));
368       }
369       if (ArgCount - 1 == i)
370         O << "\n";
371       else
372         O << ", ";
373     }
374   }
375   return;
376 }
377
378 // SwitchSection - Switch to the specified section of the executable if we are
379 // not already in it!
380 //
381 static void SwitchSection(std::ostream &OS, std::string &CurSection,
382                           const char *NewSection) {
383   if (CurSection != NewSection) {
384     CurSection = NewSection;
385     if (!CurSection.empty())
386       OS << "\t" << NewSection << "\n";
387   }
388 }
389
390 bool PPC32AsmPrinter::doFinalization(Module &M) {
391   const TargetData &TD = TM.getTargetData();
392   std::string CurSection;
393
394   // Print out module-level global variables here.
395   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
396     if (I->hasInitializer()) {   // External global require no code
397       O << "\n\n";
398       std::string name = Mang->getValueName(I);
399       Constant *C = I->getInitializer();
400       unsigned Size = TD.getTypeSize(C->getType());
401       unsigned Align = TD.getTypeAlignment(C->getType());
402
403       if (C->isNullValue() && /* FIXME: Verify correct */
404           (I->hasInternalLinkage() || I->hasWeakLinkage())) {
405         SwitchSection(O, CurSection, ".data");
406         if (I->hasInternalLinkage())
407           O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
408             << "," << (unsigned)TD.getTypeAlignment(C->getType());
409         else 
410           O << ".comm " << name << "," << TD.getTypeSize(C->getType());
411         O << "\t\t; ";
412         WriteAsOperand(O, I, true, true, &M);
413         O << "\n";
414       } else {
415         switch (I->getLinkage()) {
416         case GlobalValue::LinkOnceLinkage:
417           O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
418             << ".weak_definition " << name << '\n'
419             << ".private_extern " << name << '\n'
420             << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
421           LinkOnceStubs.insert(name);
422           break;  
423         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
424           // Nonnull linkonce -> weak
425           O << "\t.weak " << name << "\n";
426           SwitchSection(O, CurSection, "");
427           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
428           break;
429         case GlobalValue::AppendingLinkage:
430           // FIXME: appending linkage variables should go into a section of
431           // their name or something.  For now, just emit them as external.
432         case GlobalValue::ExternalLinkage:
433           // If external or appending, declare as a global symbol
434           O << "\t.globl " << name << "\n";
435           // FALL THROUGH
436         case GlobalValue::InternalLinkage:
437           SwitchSection(O, CurSection, ".data");
438           break;
439         }
440
441         O << "\t.align " << Align << "\n";
442         O << name << ":\t\t\t\t; ";
443         WriteAsOperand(O, I, true, true, &M);
444         O << " = ";
445         WriteAsOperand(O, C, false, false, &M);
446         O << "\n";
447         emitGlobalConstant(C);
448       }
449     }
450
451   // Output stubs for dynamically-linked functions
452   for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); 
453        i != e; ++i)
454   {
455     O << ".data\n";
456     O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
457     O << "\t.align 2\n";
458     O << "L" << *i << "$stub:\n";
459     O << "\t.indirect_symbol " << *i << "\n";
460     O << "\tmflr r0\n";
461     O << "\tbcl 20,31,L0$" << *i << "\n";
462     O << "L0$" << *i << ":\n";
463     O << "\tmflr r11\n";
464     O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
465     O << "\tmtlr r0\n";
466     O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
467     O << "\tmtctr r12\n";
468     O << "\tbctr\n";
469     O << ".data\n";
470     O << ".lazy_symbol_pointer\n";
471     O << "L" << *i << "$lazy_ptr:\n";
472     O << "\t.indirect_symbol " << *i << "\n";
473     O << "\t.long dyld_stub_binding_helper\n";
474   }
475
476   O << "\n";
477
478   // Output stubs for external global variables
479   if (GVStubs.begin() != GVStubs.end())
480     O << ".data\n.non_lazy_symbol_pointer\n";
481   for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end(); 
482        i != e; ++i) {
483     O << "L" << *i << "$non_lazy_ptr:\n";
484     O << "\t.indirect_symbol " << *i << "\n";
485     O << "\t.long\t0\n";
486   }
487   
488   // Output stubs for link-once variables
489   if (LinkOnceStubs.begin() != LinkOnceStubs.end())
490     O << ".data\n.align 2\n";
491   for (std::set<std::string>::iterator i = LinkOnceStubs.begin(), 
492          e = LinkOnceStubs.end(); i != e; ++i) {
493     O << "L" << *i << "$non_lazy_ptr:\n"
494       << "\t.long\t" << *i << '\n';
495   }
496   
497   AsmPrinter::doFinalization(M);
498   return false; // success
499 }