pass the mangler down into the various SectionForGlobal methods.
[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 #include "llvm/Target/TargetLoweringObjectFile.h"
29
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 Section *fCodeSection = 
75     getObjFileLowering().getOrCreateSection(codeSection, false, 
76                                             SectionKind::Text);
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       O << Mang->getMangledName(MO.getGlobal());
141       break;
142     }
143     case MachineOperand::MO_ExternalSymbol: {
144        const char *Sname = MO.getSymbolName();
145
146       // If its a libcall name, record it to decls section.
147       if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
148         LibcallDecls.push_back(Sname);
149       }
150
151       O  << Sname;
152       break;
153     }
154     case MachineOperand::MO_MachineBasicBlock:
155       printBasicBlockLabel(MO.getMBB());
156       return;
157
158     default:
159       llvm_unreachable(" Operand type not supported.");
160   }
161 }
162
163 /// printCCOperand - Print the cond code operand.
164 ///
165 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
166   int CC = (int)MI->getOperand(opNum).getImm();
167   O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
168 }
169
170 // This function is used to sort the decls list.
171 // should return true if s1 should come before s2.
172 static bool is_before(const char *s1, const char *s2) {
173   std::string str1 = s1;
174   std::string str2 = s2;
175   int i = str1.compare(str2);
176   // Return true if s1 is smaller or equal.
177   if (i <= 0) return true;
178   // false if s1 should come after s2.
179   return false;
180 }
181
182 // This is used by list::unique below. 
183 // unique will filter out duplicates if it knows them.
184 static bool is_duplicate(const char *s1, const char *s2) {
185   std::string str1 = s1;
186   std::string str2 = s2;
187   return str1 == str2;
188 }
189
190 /// printLibcallDecls - print the extern declarations for compiler 
191 /// intrinsics.
192 ///
193 void PIC16AsmPrinter::printLibcallDecls(void) {
194   // If no libcalls used, return.
195   if (LibcallDecls.empty()) return;
196
197   O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
198   // Remove duplicate entries.
199   LibcallDecls.sort(is_before);
200   LibcallDecls.unique(is_duplicate);
201
202   for (std::list<const char*>::const_iterator I = LibcallDecls.begin(); 
203        I != LibcallDecls.end(); I++) {
204     O << TAI->getExternDirective() << *I << "\n";
205     O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
206     O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
207   }
208   O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
209 }
210
211 /// doInitialization - Perfrom Module level initializations here.
212 /// One task that we do here is to sectionize all global variables.
213 /// The MemSelOptimizer pass depends on the sectionizing.
214 ///
215 bool PIC16AsmPrinter::doInitialization(Module &M) {
216   bool Result = AsmPrinter::doInitialization(M);
217
218   // FIXME:: This is temporary solution to generate the include file.
219   // The processor should be passed to llc as in input and the header file
220   // should be generated accordingly.
221   O << "\n\t#include P16F1937.INC\n";
222
223   // Set the section names for all globals.
224   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
225        I != E; ++I)
226     I->setSection(getObjFileLowering().SectionForGlobal(I, Mang,TM)->getName());
227
228   DbgInfo.BeginModule(M);
229   EmitFunctionDecls(M);
230   EmitUndefinedVars(M);
231   EmitDefinedVars(M);
232   EmitIData(M);
233   EmitUData(M);
234   EmitRomData(M);
235   return Result;
236 }
237
238 /// Emit extern decls for functions imported from other modules, and emit
239 /// global declarations for function defined in this module and which are
240 /// available to other modules.
241 ///
242 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
243  // Emit declarations for external functions.
244   O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
245   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
246     if (I->isIntrinsic())
247       continue;
248
249     std::string Name = Mang->getMangledName(I);
250     if (Name.compare("@abort") == 0)
251       continue;
252     
253     if (!I->isDeclaration() && !I->hasExternalLinkage())
254       continue;
255
256     const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
257                                                  TAI->getGlobalDirective();
258       
259     O << directive << Name << "\n";
260     O << directive << PAN::getRetvalLabel(Name) << "\n";
261     O << directive << PAN::getArgsLabel(Name) << "\n";
262   }
263
264   O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
265 }
266
267 // Emit variables imported from other Modules.
268 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
269   std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDecls->Items;
270   if (!Items.size()) return;
271
272   O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
273   for (unsigned j = 0; j < Items.size(); j++) {
274     O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
275   }
276   O << TAI->getCommentString() << "Imported Variables - END" << "\n";
277 }
278
279 // Emit variables defined in this module and are available to other modules.
280 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
281   std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDefs->Items;
282   if (!Items.size()) return;
283
284   O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
285   for (unsigned j = 0; j < Items.size(); j++) {
286     O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
287   }
288   O <<  TAI->getCommentString() << "Exported Variables - END" << "\n";
289 }
290
291 // Emit initialized data placed in ROM.
292 void PIC16AsmPrinter::EmitRomData(Module &M) {
293   // Print ROM Data section.
294   const std::vector<PIC16Section*> &ROSections = PTOF->ROSections;
295   for (unsigned i = 0; i < ROSections.size(); i++) {
296     const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
297     if (!Items.size()) continue;
298     O << "\n";
299     SwitchToSection(PTOF->ROSections[i]->S_);
300     for (unsigned j = 0; j < Items.size(); j++) {
301       O << Mang->getMangledName(Items[j]);
302       Constant *C = Items[j]->getInitializer();
303       int AddrSpace = Items[j]->getType()->getAddressSpace();
304       EmitGlobalConstant(C, AddrSpace);
305     }
306   }
307 }
308
309 bool PIC16AsmPrinter::doFinalization(Module &M) {
310   printLibcallDecls();
311   EmitRemainingAutos();
312   DbgInfo.EndModule(M);
313   O << "\n\t" << "END\n";
314   return AsmPrinter::doFinalization(M);
315 }
316
317 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
318   const Function *F = MF.getFunction();
319   std::string FuncName = Mang->getMangledName(F);
320   const TargetData *TD = TM.getTargetData();
321   // Emit the data section name.
322   O << "\n"; 
323   std::string T = PAN::getFrameSectionName(CurrentFnName);
324   const char *SectionName = T.c_str();
325
326   const Section *fPDataSection =
327     getObjFileLowering().getOrCreateSection(SectionName, false,
328                                             SectionKind::DataRel);
329   SwitchToSection(fPDataSection);
330   
331   // Emit function frame label
332   O << PAN::getFrameLabel(CurrentFnName) << ":\n";
333
334   const Type *RetType = F->getReturnType();
335   unsigned RetSize = 0; 
336   if (RetType->getTypeID() != Type::VoidTyID) 
337     RetSize = TD->getTypeAllocSize(RetType);
338   
339   //Emit function return value space
340   // FIXME: Do not emit RetvalLable when retsize is zero. To do this
341   // we will need to avoid printing a global directive for Retval label
342   // in emitExternandGloblas.
343   if(RetSize > 0)
344      O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
345   else
346      O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
347    
348   // Emit variable to hold the space for function arguments 
349   unsigned ArgSize = 0;
350   for (Function::const_arg_iterator argi = F->arg_begin(),
351            arge = F->arg_end(); argi != arge ; ++argi) {
352     const Type *Ty = argi->getType();
353     ArgSize += TD->getTypeAllocSize(Ty);
354    }
355
356   O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
357
358   // Emit temporary space
359   int TempSize = PTLI->GetTmpSize();
360   if (TempSize > 0)
361     O << PAN::getTempdataLabel(CurrentFnName) << " RES  " << TempSize << '\n';
362 }
363
364 void PIC16AsmPrinter::EmitIData(Module &M) {
365
366   // Print all IDATA sections.
367   const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
368   for (unsigned i = 0; i < IDATASections.size(); i++) {
369     O << "\n";
370     if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
371       continue;
372     SwitchToSection(IDATASections[i]->S_);
373     std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
374     for (unsigned j = 0; j < Items.size(); j++) {
375       std::string Name = Mang->getMangledName(Items[j]);
376       Constant *C = Items[j]->getInitializer();
377       int AddrSpace = Items[j]->getType()->getAddressSpace();
378       O << Name;
379       EmitGlobalConstant(C, AddrSpace);
380     }
381   }
382 }
383
384 void PIC16AsmPrinter::EmitUData(Module &M) {
385   const TargetData *TD = TM.getTargetData();
386
387   // Print all BSS sections.
388   const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
389   for (unsigned i = 0; i < BSSSections.size(); i++) {
390     O << "\n";
391     SwitchToSection(BSSSections[i]->S_);
392     std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
393     for (unsigned j = 0; j < Items.size(); j++) {
394       std::string Name = Mang->getMangledName(Items[j]);
395       Constant *C = Items[j]->getInitializer();
396       const Type *Ty = C->getType();
397       unsigned Size = TD->getTypeAllocSize(Ty);
398
399       O << Name << " RES " << Size << "\n";
400     }
401   }
402 }
403
404 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
405   // Section names for all globals are already set.
406   const TargetData *TD = TM.getTargetData();
407
408   // Now print Autos section for this function.
409   std::string SectionName = PAN::getAutosSectionName(FunctName);
410   const std::vector<PIC16Section*> &AutosSections = PTOF->AutosSections;
411   for (unsigned i = 0; i < AutosSections.size(); i++) {
412     O << "\n";
413     if (AutosSections[i]->S_->getName() == SectionName) { 
414       // Set the printing status to true
415       AutosSections[i]->setPrintedStatus(true);
416       SwitchToSection(AutosSections[i]->S_);
417       const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
418       for (unsigned j = 0; j < Items.size(); j++) {
419         std::string VarName = Mang->getMangledName(Items[j]);
420         Constant *C = Items[j]->getInitializer();
421         const Type *Ty = C->getType();
422         unsigned Size = TD->getTypeAllocSize(Ty);
423         // Emit memory reserve directive.
424         O << VarName << "  RES  " << Size << "\n";
425       }
426       break;
427     }
428   }
429 }
430
431 // Print autos that were not printed during the code printing of functions.
432 // As the functions might themselves would have got deleted by the optimizer.
433 void PIC16AsmPrinter::EmitRemainingAutos() {
434   const TargetData *TD = TM.getTargetData();
435
436   // Now print Autos section for this function.
437   std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
438   for (unsigned i = 0; i < AutosSections.size(); i++) {
439     
440     // if the section is already printed then don't print again
441     if (AutosSections[i]->isPrinted()) 
442       continue;
443
444     // Set status as printed
445     AutosSections[i]->setPrintedStatus(true);
446
447     O << "\n";
448     SwitchToSection(AutosSections[i]->S_);
449     const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
450     for (unsigned j = 0; j < Items.size(); j++) {
451       std::string VarName = Mang->getMangledName(Items[j]);
452       Constant *C = Items[j]->getInitializer();
453       const Type *Ty = C->getType();
454       unsigned Size = TD->getTypeAllocSize(Ty);
455       // Emit memory reserve directive.
456       O << VarName << "  RES  " << Size << "\n";
457     }
458   }
459 }
460
461
462 extern "C" void LLVMInitializePIC16Target() { 
463   // Register the targets
464   RegisterTargetMachine<PIC16TargetMachine> A(ThePIC16Target);  
465   RegisterTargetMachine<CooperTargetMachine> B(TheCooperTarget);
466   RegisterAsmPrinter<PIC16AsmPrinter> C(ThePIC16Target);
467   RegisterAsmPrinter<PIC16AsmPrinter> D(TheCooperTarget);
468 }