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