Map stack based frameindices for spills to zero based indices that can be accessed...
[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/Support/raw_ostream.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26
27 using namespace llvm;
28
29 #include "PIC16GenAsmWriter.inc"
30
31 inline static bool isLocalToFunc (std::string &FuncName, std::string &VarName) {
32   if (VarName.find(FuncName + ".auto.") != std::string::npos 
33       || VarName.find(FuncName + ".arg.") != std::string::npos)
34     return true;
35
36   return false;
37 }
38
39 inline static bool isLocalName (std::string &Name) {
40   if (Name.find(".auto.") != std::string::npos 
41       || Name.find(".arg.") != std::string::npos) 
42     return true;
43
44   return false;
45 }
46
47 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
48   std::string NewBank = "";
49   unsigned Operands = MI->getNumOperands();
50   if (Operands > 1) {
51     // Global address or external symbol should be second operand from last
52     // if we want to print banksel for it.
53     unsigned BankSelVar = Operands - 2;
54     // In cases where an instruction has a def or use defined in td file,
55     // that def or use becomes a machine instruction operand.
56     // eg. addfw_1 instruction defines STATUS register. So the machine
57     // instruction for it has MO_Register Operand as its last operand.
58     while ((MI->getOperand(BankSelVar + 1).getType() ==
59            MachineOperand::MO_Register) && (BankSelVar > 0))
60      BankSelVar--;
61     const MachineOperand &Op = MI->getOperand(BankSelVar);
62     unsigned OpType = Op.getType();
63     if (OpType == MachineOperand::MO_GlobalAddress ||
64         OpType == MachineOperand::MO_ExternalSymbol) {
65       if (OpType == MachineOperand::MO_GlobalAddress ) 
66         NewBank = Op.getGlobal()->getSection(); 
67       else {
68         // External Symbol is generated for temp data. Temp data in in
69         // fdata.<functionname>.# section.
70         NewBank = "fdata." + CurrentFnName +".#";
71       }
72       // Operand after global address or external symbol should be  banksel.
73       // Value 1 for this operand means we need to generate banksel else do not
74       // generate banksel.
75       const MachineOperand &BS = MI->getOperand(BankSelVar+1);
76       // If Section names are same then the variables are in same section.
77       // This is not true for external variables as section names for global
78       // variables in all files are same at this time. For eg. initialized 
79       // data in put in idata.# section in all files. 
80       if (((int)BS.getImm() == 1) &&
81           ((Op.isGlobal() && Op.getGlobal()->hasExternalLinkage()) ||
82            (NewBank.compare(CurBank) != 0))) { 
83         O << "\tbanksel ";
84         printOperand(MI, BankSelVar);
85         O << "\n";
86         CurBank = NewBank;
87       }
88     }
89   }
90   printInstruction(MI);
91   return true;
92 }
93
94 /// runOnMachineFunction - This uses the printInstruction()
95 /// method to print assembly for each instruction.
96 ///
97 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
98   this->MF = &MF;
99
100   // This calls the base class function required to be called at beginning
101   // of runOnMachineFunction.
102   SetupMachineFunction(MF);
103
104   // Get the mangled name.
105   const Function *F = MF.getFunction();
106   CurrentFnName = Mang->getValueName(F);
107
108   // Emit the function variables.
109   emitFunctionData(MF);
110   std::string codeSection;
111   codeSection = "code." + CurrentFnName + ".# " + "CODE";
112   const Section *fCodeSection = TAI->getNamedSection(codeSection.c_str(),
113                                                SectionFlags::Code);
114   O <<  "\n";
115   SwitchToSection (fCodeSection);
116
117   // Print out code for the function.
118   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
119        I != E; ++I) {
120     // Print a label for the basic block.
121     if (I != MF.begin()) {
122       printBasicBlockLabel(I, true);
123       O << '\n';
124     }
125     else
126       O << CurrentFnName << ":\n";
127     CurBank = "";
128     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
129          II != E; ++II) {
130       // Print the assembly for the instruction.
131         printMachineInstruction(II);
132     }
133   }
134   return false;  // we didn't modify anything.
135 }
136
137 /// createPIC16CodePrinterPass - Returns a pass that prints the PIC16
138 /// assembly code for a MachineFunction to the given output stream,
139 /// using the given target machine description.  This should work
140 /// regardless of whether the function is in SSA form.
141 ///
142 FunctionPass *llvm::createPIC16CodePrinterPass(raw_ostream &o,
143                                                PIC16TargetMachine &tm,
144                                                bool fast, bool verbose) {
145   return new PIC16AsmPrinter(o, tm, tm.getTargetAsmInfo(), fast, verbose);
146 }
147
148 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
149   const MachineOperand &MO = MI->getOperand(opNum);
150
151   switch (MO.getType()) {
152     case MachineOperand::MO_Register:
153       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
154         O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
155       else
156         assert(0 && "not implemented");
157         return;
158
159     case MachineOperand::MO_Immediate:
160       O << (int)MO.getImm();
161       return;
162
163     case MachineOperand::MO_GlobalAddress:
164       O << Mang->getValueName(MO.getGlobal());
165       break;
166
167     case MachineOperand::MO_ExternalSymbol:
168       O << MO.getSymbolName();
169       break;
170
171     case MachineOperand::MO_MachineBasicBlock:
172       printBasicBlockLabel(MO.getMBB());
173       return;
174
175     default:
176       assert(0 && " Operand type not supported.");
177   }
178 }
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
186 bool PIC16AsmPrinter::doInitialization (Module &M) {
187   bool Result = AsmPrinter::doInitialization(M);
188   // FIXME:: This is temporary solution to generate the include file.
189   // The processor should be passed to llc as in input and the header file
190   // should be generated accordingly.
191   O << "\t#include P16F1937.INC\n";
192   MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
193   assert(MMI);
194   DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
195   assert(DW && "Dwarf Writer is not available");
196   DW->BeginModule(&M, MMI, O, this, TAI);
197
198   EmitExternsAndGlobals (M);
199   EmitInitData (M);
200   EmitUnInitData(M);
201   EmitRomData(M);
202   return Result;
203 }
204
205 void PIC16AsmPrinter::EmitExternsAndGlobals (Module &M) {
206  // Emit declarations for external functions.
207   O << "section.0" <<"\n";
208   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
209     std::string Name = Mang->getValueName(I);
210     if (Name.compare("abort") == 0)
211       continue;
212     if (I->isDeclaration()) {
213       O << "\textern " <<Name << "\n";
214       O << "\textern " << Name << ".retval\n";
215       O << "\textern " << Name << ".args\n";
216     }
217     else if (I->hasExternalLinkage()) {
218       O << "\tglobal " << Name << "\n";
219       O << "\tglobal " << Name << ".retval\n";
220       O << "\tglobal " << Name << ".args\n";
221     }
222   }
223
224   // Emit header file to include declaration of library functions
225   O << "\t#include C16IntrinsicCalls.INC\n";
226
227   // Emit declarations for external globals.
228   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
229        I != E; I++) {
230     // Any variables reaching here with ".auto." in its name is a local scope
231     // variable and should not be printed in global data section.
232     std::string Name = Mang->getValueName(I);
233     if (isLocalName (Name))
234       continue;
235
236     if (I->isDeclaration())
237       O << "\textern "<< Name << "\n";
238     else if (I->hasCommonLinkage() || I->hasExternalLinkage())
239       O << "\tglobal "<< Name << "\n";
240   }
241 }
242
243 void PIC16AsmPrinter::EmitInitData (Module &M) {
244   SwitchToSection(TAI->getDataSection());
245   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
246        I != E; ++I) {
247     if (!I->hasInitializer())   // External global require no code.
248       continue;
249
250     Constant *C = I->getInitializer();
251     const PointerType *PtrTy = I->getType();
252     int AddrSpace = PtrTy->getAddressSpace();
253
254     if ((!C->isNullValue()) && (AddrSpace == PIC16ISD::RAM_SPACE)) {
255     
256       if (EmitSpecialLLVMGlobal(I)) 
257         continue;
258
259       // Any variables reaching here with "." in its name is a local scope
260       // variable and should not be printed in global data section.
261       std::string Name = Mang->getValueName(I);
262       if (isLocalName(Name))
263         continue;
264
265       I->setSection(TAI->getDataSection()->getName());
266       O << Name;
267       EmitGlobalConstant(C, AddrSpace);
268     }
269   }
270 }
271
272 void PIC16AsmPrinter::EmitRomData (Module &M)
273 {
274   SwitchToSection(TAI->getReadOnlySection());
275   IsRomData = true;
276   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
277        I != E; ++I) {
278     if (!I->hasInitializer())   // External global require no code.
279       continue;
280
281     Constant *C = I->getInitializer();
282     const PointerType *PtrTy = I->getType();
283     int AddrSpace = PtrTy->getAddressSpace();
284     if ((!C->isNullValue()) && (AddrSpace == PIC16ISD::ROM_SPACE)) {
285
286       if (EmitSpecialLLVMGlobal(I))
287         continue;
288
289       // Any variables reaching here with "." in its name is a local scope
290       // variable and should not be printed in global data section.
291       std::string name = Mang->getValueName(I);
292       if (name.find(".") != std::string::npos)
293         continue;
294
295       I->setSection(TAI->getReadOnlySection()->getName());
296       O << name;
297       EmitGlobalConstant(C, AddrSpace);
298       O << "\n";
299     }
300   }
301   IsRomData = false;
302 }
303
304 void PIC16AsmPrinter::EmitUnInitData (Module &M)
305 {
306   SwitchToSection(TAI->getBSSSection_());
307   const TargetData *TD = TM.getTargetData();
308
309   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
310        I != E; ++I) {
311     if (!I->hasInitializer())   // External global require no code.
312       continue;
313
314     Constant *C = I->getInitializer();
315     if (C->isNullValue()) {
316
317       if (EmitSpecialLLVMGlobal(I))
318         continue;
319
320       // Any variables reaching here with "." in its name is a local scope
321       // variable and should not be printed in global data section.
322       std::string name = Mang->getValueName(I);
323       if (name.find(".") != std::string::npos)
324         continue;
325
326       I->setSection(TAI->getBSSSection_()->getName());
327
328       const Type *Ty = C->getType();
329       unsigned Size = TD->getTypePaddedSize(Ty);
330
331       O << name << " " <<"RES"<< " " << Size ;
332       O << "\n";
333     }
334   }
335 }
336
337 bool PIC16AsmPrinter::doFinalization(Module &M) {
338   O << "\t" << "END\n";
339   bool Result = AsmPrinter::doFinalization(M);
340   return Result;
341 }
342
343 void PIC16AsmPrinter::emitFunctionData(MachineFunction &MF) {
344   const Function *F = MF.getFunction();
345   std::string FuncName = Mang->getValueName(F);
346   Module *M = const_cast<Module *>(F->getParent());
347   const TargetData *TD = TM.getTargetData();
348   unsigned FrameSize = 0;
349   // Emit the data section name.
350   O << "\n"; 
351   std::string SectionName = "fdata." + CurrentFnName + ".# " + "UDATA";
352
353   const Section *fDataSection = TAI->getNamedSection(SectionName.c_str(),
354                                                SectionFlags::Writeable);
355   SwitchToSection(fDataSection);
356   
357
358   // Emit function frame label
359   O << CurrentFnName << ".frame:\n";
360
361   const Type *RetType = F->getReturnType();
362   unsigned RetSize = 0; 
363   if (RetType->getTypeID() != Type::VoidTyID) 
364     RetSize = TD->getTypePaddedSize(RetType);
365   
366   //Emit function return value space
367   if(RetSize > 0)
368      O << CurrentFnName << ".retval    RES  " << RetSize << "\n";
369   else
370      O << CurrentFnName << ".retval:\n";
371    
372   // Emit variable to hold the space for function arguments 
373   unsigned ArgSize = 0;
374   for (Function::const_arg_iterator argi = F->arg_begin(),
375            arge = F->arg_end(); argi != arge ; ++argi) {
376     const Type *Ty = argi->getType();
377     ArgSize += TD->getTypePaddedSize(Ty);
378    }
379   O << CurrentFnName << ".args      RES  " << ArgSize << "\n";
380
381   // Emit the function variables. 
382    
383   // In PIC16 all the function arguments and local variables are global.
384   // Therefore to get the variable belonging to this function entire
385   // global list will be traversed and variables belonging to this function
386   // will be emitted in the current data section.
387   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
388        I != E; ++I) {
389     std::string VarName = Mang->getValueName(I);
390     
391     // The variables of a function are of form FuncName.* . If this variable
392     // does not belong to this function then continue. 
393     // Static local varilabes of a function does not have .auto. in their
394     // name. They are not printed as part of function data but module
395     // level global data.
396     if (! isLocalToFunc(FuncName, VarName))
397      continue;
398
399     I->setSection("fdata." + CurrentFnName + ".#");
400     Constant *C = I->getInitializer();
401     const Type *Ty = C->getType();
402     unsigned Size = TD->getTypePaddedSize(Ty);
403     FrameSize += Size; 
404     // Emit memory reserve directive.
405     O << VarName << "  RES  " << Size << "\n";
406   }
407
408   int TempSize = PTLI->GetTmpSize();
409   if (TempSize > 0 )
410     O << CurrentFnName << ".tmp       RES  " << TempSize <<"\n";
411 }