Rename LessPrivateGlobalPrefix -> LinkerPrivateGlobalPrefix to match the
[oota-llvm.git] / lib / Target / SystemZ / AsmPrinter / SystemZAsmPrinter.cpp
1 //===-- SystemZAsmPrinter.cpp - SystemZ LLVM assembly writer ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to the SystemZ assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "SystemZ.h"
17 #include "SystemZInstrInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/Mangler.h"
35
36 using namespace llvm;
37
38 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39
40 namespace {
41   class VISIBILITY_HIDDEN SystemZAsmPrinter : public AsmPrinter {
42   public:
43     SystemZAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
44                       const TargetAsmInfo *TAI, bool V)
45       : AsmPrinter(O, TM, TAI, V) {}
46
47     virtual const char *getPassName() const {
48       return "SystemZ Assembly Printer";
49     }
50
51     void printOperand(const MachineInstr *MI, int OpNum,
52                       const char* Modifier = 0);
53     void printPCRelImmOperand(const MachineInstr *MI, int OpNum);
54     void printRIAddrOperand(const MachineInstr *MI, int OpNum,
55                             const char* Modifier = 0);
56     void printRRIAddrOperand(const MachineInstr *MI, int OpNum,
57                              const char* Modifier = 0);
58     void printS16ImmOperand(const MachineInstr *MI, int OpNum) {
59       O << (int16_t)MI->getOperand(OpNum).getImm();
60     }
61     void printS32ImmOperand(const MachineInstr *MI, int OpNum) {
62       O << (int32_t)MI->getOperand(OpNum).getImm();
63     }
64
65     bool printInstruction(const MachineInstr *MI);  // autogenerated.
66     void printMachineInstruction(const MachineInstr * MI);
67
68     void emitFunctionHeader(const MachineFunction &MF);
69     bool runOnMachineFunction(MachineFunction &F);
70     bool doInitialization(Module &M);
71     bool doFinalization(Module &M);
72     void printModuleLevelGV(const GlobalVariable* GVar);
73
74     void getAnalysisUsage(AnalysisUsage &AU) const {
75       AsmPrinter::getAnalysisUsage(AU);
76       AU.setPreservesAll();
77     }
78   };
79 } // end of anonymous namespace
80
81 #include "SystemZGenAsmWriter.inc"
82
83 /// createSystemZCodePrinterPass - Returns a pass that prints the SystemZ
84 /// assembly code for a MachineFunction to the given output stream,
85 /// using the given target machine description.  This should work
86 /// regardless of whether the function is in SSA form.
87 ///
88 FunctionPass *llvm::createSystemZCodePrinterPass(formatted_raw_ostream &o,
89                                                  TargetMachine &tm,
90                                                  bool verbose) {
91   return new SystemZAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
92 }
93
94 bool SystemZAsmPrinter::doInitialization(Module &M) {
95   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix(),
96                      TAI->getLinkerPrivateGlobalPrefix());
97   return false; // success
98 }
99
100
101 bool SystemZAsmPrinter::doFinalization(Module &M) {
102   // Print out module-level global variables here.
103   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
104        I != E; ++I)
105     printModuleLevelGV(I);
106
107   return AsmPrinter::doFinalization(M);
108 }
109
110 void SystemZAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
111   unsigned FnAlign = MF.getAlignment();
112   const Function *F = MF.getFunction();
113
114   SwitchToSection(TAI->SectionForGlobal(F));
115
116   EmitAlignment(FnAlign, F);
117
118   switch (F->getLinkage()) {
119   default: assert(0 && "Unknown linkage type!");
120   case Function::InternalLinkage:  // Symbols default to internal.
121   case Function::PrivateLinkage:
122   case Function::LinkerPrivateLinkage:
123     break;
124   case Function::ExternalLinkage:
125     O << "\t.globl\t" << CurrentFnName << '\n';
126     break;
127   case Function::LinkOnceAnyLinkage:
128   case Function::LinkOnceODRLinkage:
129   case Function::WeakAnyLinkage:
130   case Function::WeakODRLinkage:
131     O << "\t.weak\t" << CurrentFnName << '\n';
132     break;
133   }
134
135   printVisibility(CurrentFnName, F->getVisibility());
136
137   O << "\t.type\t" << CurrentFnName << ",@function\n"
138     << CurrentFnName << ":\n";
139 }
140
141 bool SystemZAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
142   SetupMachineFunction(MF);
143   O << "\n\n";
144
145   // Print out constants referenced by the function
146   EmitConstantPool(MF.getConstantPool());
147
148   // Print the 'header' of function
149   emitFunctionHeader(MF);
150
151   // Print out code for the function.
152   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
153        I != E; ++I) {
154     // Print a label for the basic block.
155     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
156       // This is an entry block or a block that's only reachable via a
157       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
158     } else {
159       printBasicBlockLabel(I, true, true, VerboseAsm);
160       O << '\n';
161     }
162
163     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
164          II != E; ++II)
165       // Print the assembly for the instruction.
166       printMachineInstruction(II);
167   }
168
169   if (TAI->hasDotTypeDotSizeDirective())
170     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
171
172   // Print out jump tables referenced by the function.
173   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
174
175   O.flush();
176
177   // We didn't modify anything
178   return false;
179 }
180
181 void SystemZAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
182   ++EmittedInsts;
183
184   // Call the autogenerated instruction printer routines.
185   if (printInstruction(MI))
186     return;
187
188   llvm_unreachable("Unreachable!");
189 }
190
191 void SystemZAsmPrinter::printPCRelImmOperand(const MachineInstr *MI, int OpNum) {
192   const MachineOperand &MO = MI->getOperand(OpNum);
193   switch (MO.getType()) {
194   case MachineOperand::MO_Immediate:
195     O << MO.getImm();
196     return;
197   case MachineOperand::MO_MachineBasicBlock:
198     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
199     return;
200   case MachineOperand::MO_GlobalAddress: {
201     const GlobalValue *GV = MO.getGlobal();
202     std::string Name = Mang->getMangledName(GV);
203
204     O << Name;
205
206     // Assemble calls via PLT for externally visible symbols if PIC.
207     if (TM.getRelocationModel() == Reloc::PIC_ &&
208         !GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
209         !GV->hasLocalLinkage())
210       O << "@PLT";
211
212     printOffset(MO.getOffset());
213     return;
214   }
215   case MachineOperand::MO_ExternalSymbol: {
216     std::string Name(TAI->getGlobalPrefix());
217     Name += MO.getSymbolName();
218     O << Name;
219
220     if (TM.getRelocationModel() == Reloc::PIC_)
221       O << "@PLT";
222
223     return;
224   }
225   default:
226     assert(0 && "Not implemented yet!");
227   }
228 }
229
230
231 void SystemZAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
232                                      const char* Modifier) {
233   const MachineOperand &MO = MI->getOperand(OpNum);
234   switch (MO.getType()) {
235   case MachineOperand::MO_Register: {
236     assert (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
237             "Virtual registers should be already mapped!");
238     unsigned Reg = MO.getReg();
239     if (Modifier && strncmp(Modifier, "subreg", 6) == 0) {
240       if (strncmp(Modifier + 7, "even", 4) == 0)
241         Reg = TRI->getSubReg(Reg, SystemZ::SUBREG_EVEN);
242       else if (strncmp(Modifier + 7, "odd", 3) == 0)
243         Reg = TRI->getSubReg(Reg, SystemZ::SUBREG_ODD);
244       else
245         assert(0 && "Invalid subreg modifier");
246     }
247
248     O << '%' << TRI->getAsmName(Reg);
249     return;
250   }
251   case MachineOperand::MO_Immediate:
252     O << MO.getImm();
253     return;
254   case MachineOperand::MO_MachineBasicBlock:
255     printBasicBlockLabel(MO.getMBB());
256     return;
257   case MachineOperand::MO_JumpTableIndex:
258     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
259       << MO.getIndex();
260
261     return;
262   case MachineOperand::MO_ConstantPoolIndex:
263     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
264       << MO.getIndex();
265
266     printOffset(MO.getOffset());
267     break;
268   case MachineOperand::MO_GlobalAddress: {
269     const GlobalValue *GV = MO.getGlobal();
270     std::string Name = Mang->getMangledName(GV);
271
272     O << Name;
273     break;
274   }
275   case MachineOperand::MO_ExternalSymbol: {
276     std::string Name(TAI->getGlobalPrefix());
277     Name += MO.getSymbolName();
278     O << Name;
279     break;
280   }
281   default:
282     assert(0 && "Not implemented yet!");
283   }
284
285   switch (MO.getTargetFlags()) {
286   default:
287     llvm_unreachable("Unknown target flag on GV operand");
288   case SystemZII::MO_NO_FLAG:
289     break;
290   case SystemZII::MO_GOTENT:    O << "@GOTENT";    break;
291   case SystemZII::MO_PLT:       O << "@PLT";       break;
292   }
293
294   printOffset(MO.getOffset());
295 }
296
297 void SystemZAsmPrinter::printRIAddrOperand(const MachineInstr *MI, int OpNum,
298                                            const char* Modifier) {
299   const MachineOperand &Base = MI->getOperand(OpNum);
300
301   // Print displacement operand.
302   printOperand(MI, OpNum+1);
303
304   // Print base operand (if any)
305   if (Base.getReg()) {
306     O << '(';
307     printOperand(MI, OpNum);
308     O << ')';
309   }
310 }
311
312 void SystemZAsmPrinter::printRRIAddrOperand(const MachineInstr *MI, int OpNum,
313                                             const char* Modifier) {
314   const MachineOperand &Base = MI->getOperand(OpNum);
315   const MachineOperand &Index = MI->getOperand(OpNum+2);
316
317   // Print displacement operand.
318   printOperand(MI, OpNum+1);
319
320   // Print base operand (if any)
321   if (Base.getReg()) {
322     O << '(';
323     printOperand(MI, OpNum);
324     if (Index.getReg()) {
325       O << ',';
326       printOperand(MI, OpNum+2);
327     }
328     O << ')';
329   } else
330     assert(!Index.getReg() && "Should allocate base register first!");
331 }
332
333 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
334 /// Don't print things like \\n or \\0.
335 static void PrintUnmangledNameSafely(const Value *V, formatted_raw_ostream &OS) {
336   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
337        Name != E; ++Name)
338     if (isprint(*Name))
339       OS << *Name;
340 }
341
342 void SystemZAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
343   const TargetData *TD = TM.getTargetData();
344
345   if (!GVar->hasInitializer())
346     return;   // External global require no code
347
348   // Check to see if this is a special global used by LLVM, if so, emit it.
349   if (EmitSpecialLLVMGlobal(GVar))
350     return;
351
352   std::string name = Mang->getMangledName(GVar);
353   Constant *C = GVar->getInitializer();
354   unsigned Size = TD->getTypeAllocSize(C->getType());
355   unsigned Align = std::max(1U, TD->getPreferredAlignmentLog(GVar));
356
357   printVisibility(name, GVar->getVisibility());
358
359   O << "\t.type\t" << name << ",@object\n";
360
361   SwitchToSection(TAI->SectionForGlobal(GVar));
362
363   if (C->isNullValue() && !GVar->hasSection() &&
364       !GVar->isThreadLocal() &&
365       (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
366
367     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
368
369     if (GVar->hasLocalLinkage())
370       O << "\t.local\t" << name << '\n';
371
372     O << TAI->getCOMMDirective()  << name << ',' << Size;
373     if (TAI->getCOMMDirectiveTakesAlignment())
374       O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
375
376     if (VerboseAsm) {
377       O << "\t\t" << TAI->getCommentString() << ' ';
378       PrintUnmangledNameSafely(GVar, O);
379     }
380     O << '\n';
381     return;
382   }
383
384   switch (GVar->getLinkage()) {
385   case GlobalValue::CommonLinkage:
386   case GlobalValue::LinkOnceAnyLinkage:
387   case GlobalValue::LinkOnceODRLinkage:
388   case GlobalValue::WeakAnyLinkage:
389   case GlobalValue::WeakODRLinkage:
390     O << "\t.weak\t" << name << '\n';
391     break;
392   case GlobalValue::DLLExportLinkage:
393   case GlobalValue::AppendingLinkage:
394     // FIXME: appending linkage variables should go into a section of
395     // their name or something.  For now, just emit them as external.
396   case GlobalValue::ExternalLinkage:
397     // If external or appending, declare as a global symbol
398     O << "\t.globl " << name << '\n';
399     // FALL THROUGH
400   case GlobalValue::PrivateLinkage:
401   case GlobalValue::LinkerPrivateLinkage:
402   case GlobalValue::InternalLinkage:
403      break;
404   default:
405     assert(0 && "Unknown linkage type!");
406   }
407
408   // Use 16-bit alignment by default to simplify bunch of stuff
409   EmitAlignment(Align, GVar, 1);
410   O << name << ":";
411   if (VerboseAsm) {
412     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
413     PrintUnmangledNameSafely(GVar, O);
414   }
415   O << '\n';
416   if (TAI->hasDotTypeDotSizeDirective())
417     O << "\t.size\t" << name << ", " << Size << '\n';
418
419   EmitGlobalConstant(C);
420 }
421
422 // Force static initialization.
423 extern "C" void LLVMInitializeSystemZAsmPrinter() {
424   TargetRegistry::RegisterAsmPrinter(TheSystemZTarget,
425                                      createSystemZCodePrinterPass);
426 }