Implement 'large' PIC model
[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/ADT/Statistic.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 using namespace llvm;
36
37 STATISTIC(EmittedInsts, "Number of machine instrs printed");
38
39 namespace {
40   class VISIBILITY_HIDDEN SystemZAsmPrinter : public AsmPrinter {
41   public:
42     SystemZAsmPrinter(raw_ostream &O, SystemZTargetMachine &TM,
43                      const TargetAsmInfo *TAI,
44                      CodeGenOpt::Level OL, bool V)
45       : AsmPrinter(O, TM, TAI, OL, 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(raw_ostream &o,
89                                                 SystemZTargetMachine &tm,
90                                                 CodeGenOpt::Level OptLevel,
91                                                 bool verbose) {
92   return new SystemZAsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, verbose);
93 }
94
95 bool SystemZAsmPrinter::doInitialization(Module &M) {
96   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
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   const Function *F = MF.getFunction();
112
113   SwitchToSection(TAI->SectionForGlobal(F));
114
115   unsigned FnAlign = 4;
116   if (F->hasFnAttr(Attribute::OptimizeForSize))
117     FnAlign = 1;
118
119   EmitAlignment(FnAlign, F);
120
121   switch (F->getLinkage()) {
122   default: assert(0 && "Unknown linkage type!");
123   case Function::InternalLinkage:  // Symbols default to internal.
124   case Function::PrivateLinkage:
125     break;
126   case Function::ExternalLinkage:
127     O << "\t.globl\t" << CurrentFnName << '\n';
128     break;
129   case Function::LinkOnceAnyLinkage:
130   case Function::LinkOnceODRLinkage:
131   case Function::WeakAnyLinkage:
132   case Function::WeakODRLinkage:
133     O << "\t.weak\t" << CurrentFnName << '\n';
134     break;
135   }
136
137   printVisibility(CurrentFnName, F->getVisibility());
138
139   O << "\t.type\t" << CurrentFnName << ",@function\n"
140     << CurrentFnName << ":\n";
141 }
142
143 bool SystemZAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
144   SetupMachineFunction(MF);
145   O << "\n\n";
146
147   // Print the 'header' of function
148   emitFunctionHeader(MF);
149
150   // Print out code for the function.
151   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
152        I != E; ++I) {
153     // Print a label for the basic block.
154     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
155       // This is an entry block or a block that's only reachable via a
156       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
157     } else {
158       printBasicBlockLabel(I, true, true, VerboseAsm);
159       O << '\n';
160     }
161
162     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
163          II != E; ++II)
164       // Print the assembly for the instruction.
165       printMachineInstruction(II);
166   }
167
168   if (TAI->hasDotTypeDotSizeDirective())
169     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
170
171   // Print out jump tables referenced by the function.
172   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
173
174   O.flush();
175
176   // We didn't modify anything
177   return false;
178 }
179
180 void SystemZAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
181   ++EmittedInsts;
182
183   // Call the autogenerated instruction printer routines.
184   if (printInstruction(MI))
185     return;
186
187   assert(0 && "Should not happen");
188 }
189
190 void SystemZAsmPrinter::printPCRelImmOperand(const MachineInstr *MI, int OpNum) {
191   const MachineOperand &MO = MI->getOperand(OpNum);
192   switch (MO.getType()) {
193   case MachineOperand::MO_GlobalAddress: {
194     const GlobalValue *GV = MO.getGlobal();
195     std::string Name = Mang->getValueName(GV);
196
197     O << Name;
198
199     // Assemble calls via PLT for externally visible symbols if PIC.
200     if (TM.getRelocationModel() == Reloc::PIC_ &&
201         !GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
202         !GV->hasLocalLinkage())
203       O << "@PLT";
204
205     printOffset(MO.getOffset());
206     return;
207   }
208   case MachineOperand::MO_ExternalSymbol: {
209     std::string Name(TAI->getGlobalPrefix());
210     Name += MO.getSymbolName();
211     O << Name;
212
213     if (TM.getRelocationModel() == Reloc::PIC_)
214       O << "@PLT";
215
216     return;
217   }
218   default:
219     assert(0 && "Not implemented yet!");
220   }
221 }
222
223
224 void SystemZAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
225                                      const char* Modifier) {
226   const MachineOperand &MO = MI->getOperand(OpNum);
227   switch (MO.getType()) {
228   case MachineOperand::MO_Register: {
229     assert (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
230             "Virtual registers should be already mapped!");
231     unsigned Reg = MO.getReg();
232     if (Modifier && strncmp(Modifier, "subreg", 6) == 0) {
233       if (strncmp(Modifier + 7, "even", 4) == 0)
234         Reg = TRI->getSubReg(Reg, SystemZ::SUBREG_EVEN);
235       else if (strncmp(Modifier + 7, "odd", 3) == 0)
236         Reg = TRI->getSubReg(Reg, SystemZ::SUBREG_ODD);
237       else
238         assert(0 && "Invalid subreg modifier");
239     }
240
241     O << '%' << TRI->getAsmName(Reg);
242     return;
243   }
244   case MachineOperand::MO_Immediate:
245     O << MO.getImm();
246     return;
247   case MachineOperand::MO_MachineBasicBlock:
248     printBasicBlockLabel(MO.getMBB());
249     return;
250   case MachineOperand::MO_JumpTableIndex:
251     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
252       << MO.getIndex();
253
254     return;
255   case MachineOperand::MO_GlobalAddress: {
256     const GlobalValue *GV = MO.getGlobal();
257     std::string Name = Mang->getValueName(GV);
258
259     O << Name;
260     break;
261   }
262   case MachineOperand::MO_ExternalSymbol: {
263     std::string Name(TAI->getGlobalPrefix());
264     Name += MO.getSymbolName();
265     O << Name;
266     break;
267   }
268   default:
269     assert(0 && "Not implemented yet!");
270   }
271
272   switch (MO.getTargetFlags()) {
273   default:
274     assert(0 && "Unknown target flag on GV operand");
275   case SystemZII::MO_NO_FLAG:
276     break;
277   case SystemZII::MO_GOTENT:    O << "@GOTENT";    break;
278   case SystemZII::MO_PLT:       O << "@PLT";       break;
279   }
280
281   printOffset(MO.getOffset());
282 }
283
284 void SystemZAsmPrinter::printRIAddrOperand(const MachineInstr *MI, int OpNum,
285                                            const char* Modifier) {
286   const MachineOperand &Base = MI->getOperand(OpNum);
287
288   // Print displacement operand.
289   printOperand(MI, OpNum+1);
290
291   // Print base operand (if any)
292   if (Base.getReg()) {
293     O << '(';
294     printOperand(MI, OpNum);
295     O << ')';
296   }
297 }
298
299 void SystemZAsmPrinter::printRRIAddrOperand(const MachineInstr *MI, int OpNum,
300                                             const char* Modifier) {
301   const MachineOperand &Base = MI->getOperand(OpNum);
302   const MachineOperand &Index = MI->getOperand(OpNum+2);
303
304   // Print displacement operand.
305   printOperand(MI, OpNum+1);
306
307   // Print base operand (if any)
308   if (Base.getReg()) {
309     O << '(';
310     printOperand(MI, OpNum);
311     if (Index.getReg()) {
312       O << ',';
313       printOperand(MI, OpNum+2);
314     }
315     O << ')';
316   } else
317     assert(!Index.getReg() && "Should allocate base register first!");
318 }
319
320 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
321 /// Don't print things like \\n or \\0.
322 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
323   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
324        Name != E; ++Name)
325     if (isprint(*Name))
326       OS << *Name;
327 }
328
329 void SystemZAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
330   const TargetData *TD = TM.getTargetData();
331
332   if (!GVar->hasInitializer())
333     return;   // External global require no code
334
335   // Check to see if this is a special global used by LLVM, if so, emit it.
336   if (EmitSpecialLLVMGlobal(GVar))
337     return;
338
339   std::string name = Mang->getValueName(GVar);
340   Constant *C = GVar->getInitializer();
341   const Type *Type = C->getType();
342   unsigned Size = TD->getTypeAllocSize(Type);
343   unsigned Align = std::max(1U, TD->getPreferredAlignmentLog(GVar));
344
345   printVisibility(name, GVar->getVisibility());
346
347   O << "\t.type\t" << name << ",@object\n";
348
349   SwitchToSection(TAI->SectionForGlobal(GVar));
350
351   if (C->isNullValue() && !GVar->hasSection() &&
352       !GVar->isThreadLocal() &&
353       (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
354
355     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
356
357     if (GVar->hasLocalLinkage())
358       O << "\t.local\t" << name << '\n';
359
360     O << TAI->getCOMMDirective()  << name << ',' << Size;
361     if (TAI->getCOMMDirectiveTakesAlignment())
362       O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
363
364     if (VerboseAsm) {
365       O << "\t\t" << TAI->getCommentString() << ' ';
366       PrintUnmangledNameSafely(GVar, O);
367     }
368     O << '\n';
369     return;
370   }
371
372   switch (GVar->getLinkage()) {
373   case GlobalValue::CommonLinkage:
374   case GlobalValue::LinkOnceAnyLinkage:
375   case GlobalValue::LinkOnceODRLinkage:
376   case GlobalValue::WeakAnyLinkage:
377   case GlobalValue::WeakODRLinkage:
378     O << "\t.weak\t" << name << '\n';
379     break;
380   case GlobalValue::DLLExportLinkage:
381   case GlobalValue::AppendingLinkage:
382     // FIXME: appending linkage variables should go into a section of
383     // their name or something.  For now, just emit them as external.
384   case GlobalValue::ExternalLinkage:
385     // If external or appending, declare as a global symbol
386     O << "\t.globl " << name << '\n';
387     // FALL THROUGH
388   case GlobalValue::PrivateLinkage:
389   case GlobalValue::InternalLinkage:
390      break;
391   default:
392     assert(0 && "Unknown linkage type!");
393   }
394
395   // Use 16-bit alignment by default to simplify bunch of stuff
396   EmitAlignment(Align, GVar, 1);
397   O << name << ":";
398   if (VerboseAsm) {
399     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
400     PrintUnmangledNameSafely(GVar, O);
401   }
402   O << '\n';
403   if (TAI->hasDotTypeDotSizeDirective())
404     O << "\t.size\t" << name << ", " << Size << '\n';
405
406   EmitGlobalConstant(C);
407 }