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