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