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