Remove the xcore-file-directive option now that LLVM has proper support for
[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, XCoreTargetMachine &TM,
56                              const TargetAsmInfo *T, bool V)
57       : AsmPrinter(O, TM, T, V), DW(0),
58         Subtarget(*TM.getSubtargetImpl()) {}
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                                                XCoreTargetMachine &tm,
102                                                bool verbose) {
103   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
104 }
105
106 // PrintEscapedString - Print each character of the specified string, escaping
107 // it if it is not printable or if it is an escape char.
108 static void PrintEscapedString(const std::string &Str,
109                                formatted_raw_ostream &Out) {
110   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
111     unsigned char C = Str[i];
112     if (isprint(C) && C != '"' && C != '\\') {
113       Out << C;
114     } else {
115       Out << '\\'
116           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
117           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
118     }
119   }
120 }
121
122 void XCoreAsmPrinter::
123 emitGlobalDirective(const std::string &name)
124 {
125   O << TAI->getGlobalDirective() << name;
126   O << "\n";
127 }
128
129 void XCoreAsmPrinter::
130 emitExternDirective(const std::string &name)
131 {
132   O << "\t.extern\t" << name;
133   O << '\n';
134 }
135
136 void XCoreAsmPrinter::
137 emitArrayBound(const std::string &name, const GlobalVariable *GV)
138 {
139   assert(((GV->hasExternalLinkage() ||
140     GV->hasWeakLinkage()) ||
141     GV->hasLinkOnceLinkage()) && "Unexpected linkage");
142   if (const ArrayType *ATy = dyn_cast<ArrayType>(
143     cast<PointerType>(GV->getType())->getElementType()))
144   {
145     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
146     O << TAI->getSetDirective() << name << ".globound" << ","
147       << ATy->getNumElements() << "\n";
148     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
149       // TODO Use COMDAT groups for LinkOnceLinkage
150       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
151     }
152   }
153 }
154
155 void XCoreAsmPrinter::
156 emitGlobal(const GlobalVariable *GV)
157 {
158   const TargetData *TD = TM.getTargetData();
159
160   if (GV->hasInitializer()) {
161     // Check to see if this is a special global used by LLVM, if so, emit it.
162     if (EmitSpecialLLVMGlobal(GV))
163       return;
164
165     SwitchToSection(TAI->SectionForGlobal(GV));
166     
167     std::string name = Mang->getMangledName(GV);
168     Constant *C = GV->getInitializer();
169     unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
170     
171     // Mark the start of the global
172     O << "\t.cc_top " << name << ".data," << name << "\n";
173
174     switch (GV->getLinkage()) {
175     case GlobalValue::AppendingLinkage:
176       llvm_report_error("AppendingLinkage is not supported by this target!");
177     case GlobalValue::LinkOnceAnyLinkage:
178     case GlobalValue::LinkOnceODRLinkage:
179     case GlobalValue::WeakAnyLinkage:
180     case GlobalValue::WeakODRLinkage:
181     case GlobalValue::ExternalLinkage:
182       emitArrayBound(name, GV);
183       emitGlobalDirective(name);
184       // TODO Use COMDAT groups for LinkOnceLinkage
185       if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
186         O << TAI->getWeakDefDirective() << name << "\n";
187       }
188       // FALL THROUGH
189     case GlobalValue::InternalLinkage:
190     case GlobalValue::PrivateLinkage:
191       break;
192     case GlobalValue::GhostLinkage:
193       llvm_unreachable("Should not have any unmaterialized functions!");
194     case GlobalValue::DLLImportLinkage:
195       llvm_unreachable("DLLImport linkage is not supported by this target!");
196     case GlobalValue::DLLExportLinkage:
197       llvm_unreachable("DLLExport linkage is not supported by this target!");
198     default:
199       llvm_unreachable("Unknown linkage type!");
200     }
201
202     EmitAlignment(Align, GV, 2);
203     
204     unsigned Size = TD->getTypeAllocSize(C->getType());
205     if (GV->isThreadLocal()) {
206       Size *= MaxThreads;
207     }
208     if (TAI->hasDotTypeDotSizeDirective()) {
209       O << "\t.type " << name << ",@object\n";
210       O << "\t.size " << name << "," << Size << "\n";
211     }
212     O << name << ":\n";
213     
214     EmitGlobalConstant(C);
215     if (GV->isThreadLocal()) {
216       for (unsigned i = 1; i < MaxThreads; ++i) {
217         EmitGlobalConstant(C);
218       }
219     }
220     if (Size < 4) {
221       // The ABI requires that unsigned scalar types smaller than 32 bits
222       // are are padded to 32 bits.
223       EmitZeros(4 - Size);
224     }
225     
226     // Mark the end of the global
227     O << "\t.cc_bottom " << name << ".data\n";
228   }
229 }
230
231 /// Emit the directives on the start of functions
232 void XCoreAsmPrinter::
233 emitFunctionStart(MachineFunction &MF)
234 {
235   // Print out the label for the function.
236   const Function *F = MF.getFunction();
237
238   SwitchToSection(TAI->SectionForGlobal(F));
239   
240   // Mark the start of the function
241   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
242
243   switch (F->getLinkage()) {
244   default: llvm_unreachable("Unknown linkage type!");
245   case Function::InternalLinkage:  // Symbols default to internal.
246   case Function::PrivateLinkage:
247     break;
248   case Function::ExternalLinkage:
249     emitGlobalDirective(CurrentFnName);
250     break;
251   case Function::LinkOnceAnyLinkage:
252   case Function::LinkOnceODRLinkage:
253   case Function::WeakAnyLinkage:
254   case Function::WeakODRLinkage:
255     // TODO Use COMDAT groups for LinkOnceLinkage
256     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
257     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
258     break;
259   }
260   // (1 << 1) byte aligned
261   EmitAlignment(MF.getAlignment(), F, 1);
262   if (TAI->hasDotTypeDotSizeDirective()) {
263     O << "\t.type " << CurrentFnName << ",@function\n";
264   }
265   O << CurrentFnName << ":\n";
266 }
267
268 /// Emit the directives on the end of functions
269 void XCoreAsmPrinter::
270 emitFunctionEnd(MachineFunction &MF) 
271 {
272   // Mark the end of the function
273   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
274 }
275
276 /// runOnMachineFunction - This uses the printMachineInstruction()
277 /// method to print assembly for each instruction.
278 ///
279 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
280 {
281   this->MF = &MF;
282
283   SetupMachineFunction(MF);
284
285   // Print out constants referenced by the function
286   EmitConstantPool(MF.getConstantPool());
287
288   // Print out jump tables referenced by the function
289   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
290
291   // Emit the function start directives
292   emitFunctionStart(MF);
293   
294   // Emit pre-function debug information.
295   DW->BeginFunction(&MF);
296
297   // Print out code for the function.
298   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
299        I != E; ++I) {
300
301     // Print a label for the basic block.
302     if (I != MF.begin()) {
303       printBasicBlockLabel(I, true , true);
304       O << '\n';
305     }
306
307     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
308          II != E; ++II) {
309       // Print the assembly for the instruction.
310       O << "\t";
311       printMachineInstruction(II);
312     }
313
314     // Each Basic Block is separated by a newline
315     O << '\n';
316   }
317
318   // Emit function end directives
319   emitFunctionEnd(MF);
320   
321   // Emit post-function debug information.
322   DW->EndFunction(&MF);
323
324   // We didn't modify anything.
325   return false;
326 }
327
328 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
329 {
330   printOperand(MI, opNum);
331   
332   if (MI->getOperand(opNum+1).isImm()
333     && MI->getOperand(opNum+1).getImm() == 0)
334     return;
335   
336   O << "+";
337   printOperand(MI, opNum+1);
338 }
339
340 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
341   const MachineOperand &MO = MI->getOperand(opNum);
342   switch (MO.getType()) {
343   case MachineOperand::MO_Register:
344     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
345       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
346     else
347       llvm_unreachable("not implemented");
348     break;
349   case MachineOperand::MO_Immediate:
350     O << MO.getImm();
351     break;
352   case MachineOperand::MO_MachineBasicBlock:
353     printBasicBlockLabel(MO.getMBB());
354     break;
355   case MachineOperand::MO_GlobalAddress:
356     O << Mang->getMangledName(MO.getGlobal());
357     break;
358   case MachineOperand::MO_ExternalSymbol:
359     O << MO.getSymbolName();
360     break;
361   case MachineOperand::MO_ConstantPoolIndex:
362     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
363       << '_' << MO.getIndex();
364     break;
365   case MachineOperand::MO_JumpTableIndex:
366     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
367       << '_' << MO.getIndex();
368     break;
369   default:
370     llvm_unreachable("not implemented");
371   }
372 }
373
374 /// PrintAsmOperand - Print out an operand for an inline asm expression.
375 ///
376 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
377                                       unsigned AsmVariant, 
378                                       const char *ExtraCode) {
379   printOperand(MI, OpNo);
380   return false;
381 }
382
383 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
384   ++EmittedInsts;
385
386   // Check for mov mnemonic
387   unsigned src, dst, srcSR, dstSR;
388   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst, srcSR, dstSR)) {
389     O << "\tmov ";
390     O << TM.getRegisterInfo()->get(dst).AsmName;
391     O << ", ";
392     O << TM.getRegisterInfo()->get(src).AsmName;
393     O << "\n";
394     return;
395   }
396   if (printInstruction(MI)) {
397     return;
398   }
399   llvm_unreachable("Unhandled instruction in asm writer!");
400 }
401
402 bool XCoreAsmPrinter::doInitialization(Module &M) {
403   bool Result = AsmPrinter::doInitialization(M);
404   DW = getAnalysisIfAvailable<DwarfWriter>();
405   
406   return Result;
407 }
408
409 bool XCoreAsmPrinter::doFinalization(Module &M) {
410
411   // Print out module-level global variables.
412   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
413        I != E; ++I) {
414     emitGlobal(I);
415   }
416   
417   return AsmPrinter::doFinalization(M);
418 }