6466ad6a22ec4561e9459cf8ea0a2cdb4a4e4df3
[oota-llvm.git] / lib / Target / PIC16 / PIC16AsmPrinter.cpp
1 //===-- PIC16AsmPrinter.cpp - PIC16 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 PIC16 assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PIC16AsmPrinter.h"
16 #include "PIC16TargetAsmInfo.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/DwarfWriter.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26
27 using namespace llvm;
28
29 #include "PIC16GenAsmWriter.inc"
30
31 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
32   printInstruction(MI);
33   return true;
34 }
35
36 /// runOnMachineFunction - This emits the frame section, autos section and 
37 /// assembly for each instruction. Also takes care of function begin debug
38 /// directive and file begin debug directive (if required) for the function.
39 ///
40 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
41   this->MF = &MF;
42
43   // This calls the base class function required to be called at beginning
44   // of runOnMachineFunction.
45   SetupMachineFunction(MF);
46
47   // Get the mangled name.
48   const Function *F = MF.getFunction();
49   CurrentFnName = Mang->getValueName(F);
50
51   // Emit the function frame (args and temps).
52   EmitFunctionFrame(MF);
53
54   DbgInfo.BeginFunction(MF);
55
56   // Emit the autos section of function.
57   EmitAutos(CurrentFnName);
58
59   // Now emit the instructions of function in its code section.
60   const char *codeSection = PAN::getCodeSectionName(CurrentFnName).c_str();
61  
62   const Section *fCodeSection = TAI->getNamedSection(codeSection,
63                                                      SectionFlags::Code);
64   // Start the Code Section.
65   O <<  "\n";
66   SwitchToSection (fCodeSection);
67
68   // Emit the frame address of the function at the beginning of code.
69   O << "\tretlw  low(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
70   O << "\tretlw  high(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
71
72   // Emit function start label.
73   O << CurrentFnName << ":\n";
74
75   DebugLoc CurDL;
76   O << "\n"; 
77   // Print out code for the function.
78   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
79        I != E; ++I) {
80
81     // Print a label for the basic block.
82     if (I != MF.begin()) {
83       printBasicBlockLabel(I, true);
84       O << '\n';
85     }
86     
87     // Print a basic block.
88     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
89          II != E; ++II) {
90
91       // Emit the line directive if source line changed.
92       const DebugLoc DL = II->getDebugLoc();
93       if (!DL.isUnknown() && DL != CurDL) {
94         DbgInfo.ChangeDebugLoc(MF, DL);
95         CurDL = DL;
96       }
97         
98       // Print the assembly for the instruction.
99       printMachineInstruction(II);
100     }
101   }
102   
103   // Emit function end debug directives.
104   DbgInfo.EndFunction(MF);
105
106   return false;  // we didn't modify anything.
107 }
108
109 /// createPIC16CodePrinterPass - Returns a pass that prints the PIC16
110 /// assembly code for a MachineFunction to the given output stream,
111 /// using the given target machine description.  This should work
112 /// regardless of whether the function is in SSA form.
113 ///
114 FunctionPass *llvm::createPIC16CodePrinterPass(raw_ostream &o,
115                                                PIC16TargetMachine &tm,
116                                                bool verbose) {
117   return new PIC16AsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
118 }
119
120
121 // printOperand - print operand of insn.
122 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
123   const MachineOperand &MO = MI->getOperand(opNum);
124
125   switch (MO.getType()) {
126     case MachineOperand::MO_Register:
127       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
128         O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
129       else
130         assert(0 && "not implemented");
131         return;
132
133     case MachineOperand::MO_Immediate:
134       O << (int)MO.getImm();
135       return;
136
137     case MachineOperand::MO_GlobalAddress: {
138       O << Mang->getValueName(MO.getGlobal());
139       break;
140     }
141     case MachineOperand::MO_ExternalSymbol: {
142        const char *Sname = MO.getSymbolName();
143
144       // If its a libcall name, record it to decls section.
145       if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
146         LibcallDecls.push_back(Sname);
147       }
148
149       O  << Sname;
150       break;
151     }
152     case MachineOperand::MO_MachineBasicBlock:
153       printBasicBlockLabel(MO.getMBB());
154       return;
155
156     default:
157       assert(0 && " Operand type not supported.");
158   }
159 }
160
161 /// printCCOperand - Print the cond code operand.
162 ///
163 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
164   int CC = (int)MI->getOperand(opNum).getImm();
165   O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
166 }
167
168 /// printLibcallDecls - print the extern declarations for compiler 
169 /// intrinsics.
170 ///
171 void PIC16AsmPrinter::printLibcallDecls(void) {
172   // If no libcalls used, return.
173   if (LibcallDecls.empty()) return;
174
175   O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
176   // Remove duplicate entries.
177   LibcallDecls.sort();
178   LibcallDecls.unique();
179   for (std::list<const char*>::const_iterator I = LibcallDecls.begin(); 
180        I != LibcallDecls.end(); I++) {
181     O << TAI->getExternDirective() << *I << "\n";
182     O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
183     O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
184   }
185   O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
186 }
187
188 /// doInitialization - Perfrom Module level initializations here.
189 /// One task that we do here is to sectionize all global variables.
190 /// The MemSelOptimizer pass depends on the sectionizing.
191 ///
192 bool PIC16AsmPrinter::doInitialization (Module &M) {
193   bool Result = AsmPrinter::doInitialization(M);
194
195   // FIXME:: This is temporary solution to generate the include file.
196   // The processor should be passed to llc as in input and the header file
197   // should be generated accordingly.
198   O << "\n\t#include P16F1937.INC\n";
199
200   // Set the section names for all globals.
201   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
202        I != E; ++I) {
203     I->setSection(TAI->SectionForGlobal(I)->getName());
204   }
205
206   DbgInfo.BeginModule(M);
207   EmitFunctionDecls(M);
208   EmitUndefinedVars(M);
209   EmitDefinedVars(M);
210   EmitIData(M);
211   EmitUData(M);
212   EmitRomData(M);
213   return Result;
214 }
215
216 /// Emit extern decls for functions imported from other modules, and emit
217 /// global declarations for function defined in this module and which are
218 /// available to other modules.
219 ///
220 void PIC16AsmPrinter::EmitFunctionDecls (Module &M) {
221  // Emit declarations for external functions.
222   O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
223   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
224     std::string Name = Mang->getValueName(I);
225     if (Name.compare("@abort") == 0)
226       continue;
227     
228     // If it is llvm intrinsic call then don't emit
229     if (Name.find("llvm.") != std::string::npos)
230       continue;
231
232     if (! (I->isDeclaration() || I->hasExternalLinkage()))
233       continue;
234
235     const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
236                                                  TAI->getGlobalDirective();
237       
238     O << directive << Name << "\n";
239     O << directive << PAN::getRetvalLabel(Name) << "\n";
240     O << directive << PAN::getArgsLabel(Name) << "\n";
241   }
242
243   O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
244 }
245
246 // Emit variables imported from other Modules.
247 void PIC16AsmPrinter::EmitUndefinedVars (Module &M)
248 {
249   std::vector<const GlobalVariable*> Items = PTAI->ExternalVarDecls->Items;
250   if (! Items.size()) return;
251
252   O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
253   for (unsigned j = 0; j < Items.size(); j++) {
254     O << TAI->getExternDirective() << Mang->getValueName(Items[j]) << "\n";
255   }
256   O << TAI->getCommentString() << "Imported Variables - END" << "\n";
257 }
258
259 // Emit variables defined in this module and are available to other modules.
260 void PIC16AsmPrinter::EmitDefinedVars (Module &M)
261 {
262   std::vector<const GlobalVariable*> Items = PTAI->ExternalVarDefs->Items;
263   if (! Items.size()) return;
264
265   O << "\n" <<  TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
266   for (unsigned j = 0; j < Items.size(); j++) {
267     O << TAI->getGlobalDirective() << Mang->getValueName(Items[j]) << "\n";
268   }
269   O <<  TAI->getCommentString() << "Exported Variables - END" << "\n";
270 }
271
272 // Emit initialized data placed in ROM.
273 void PIC16AsmPrinter::EmitRomData (Module &M)
274 {
275   // Print ROM Data section.
276   std::vector <PIC16Section *>ROSections = PTAI->ROSections;
277   for (unsigned i = 0; i < ROSections.size(); i++) {
278     std::vector<const GlobalVariable*> Items = ROSections[i]->Items;
279     if (! Items.size()) continue;
280     O << "\n";
281     SwitchToSection(PTAI->ROSections[i]->S_);
282     for (unsigned j = 0; j < Items.size(); j++) {
283       O << Mang->getValueName(Items[j]);
284       Constant *C = Items[j]->getInitializer();
285       int AddrSpace = Items[j]->getType()->getAddressSpace();
286       EmitGlobalConstant(C, AddrSpace);
287     }
288   }
289 }
290
291 bool PIC16AsmPrinter::doFinalization(Module &M) {
292   printLibcallDecls();
293   EmitRemainingAutos();
294   DbgInfo.EndModule(M);
295   O << "\n\t" << "END\n";
296   bool Result = AsmPrinter::doFinalization(M);
297   return Result;
298 }
299
300 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
301   const Function *F = MF.getFunction();
302   std::string FuncName = Mang->getValueName(F);
303   const TargetData *TD = TM.getTargetData();
304   // Emit the data section name.
305   O << "\n"; 
306   const char *SectionName = PAN::getFrameSectionName(CurrentFnName).c_str();
307
308   const Section *fPDataSection = TAI->getNamedSection(SectionName,
309                                                       SectionFlags::Writeable);
310   SwitchToSection(fPDataSection);
311   
312   // Emit function frame label
313   O << PAN::getFrameLabel(CurrentFnName) << ":\n";
314
315   const Type *RetType = F->getReturnType();
316   unsigned RetSize = 0; 
317   if (RetType->getTypeID() != Type::VoidTyID) 
318     RetSize = TD->getTypeAllocSize(RetType);
319   
320   //Emit function return value space
321   // FIXME: Do not emit RetvalLable when retsize is zero. To do this
322   // we will need to avoid printing a global directive for Retval label
323   // in emitExternandGloblas.
324   if(RetSize > 0)
325      O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
326   else
327      O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
328    
329   // Emit variable to hold the space for function arguments 
330   unsigned ArgSize = 0;
331   for (Function::const_arg_iterator argi = F->arg_begin(),
332            arge = F->arg_end(); argi != arge ; ++argi) {
333     const Type *Ty = argi->getType();
334     ArgSize += TD->getTypeAllocSize(Ty);
335    }
336
337   O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
338
339   // Emit temporary space
340   int TempSize = PTLI->GetTmpSize();
341   if (TempSize > 0 )
342     O << PAN::getTempdataLabel(CurrentFnName) << " RES  " << TempSize <<"\n";
343 }
344
345 void PIC16AsmPrinter::EmitIData (Module &M) {
346
347   // Print all IDATA sections.
348   std::vector <PIC16Section *>IDATASections = PTAI->IDATASections;
349   for (unsigned i = 0; i < IDATASections.size(); i++) {
350     O << "\n";
351     if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
352       continue;
353     SwitchToSection(IDATASections[i]->S_);
354     std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
355     for (unsigned j = 0; j < Items.size(); j++) {
356       std::string Name = Mang->getValueName(Items[j]);
357       Constant *C = Items[j]->getInitializer();
358       int AddrSpace = Items[j]->getType()->getAddressSpace();
359       O << Name;
360       EmitGlobalConstant(C, AddrSpace);
361     }
362   }
363 }
364
365 void PIC16AsmPrinter::EmitUData (Module &M) {
366   const TargetData *TD = TM.getTargetData();
367
368   // Print all BSS sections.
369   std::vector <PIC16Section *>BSSSections = PTAI->BSSSections;
370   for (unsigned i = 0; i < BSSSections.size(); i++) {
371     O << "\n";
372     SwitchToSection(BSSSections[i]->S_);
373     std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
374     for (unsigned j = 0; j < Items.size(); j++) {
375       std::string Name = Mang->getValueName(Items[j]);
376       Constant *C = Items[j]->getInitializer();
377       const Type *Ty = C->getType();
378       unsigned Size = TD->getTypeAllocSize(Ty);
379
380       O << Name << " " <<"RES"<< " " << Size ;
381       O << "\n";
382     }
383   }
384 }
385
386 void PIC16AsmPrinter::EmitAutos (std::string FunctName)
387 {
388   // Section names for all globals are already set.
389
390   const TargetData *TD = TM.getTargetData();
391
392   // Now print Autos section for this function.
393   std::string SectionName = PAN::getAutosSectionName(FunctName);
394   std::vector <PIC16Section *>AutosSections = PTAI->AutosSections;
395   for (unsigned i = 0; i < AutosSections.size(); i++) {
396     O << "\n";
397     if (AutosSections[i]->S_->getName() == SectionName) { 
398       // Set the printing status to true
399       AutosSections[i]->setPrintedStatus(true);
400       SwitchToSection(AutosSections[i]->S_);
401       std::vector<const GlobalVariable*> Items = AutosSections[i]->Items;
402       for (unsigned j = 0; j < Items.size(); j++) {
403         std::string VarName = Mang->getValueName(Items[j]);
404         Constant *C = Items[j]->getInitializer();
405         const Type *Ty = C->getType();
406         unsigned Size = TD->getTypeAllocSize(Ty);
407         // Emit memory reserve directive.
408         O << VarName << "  RES  " << Size << "\n";
409       }
410       break;
411     }
412   }
413 }
414
415 // Print autos that were not printed during the code printing of functions.
416 // As the functions might themselves would have got deleted by the optimizer.
417 void PIC16AsmPrinter::EmitRemainingAutos()
418 {
419   const TargetData *TD = TM.getTargetData();
420
421   // Now print Autos section for this function.
422   std::vector <PIC16Section *>AutosSections = PTAI->AutosSections;
423   for (unsigned i = 0; i < AutosSections.size(); i++) {
424     
425     // if the section is already printed then don't print again
426     if (AutosSections[i]->isPrinted()) 
427       continue;
428
429     // Set status as printed
430     AutosSections[i]->setPrintedStatus(true);
431
432     O << "\n";
433     SwitchToSection(AutosSections[i]->S_);
434     std::vector<const GlobalVariable*> Items = AutosSections[i]->Items;
435     for (unsigned j = 0; j < Items.size(); j++) {
436       std::string VarName = Mang->getValueName(Items[j]);
437       Constant *C = Items[j]->getInitializer();
438       const Type *Ty = C->getType();
439       unsigned Size = TD->getTypeAllocSize(Ty);
440       // Emit memory reserve directive.
441       O << VarName << "  RES  " << Size << "\n";
442     }
443   }
444 }
445