Convert DwarfWriter into a pass.
[oota-llvm.git] / lib / Target / XCore / XCoreAsmPrinter.cpp
1 //===-- XCoreAsmPrinter.cpp - XCore 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 XAS-format XCore assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "XCore.h"
17 #include "XCoreInstrInfo.h"
18 #include "XCoreSubtarget.h"
19 #include "XCoreTargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cctype>
39 using namespace llvm;
40
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
42
43 static cl::opt<std::string> FileDirective("xcore-file-directive", cl::Optional,
44   cl::desc("Output a file directive into the assembly file"),
45   cl::Hidden,
46   cl::value_desc("filename"),
47   cl::init(""));
48
49 static cl::opt<unsigned> MaxThreads("xcore-max-threads", cl::Optional,
50   cl::desc("Maximum number of threads (for emulation thread-local storage)"),
51   cl::Hidden,
52   cl::value_desc("number"),
53   cl::init(8));
54
55 namespace {
56   struct VISIBILITY_HIDDEN XCoreAsmPrinter : public AsmPrinter {
57     XCoreAsmPrinter(raw_ostream &O, XCoreTargetMachine &TM,
58                     const TargetAsmInfo *T)
59       : AsmPrinter(O, TM, T), DW(0),
60         Subtarget(*TM.getSubtargetImpl()) { }
61
62     DwarfWriter *DW;
63     const XCoreSubtarget &Subtarget;
64
65     virtual const char *getPassName() const {
66       return "XCore Assembly Printer";
67     }
68
69     void printMemOperand(const MachineInstr *MI, int opNum);
70     void printOperand(const MachineInstr *MI, int opNum);
71     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
72                         unsigned AsmVariant, const char *ExtraCode);
73     
74     void emitFileDirective(const std::string &filename);
75     void emitGlobalDirective(const std::string &name);
76     void emitExternDirective(const std::string &name);
77     
78     void emitArrayBound(const std::string &name, const GlobalVariable *GV);
79     void emitGlobal(const GlobalVariable *GV);
80
81     void emitFunctionStart(MachineFunction &MF);
82     void emitFunctionEnd(MachineFunction &MF);
83
84     bool printInstruction(const MachineInstr *MI);  // autogenerated.
85     void printMachineInstruction(const MachineInstr *MI);
86     bool runOnMachineFunction(MachineFunction &F);
87     bool doInitialization(Module &M);
88     bool doFinalization(Module &M);
89     
90     void getAnalysisUsage(AnalysisUsage &AU) const {
91       AsmPrinter::getAnalysisUsage(AU);
92       AU.setPreservesAll();
93       AU.addRequired<MachineModuleInfo>();
94       AU.addRequired<DwarfWriter>();
95     }
96   };
97 } // end of anonymous namespace
98
99 #include "XCoreGenAsmWriter.inc"
100
101 /// createXCoreCodePrinterPass - Returns a pass that prints the XCore
102 /// assembly code for a MachineFunction to the given output stream,
103 /// using the given target machine description.  This should work
104 /// regardless of whether the function is in SSA form.
105 ///
106 FunctionPass *llvm::createXCoreCodePrinterPass(raw_ostream &o,
107                                                XCoreTargetMachine &tm) {
108   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo());
109 }
110
111 // PrintEscapedString - Print each character of the specified string, escaping
112 // it if it is not printable or if it is an escape char.
113 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
114   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
115     unsigned char C = Str[i];
116     if (isprint(C) && C != '"' && C != '\\') {
117       Out << C;
118     } else {
119       Out << '\\'
120           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
121           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
122     }
123   }
124 }
125
126 void XCoreAsmPrinter::
127 emitFileDirective(const std::string &name)
128 {
129   O << "\t.file\t\"";
130   PrintEscapedString(name, O);
131   O << "\"\n";
132 }
133
134 void XCoreAsmPrinter::
135 emitGlobalDirective(const std::string &name)
136 {
137   O << TAI->getGlobalDirective() << name;
138   O << "\n";
139 }
140
141 void XCoreAsmPrinter::
142 emitExternDirective(const std::string &name)
143 {
144   O << "\t.extern\t" << name;
145   O << '\n';
146 }
147
148 void XCoreAsmPrinter::
149 emitArrayBound(const std::string &name, const GlobalVariable *GV)
150 {
151   assert(((GV->hasExternalLinkage() ||
152     GV->hasWeakLinkage()) ||
153     GV->hasLinkOnceLinkage()) && "Unexpected linkage");
154   if (const ArrayType *ATy = dyn_cast<ArrayType>(
155     cast<PointerType>(GV->getType())->getElementType()))
156   {
157     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
158     O << TAI->getSetDirective() << name << ".globound" << ","
159       << ATy->getNumElements() << "\n";
160     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
161       // TODO Use COMDAT groups for LinkOnceLinkage
162       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
163     }
164   }
165 }
166
167 void XCoreAsmPrinter::
168 emitGlobal(const GlobalVariable *GV)
169 {
170   const TargetData *TD = TM.getTargetData();
171
172   if (GV->hasInitializer()) {
173     // Check to see if this is a special global used by LLVM, if so, emit it.
174     if (EmitSpecialLLVMGlobal(GV))
175       return;
176
177     SwitchToSection(TAI->SectionForGlobal(GV));
178     
179     std::string name = Mang->getValueName(GV);
180     Constant *C = GV->getInitializer();
181     unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
182     
183     // Mark the start of the global
184     O << "\t.cc_top " << name << ".data," << name << "\n";
185
186     switch (GV->getLinkage()) {
187     case GlobalValue::AppendingLinkage:
188       cerr << "AppendingLinkage is not supported by this target!\n";
189       abort();
190     case GlobalValue::LinkOnceLinkage:
191     case GlobalValue::WeakLinkage:
192     case GlobalValue::ExternalLinkage:
193       emitArrayBound(name, GV);
194       emitGlobalDirective(name);
195       // TODO Use COMDAT groups for LinkOnceLinkage
196       if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
197         O << TAI->getWeakDefDirective() << name << "\n";
198       }
199       // FALL THROUGH
200     case GlobalValue::InternalLinkage:
201       break;
202     case GlobalValue::GhostLinkage:
203       cerr << "Should not have any unmaterialized functions!\n";
204       abort();
205     case GlobalValue::DLLImportLinkage:
206       cerr << "DLLImport linkage is not supported by this target!\n";
207       abort();
208     case GlobalValue::DLLExportLinkage:
209       cerr << "DLLExport linkage is not supported by this target!\n";
210       abort();
211     default:
212       assert(0 && "Unknown linkage type!");
213     }
214
215     EmitAlignment(Align, GV, 2);
216     
217     unsigned Size = TD->getABITypeSize(C->getType());
218     if (GV->isThreadLocal()) {
219       Size *= MaxThreads;
220     }
221     if (TAI->hasDotTypeDotSizeDirective()) {
222       O << "\t.type " << name << ",@object\n";
223       O << "\t.size " << name << "," << Size << "\n";
224     }
225     O << name << ":\n";
226     
227     EmitGlobalConstant(C);
228     if (GV->isThreadLocal()) {
229       for (unsigned i = 1; i < MaxThreads; ++i) {
230         EmitGlobalConstant(C);
231       }
232     }
233     if (Size < 4) {
234       // The ABI requires that unsigned scalar types smaller than 32 bits
235       // are are padded to 32 bits.
236       EmitZeros(4 - Size);
237     }
238     
239     // Mark the end of the global
240     O << "\t.cc_bottom " << name << ".data\n";
241   } else {
242     if (GV->hasExternalWeakLinkage())
243       ExtWeakSymbols.insert(GV);
244   }
245 }
246
247 /// Emit the directives on the start of functions
248 void XCoreAsmPrinter::
249 emitFunctionStart(MachineFunction &MF)
250 {
251   // Print out the label for the function.
252   const Function *F = MF.getFunction();
253
254   SwitchToSection(TAI->SectionForGlobal(F));
255   
256   // Mark the start of the function
257   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
258
259   switch (F->getLinkage()) {
260   default: assert(0 && "Unknown linkage type!");
261   case Function::InternalLinkage:  // Symbols default to internal.
262     break;
263   case Function::ExternalLinkage:
264     emitGlobalDirective(CurrentFnName);
265     break;
266   case Function::LinkOnceLinkage:
267   case Function::WeakLinkage:
268     // TODO Use COMDAT groups for LinkOnceLinkage
269     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
270     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
271     break;
272   }
273   // (1 << 1) byte aligned
274   EmitAlignment(1, F, 1);
275   if (TAI->hasDotTypeDotSizeDirective()) {
276     O << "\t.type " << CurrentFnName << ",@function\n";
277   }
278   O << CurrentFnName << ":\n";
279 }
280
281 /// Emit the directives on the end of functions
282 void XCoreAsmPrinter::
283 emitFunctionEnd(MachineFunction &MF) 
284 {
285   // Mark the end of the function
286   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
287 }
288
289 /// runOnMachineFunction - This uses the printMachineInstruction()
290 /// method to print assembly for each instruction.
291 ///
292 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
293 {
294   SetupMachineFunction(MF);
295
296   // Print out constants referenced by the function
297   EmitConstantPool(MF.getConstantPool());
298
299   // Print out jump tables referenced by the function
300   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
301
302   // What's my mangled name?
303   CurrentFnName = Mang->getValueName(MF.getFunction());
304
305   // Emit the function start directives
306   emitFunctionStart(MF);
307   
308   // Emit pre-function debug information.
309   DW->BeginFunction(&MF);
310
311   // Print out code for the function.
312   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
313        I != E; ++I) {
314
315     // Print a label for the basic block.
316     if (I != MF.begin()) {
317       printBasicBlockLabel(I, true , true);
318       O << '\n';
319     }
320
321     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
322          II != E; ++II) {
323       // Print the assembly for the instruction.
324       O << "\t";
325       printMachineInstruction(II);
326     }
327
328     // Each Basic Block is separated by a newline
329     O << '\n';
330   }
331
332   // Emit function end directives
333   emitFunctionEnd(MF);
334   
335   // Emit post-function debug information.
336   DW->EndFunction(&MF);
337
338   // We didn't modify anything.
339   return false;
340 }
341
342 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
343 {
344   printOperand(MI, opNum);
345   
346   if (MI->getOperand(opNum+1).isImm()
347     && MI->getOperand(opNum+1).getImm() == 0)
348     return;
349   
350   O << "+";
351   printOperand(MI, opNum+1);
352 }
353
354 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
355   const MachineOperand &MO = MI->getOperand(opNum);
356   switch (MO.getType()) {
357   case MachineOperand::MO_Register:
358     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
359       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
360     else
361       assert(0 && "not implemented");
362     break;
363   case MachineOperand::MO_Immediate:
364     O << MO.getImm();
365     break;
366   case MachineOperand::MO_MachineBasicBlock:
367     printBasicBlockLabel(MO.getMBB());
368     break;
369   case MachineOperand::MO_GlobalAddress:
370     O << Mang->getValueName(MO.getGlobal());
371     if (MO.getGlobal()->hasExternalWeakLinkage())
372       ExtWeakSymbols.insert(MO.getGlobal());
373     break;
374   case MachineOperand::MO_ExternalSymbol:
375     O << MO.getSymbolName();
376     break;
377   case MachineOperand::MO_ConstantPoolIndex:
378     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
379       << '_' << MO.getIndex();
380     break;
381   case MachineOperand::MO_JumpTableIndex:
382     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
383       << '_' << MO.getIndex();
384     break;
385   default:
386     assert(0 && "not implemented");
387   }
388 }
389
390 /// PrintAsmOperand - Print out an operand for an inline asm expression.
391 ///
392 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
393                                       unsigned AsmVariant, 
394                                       const char *ExtraCode) {
395   printOperand(MI, OpNo);
396   return false;
397 }
398
399 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
400   ++EmittedInsts;
401
402   // Check for mov mnemonic
403   unsigned src, dst;
404   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst)) {
405     O << "\tmov ";
406     O << TM.getRegisterInfo()->get(dst).AsmName;
407     O << ", ";
408     O << TM.getRegisterInfo()->get(src).AsmName;
409     O << "\n";
410     return;
411   }
412   if (printInstruction(MI)) {
413     return;
414   }
415   assert(0 && "Unhandled instruction in asm writer!");
416 }
417
418 bool XCoreAsmPrinter::doInitialization(Module &M) {
419   bool Result = AsmPrinter::doInitialization(M);
420   
421   if (!FileDirective.empty()) {
422     emitFileDirective(FileDirective);
423   }
424   
425   // Print out type strings for external functions here
426   for (Module::const_iterator I = M.begin(), E = M.end();
427        I != E; ++I) {
428     if (I->isDeclaration() && !I->isIntrinsic()) {
429       switch (I->getLinkage()) {
430       default:
431         assert(0 && "Unexpected linkage");
432       case Function::ExternalWeakLinkage:
433         ExtWeakSymbols.insert(I);
434         // fallthrough
435       case Function::ExternalLinkage:
436         break;
437       }
438     }
439   }
440
441   // Emit initial debug information.
442   DW = getAnalysisToUpdate<DwarfWriter>();
443   assert(DW && "Dwarf Writer is not available");
444   DW->BeginModule(&M, getAnalysisToUpdate<MachineModuleInfo>(), 
445                   O, this, TAI);
446   return Result;
447 }
448
449 bool XCoreAsmPrinter::doFinalization(Module &M) {
450
451   // Print out module-level global variables.
452   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
453        I != E; ++I) {
454     emitGlobal(I);
455   }
456   
457   // Emit final debug information.
458   DW->EndModule();
459
460   return AsmPrinter::doFinalization(M);
461 }