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