Register AsmPrinter for XCore, MSP430, and PIC16 targets.
[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/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <algorithm>
39 #include <cctype>
40 using namespace llvm;
41
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43
44 static cl::opt<unsigned> MaxThreads("xcore-max-threads", cl::Optional,
45   cl::desc("Maximum number of threads (for emulation thread-local storage)"),
46   cl::Hidden,
47   cl::value_desc("number"),
48   cl::init(8));
49
50 namespace {
51   class VISIBILITY_HIDDEN XCoreAsmPrinter : public AsmPrinter {
52     DwarfWriter *DW;
53     const XCoreSubtarget &Subtarget;
54   public:
55     explicit XCoreAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
56                              const TargetAsmInfo *T, bool V)
57       : AsmPrinter(O, TM, T, V), DW(0),
58       Subtarget(TM.getSubtarget<XCoreSubtarget>()) {}
59
60     virtual const char *getPassName() const {
61       return "XCore Assembly Printer";
62     }
63
64     void printMemOperand(const MachineInstr *MI, int opNum);
65     void printOperand(const MachineInstr *MI, int opNum);
66     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
67                         unsigned AsmVariant, const char *ExtraCode);
68
69     void emitGlobalDirective(const std::string &name);
70     void emitExternDirective(const std::string &name);
71     
72     void emitArrayBound(const std::string &name, const GlobalVariable *GV);
73     void emitGlobal(const GlobalVariable *GV);
74
75     void emitFunctionStart(MachineFunction &MF);
76     void emitFunctionEnd(MachineFunction &MF);
77
78     bool printInstruction(const MachineInstr *MI);  // autogenerated.
79     void printMachineInstruction(const MachineInstr *MI);
80     bool runOnMachineFunction(MachineFunction &F);
81     bool doInitialization(Module &M);
82     bool doFinalization(Module &M);
83     
84     void getAnalysisUsage(AnalysisUsage &AU) const {
85       AsmPrinter::getAnalysisUsage(AU);
86       AU.setPreservesAll();
87       AU.addRequired<MachineModuleInfo>();
88       AU.addRequired<DwarfWriter>();
89     }
90   };
91 } // end of anonymous namespace
92
93 #include "XCoreGenAsmWriter.inc"
94
95 /// createXCoreCodePrinterPass - Returns a pass that prints the XCore
96 /// assembly code for a MachineFunction to the given output stream,
97 /// using the given target machine description.  This should work
98 /// regardless of whether the function is in SSA form.
99 ///
100 FunctionPass *llvm::createXCoreCodePrinterPass(formatted_raw_ostream &o,
101                                                TargetMachine &tm,
102                                                bool verbose) {
103   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
104 }
105
106 void XCoreAsmPrinter::
107 emitGlobalDirective(const std::string &name)
108 {
109   O << TAI->getGlobalDirective() << name;
110   O << "\n";
111 }
112
113 void XCoreAsmPrinter::
114 emitExternDirective(const std::string &name)
115 {
116   O << "\t.extern\t" << name;
117   O << '\n';
118 }
119
120 void XCoreAsmPrinter::
121 emitArrayBound(const std::string &name, const GlobalVariable *GV)
122 {
123   assert(((GV->hasExternalLinkage() ||
124     GV->hasWeakLinkage()) ||
125     GV->hasLinkOnceLinkage()) && "Unexpected linkage");
126   if (const ArrayType *ATy = dyn_cast<ArrayType>(
127     cast<PointerType>(GV->getType())->getElementType()))
128   {
129     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
130     O << TAI->getSetDirective() << name << ".globound" << ","
131       << ATy->getNumElements() << "\n";
132     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
133       // TODO Use COMDAT groups for LinkOnceLinkage
134       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
135     }
136   }
137 }
138
139 void XCoreAsmPrinter::
140 emitGlobal(const GlobalVariable *GV)
141 {
142   const TargetData *TD = TM.getTargetData();
143
144   if (GV->hasInitializer()) {
145     // Check to see if this is a special global used by LLVM, if so, emit it.
146     if (EmitSpecialLLVMGlobal(GV))
147       return;
148
149     SwitchToSection(TAI->SectionForGlobal(GV));
150     
151     std::string name = Mang->getMangledName(GV);
152     Constant *C = GV->getInitializer();
153     unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
154     
155     // Mark the start of the global
156     O << "\t.cc_top " << name << ".data," << name << "\n";
157
158     switch (GV->getLinkage()) {
159     case GlobalValue::AppendingLinkage:
160       llvm_report_error("AppendingLinkage is not supported by this target!");
161     case GlobalValue::LinkOnceAnyLinkage:
162     case GlobalValue::LinkOnceODRLinkage:
163     case GlobalValue::WeakAnyLinkage:
164     case GlobalValue::WeakODRLinkage:
165     case GlobalValue::ExternalLinkage:
166       emitArrayBound(name, GV);
167       emitGlobalDirective(name);
168       // TODO Use COMDAT groups for LinkOnceLinkage
169       if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
170         O << TAI->getWeakDefDirective() << name << "\n";
171       }
172       // FALL THROUGH
173     case GlobalValue::InternalLinkage:
174     case GlobalValue::PrivateLinkage:
175       break;
176     case GlobalValue::GhostLinkage:
177       llvm_unreachable("Should not have any unmaterialized functions!");
178     case GlobalValue::DLLImportLinkage:
179       llvm_unreachable("DLLImport linkage is not supported by this target!");
180     case GlobalValue::DLLExportLinkage:
181       llvm_unreachable("DLLExport linkage is not supported by this target!");
182     default:
183       llvm_unreachable("Unknown linkage type!");
184     }
185
186     EmitAlignment(Align, GV, 2);
187     
188     unsigned Size = TD->getTypeAllocSize(C->getType());
189     if (GV->isThreadLocal()) {
190       Size *= MaxThreads;
191     }
192     if (TAI->hasDotTypeDotSizeDirective()) {
193       O << "\t.type " << name << ",@object\n";
194       O << "\t.size " << name << "," << Size << "\n";
195     }
196     O << name << ":\n";
197     
198     EmitGlobalConstant(C);
199     if (GV->isThreadLocal()) {
200       for (unsigned i = 1; i < MaxThreads; ++i) {
201         EmitGlobalConstant(C);
202       }
203     }
204     if (Size < 4) {
205       // The ABI requires that unsigned scalar types smaller than 32 bits
206       // are are padded to 32 bits.
207       EmitZeros(4 - Size);
208     }
209     
210     // Mark the end of the global
211     O << "\t.cc_bottom " << name << ".data\n";
212   }
213 }
214
215 /// Emit the directives on the start of functions
216 void XCoreAsmPrinter::
217 emitFunctionStart(MachineFunction &MF)
218 {
219   // Print out the label for the function.
220   const Function *F = MF.getFunction();
221
222   SwitchToSection(TAI->SectionForGlobal(F));
223   
224   // Mark the start of the function
225   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
226
227   switch (F->getLinkage()) {
228   default: llvm_unreachable("Unknown linkage type!");
229   case Function::InternalLinkage:  // Symbols default to internal.
230   case Function::PrivateLinkage:
231     break;
232   case Function::ExternalLinkage:
233     emitGlobalDirective(CurrentFnName);
234     break;
235   case Function::LinkOnceAnyLinkage:
236   case Function::LinkOnceODRLinkage:
237   case Function::WeakAnyLinkage:
238   case Function::WeakODRLinkage:
239     // TODO Use COMDAT groups for LinkOnceLinkage
240     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
241     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
242     break;
243   }
244   // (1 << 1) byte aligned
245   EmitAlignment(MF.getAlignment(), F, 1);
246   if (TAI->hasDotTypeDotSizeDirective()) {
247     O << "\t.type " << CurrentFnName << ",@function\n";
248   }
249   O << CurrentFnName << ":\n";
250 }
251
252 /// Emit the directives on the end of functions
253 void XCoreAsmPrinter::
254 emitFunctionEnd(MachineFunction &MF) 
255 {
256   // Mark the end of the function
257   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
258 }
259
260 /// runOnMachineFunction - This uses the printMachineInstruction()
261 /// method to print assembly for each instruction.
262 ///
263 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
264 {
265   this->MF = &MF;
266
267   SetupMachineFunction(MF);
268
269   // Print out constants referenced by the function
270   EmitConstantPool(MF.getConstantPool());
271
272   // Print out jump tables referenced by the function
273   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
274
275   // Emit the function start directives
276   emitFunctionStart(MF);
277   
278   // Emit pre-function debug information.
279   DW->BeginFunction(&MF);
280
281   // Print out code for the function.
282   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
283        I != E; ++I) {
284
285     // Print a label for the basic block.
286     if (I != MF.begin()) {
287       printBasicBlockLabel(I, true , true);
288       O << '\n';
289     }
290
291     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
292          II != E; ++II) {
293       // Print the assembly for the instruction.
294       O << "\t";
295       printMachineInstruction(II);
296     }
297
298     // Each Basic Block is separated by a newline
299     O << '\n';
300   }
301
302   // Emit function end directives
303   emitFunctionEnd(MF);
304   
305   // Emit post-function debug information.
306   DW->EndFunction(&MF);
307
308   // We didn't modify anything.
309   return false;
310 }
311
312 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
313 {
314   printOperand(MI, opNum);
315   
316   if (MI->getOperand(opNum+1).isImm()
317     && MI->getOperand(opNum+1).getImm() == 0)
318     return;
319   
320   O << "+";
321   printOperand(MI, opNum+1);
322 }
323
324 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
325   const MachineOperand &MO = MI->getOperand(opNum);
326   switch (MO.getType()) {
327   case MachineOperand::MO_Register:
328     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
329       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
330     else
331       llvm_unreachable("not implemented");
332     break;
333   case MachineOperand::MO_Immediate:
334     O << MO.getImm();
335     break;
336   case MachineOperand::MO_MachineBasicBlock:
337     printBasicBlockLabel(MO.getMBB());
338     break;
339   case MachineOperand::MO_GlobalAddress:
340     O << Mang->getMangledName(MO.getGlobal());
341     break;
342   case MachineOperand::MO_ExternalSymbol:
343     O << MO.getSymbolName();
344     break;
345   case MachineOperand::MO_ConstantPoolIndex:
346     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
347       << '_' << MO.getIndex();
348     break;
349   case MachineOperand::MO_JumpTableIndex:
350     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
351       << '_' << MO.getIndex();
352     break;
353   default:
354     llvm_unreachable("not implemented");
355   }
356 }
357
358 /// PrintAsmOperand - Print out an operand for an inline asm expression.
359 ///
360 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
361                                       unsigned AsmVariant, 
362                                       const char *ExtraCode) {
363   printOperand(MI, OpNo);
364   return false;
365 }
366
367 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
368   ++EmittedInsts;
369
370   // Check for mov mnemonic
371   unsigned src, dst, srcSR, dstSR;
372   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst, srcSR, dstSR)) {
373     O << "\tmov ";
374     O << TM.getRegisterInfo()->get(dst).AsmName;
375     O << ", ";
376     O << TM.getRegisterInfo()->get(src).AsmName;
377     O << "\n";
378     return;
379   }
380   if (printInstruction(MI)) {
381     return;
382   }
383   llvm_unreachable("Unhandled instruction in asm writer!");
384 }
385
386 bool XCoreAsmPrinter::doInitialization(Module &M) {
387   bool Result = AsmPrinter::doInitialization(M);
388   DW = getAnalysisIfAvailable<DwarfWriter>();
389   
390   return Result;
391 }
392
393 bool XCoreAsmPrinter::doFinalization(Module &M) {
394
395   // Print out module-level global variables.
396   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
397        I != E; ++I) {
398     emitGlobal(I);
399   }
400   
401   return AsmPrinter::doFinalization(M);
402 }