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