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