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