Rename PaddedSize to AllocSize, in the hope that this
[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   printInstruction(MI);
49   return true;
50 }
51
52 /// runOnMachineFunction - This uses the printInstruction()
53 /// method to print assembly for each instruction.
54 ///
55 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
56   this->MF = &MF;
57
58   // This calls the base class function required to be called at beginning
59   // of runOnMachineFunction.
60   SetupMachineFunction(MF);
61
62   // Get the mangled name.
63   const Function *F = MF.getFunction();
64   CurrentFnName = Mang->getValueName(F);
65
66   // Emit the function variables.
67   emitFunctionData(MF);
68   std::string codeSection;
69   codeSection = "code." + CurrentFnName + ".# " + "CODE";
70   const Section *fCodeSection = TAI->getNamedSection(codeSection.c_str(),
71                                                SectionFlags::Code);
72   O <<  "\n";
73   SwitchToSection (fCodeSection);
74
75   // Emit the frame address of the function at the beginning of code.
76   O << "    retlw  low(" << FunctionLabelBegin<< CurrentFnName << ".frame.)\n";
77   O << "    retlw  high(" << FunctionLabelBegin<< CurrentFnName << ".frame.)\n"; 
78   O << CurrentFnName << ":\n";
79
80
81   // Print out code for the function.
82   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
83        I != E; ++I) {
84     // Print a label for the basic block.
85     if (I != MF.begin()) {
86       printBasicBlockLabel(I, true);
87       O << '\n';
88     }
89     
90     // For emitting line directives, we need to keep track of the current
91     // source line. When it changes then only emit the line directive.
92     unsigned CurLine = 0;
93     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
94          II != E; ++II) {
95       // Emit the line directive if source line changed.
96       const DebugLoc DL = II->getDebugLoc();
97       if (!DL.isUnknown()) {
98         unsigned line = MF.getDebugLocTuple(DL).Line;
99         if (line != CurLine) {
100           O << "\t.line " << line << "\n";
101           CurLine = line;
102         }
103       }
104       // Print the assembly for the instruction.
105       printMachineInstruction(II);
106     }
107   }
108   return false;  // we didn't modify anything.
109 }
110
111 /// createPIC16CodePrinterPass - Returns a pass that prints the PIC16
112 /// assembly code for a MachineFunction to the given output stream,
113 /// using the given target machine description.  This should work
114 /// regardless of whether the function is in SSA form.
115 ///
116 FunctionPass *llvm::createPIC16CodePrinterPass(raw_ostream &o,
117                                                PIC16TargetMachine &tm,
118                                                CodeGenOpt::Level OptLevel,
119                                                bool verbose) {
120   return new PIC16AsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, verbose);
121 }
122
123 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
124   const MachineOperand &MO = MI->getOperand(opNum);
125
126   switch (MO.getType()) {
127     case MachineOperand::MO_Register:
128       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
129         O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
130       else
131         assert(0 && "not implemented");
132         return;
133
134     case MachineOperand::MO_Immediate:
135       O << (int)MO.getImm();
136       return;
137
138     case MachineOperand::MO_GlobalAddress: {
139       std::string Name = Mang->getValueName(MO.getGlobal());
140       if (isLocalName(Name)) 
141         O << FunctionLabelBegin << Mang->getValueName(MO.getGlobal());
142       else
143          O << Mang->getValueName(MO.getGlobal());
144       break;
145     }
146     case MachineOperand::MO_ExternalSymbol: {
147       std::string Name = MO.getSymbolName(); 
148       if (Name.find("__intrinsics.") != std::string::npos)
149         O  << MO.getSymbolName();
150       else
151         O << FunctionLabelBegin << MO.getSymbolName();
152       break;
153     }
154     case MachineOperand::MO_MachineBasicBlock:
155       printBasicBlockLabel(MO.getMBB());
156       return;
157
158     default:
159       assert(0 && " Operand type not supported.");
160   }
161 }
162
163 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
164   int CC = (int)MI->getOperand(opNum).getImm();
165   O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
166 }
167
168
169 bool PIC16AsmPrinter::doInitialization (Module &M) {
170   bool Result = AsmPrinter::doInitialization(M);
171   // FIXME:: This is temporary solution to generate the include file.
172   // The processor should be passed to llc as in input and the header file
173   // should be generated accordingly.
174   O << "\t#include P16F1937.INC\n";
175   MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
176   assert(MMI);
177   DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
178   assert(DW && "Dwarf Writer is not available");
179   DW->BeginModule(&M, MMI, O, this, TAI);
180
181   EmitExternsAndGlobals (M);
182   EmitGlobalData(M);
183   EmitRomData(M);
184   return Result;
185 }
186
187 void PIC16AsmPrinter::EmitExternsAndGlobals (Module &M) {
188  // Emit declarations for external functions.
189   O << "section.0" <<"\n";
190   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
191     std::string Name = Mang->getValueName(I);
192     if (Name.compare("abort") == 0)
193       continue;
194     
195     // If it is llvm intrinsic call then don't emit
196     if (Name.find("llvm.") != std::string::npos)
197       continue;
198
199     if (I->isDeclaration()) {
200       O << "\textern " <<Name << "\n";
201       O << "\textern "  << FunctionLabelBegin << Name << ".ret.\n";
202       O << "\textern " << FunctionLabelBegin << Name << ".args.\n";
203     }
204     else if (I->hasExternalLinkage()) {
205       O << "\tglobal " << Name << "\n";
206       O << "\tglobal " << FunctionLabelBegin << Name << ".ret.\n";
207       O << "\tglobal " << FunctionLabelBegin<< Name << ".args.\n";
208     }
209   }
210
211   // Emit header file to include declaration of library functions
212   O << "\t#include C16IntrinsicCalls.INC\n";
213
214   // Emit declarations for external globals.
215   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
216        I != E; I++) {
217     // Any variables reaching here with ".auto." in its name is a local scope
218     // variable and should not be printed in global data section.
219     std::string Name = Mang->getValueName(I);
220     if (isLocalName (Name))
221       continue;
222
223     if (I->isDeclaration())
224       O << "\textern "<< Name << "\n";
225     else if (I->hasCommonLinkage() || I->hasExternalLinkage())
226       O << "\tglobal "<< Name << "\n";
227   }
228 }
229
230 void PIC16AsmPrinter::EmitRomData (Module &M)
231 {
232   SwitchToSection(TAI->getReadOnlySection());
233   IsRomData = true;
234   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
235        I != E; ++I) {
236     if (!I->hasInitializer())   // External global require no code.
237       continue;
238
239     Constant *C = I->getInitializer();
240     const PointerType *PtrTy = I->getType();
241     int AddrSpace = PtrTy->getAddressSpace();
242     if ((!C->isNullValue()) && (AddrSpace == PIC16ISD::ROM_SPACE)) {
243
244       if (EmitSpecialLLVMGlobal(I))
245         continue;
246
247       // Any variables reaching here with "." in its name is a local scope
248       // variable and should not be printed in global data section.
249       std::string name = Mang->getValueName(I);
250       if (name.find(".") != std::string::npos)
251         continue;
252
253       I->setSection(TAI->getReadOnlySection()->getName());
254       O << name;
255       EmitGlobalConstant(C, AddrSpace);
256       O << "\n";
257     }
258   }
259   IsRomData = false;
260 }
261
262 bool PIC16AsmPrinter::doFinalization(Module &M) {
263   O << "\t" << "END\n";
264   bool Result = AsmPrinter::doFinalization(M);
265   return Result;
266 }
267
268 void PIC16AsmPrinter::emitFunctionData(MachineFunction &MF) {
269   const Function *F = MF.getFunction();
270   std::string FuncName = Mang->getValueName(F);
271   Module *M = const_cast<Module *>(F->getParent());
272   const TargetData *TD = TM.getTargetData();
273   unsigned FrameSize = 0;
274   // Emit the data section name.
275   O << "\n"; 
276   std::string SectionName = "fpdata." + CurrentFnName + ".# " + "UDATA_OVR";
277
278   const Section *fPDataSection = TAI->getNamedSection(SectionName.c_str(),
279                                                       SectionFlags::Writeable);
280   SwitchToSection(fPDataSection);
281   
282
283   // Emit function frame label
284   O << FunctionLabelBegin << CurrentFnName << ".frame.:\n";
285
286   const Type *RetType = F->getReturnType();
287   unsigned RetSize = 0; 
288   if (RetType->getTypeID() != Type::VoidTyID) 
289     RetSize = TD->getTypeAllocSize(RetType);
290   
291   //Emit function return value space
292   if(RetSize > 0)
293      O << FunctionLabelBegin << CurrentFnName << ".ret.    RES  " << RetSize 
294        << "\n";
295   else
296      O << FunctionLabelBegin << CurrentFnName << ".ret.:\n";
297    
298   // Emit variable to hold the space for function arguments 
299   unsigned ArgSize = 0;
300   for (Function::const_arg_iterator argi = F->arg_begin(),
301            arge = F->arg_end(); argi != arge ; ++argi) {
302     const Type *Ty = argi->getType();
303     ArgSize += TD->getTypeAllocSize(Ty);
304    }
305   O << FunctionLabelBegin << CurrentFnName << ".args.      RES  " << ArgSize 
306     << "\n";
307
308   // Emit temporary space
309   int TempSize = PTLI->GetTmpSize();
310   if (TempSize > 0 )
311     O << FunctionLabelBegin << CurrentFnName << ".temp.       RES  " << TempSize 
312       <<"\n";
313
314   // Emit the section name for local variables.
315   O << "\n";
316   std::string SecNameLocals = "fadata." + CurrentFnName + ".# " + "UDATA_OVR";
317
318   const Section *fADataSection = TAI->getNamedSection(SecNameLocals.c_str(),
319                                                       SectionFlags::Writeable);
320   SwitchToSection(fADataSection);
321
322   // Emit the function variables. 
323    
324   // In PIC16 all the function arguments and local variables are global.
325   // Therefore to get the variable belonging to this function entire
326   // global list will be traversed and variables belonging to this function
327   // will be emitted in the current data section.
328   for (Module::global_iterator I = M->global_begin(), E = M->global_end();
329        I != E; ++I) {
330     std::string VarName = Mang->getValueName(I);
331     
332     // The variables of a function are of form FuncName.* . If this variable
333     // does not belong to this function then continue. 
334     // Static local varilabes of a function does not have .auto. in their
335     // name. They are not printed as part of function data but module
336     // level global data.
337     if (! isLocalToFunc(FuncName, VarName))
338      continue;
339
340     I->setSection("fadata." + CurrentFnName + ".#");
341     Constant *C = I->getInitializer();
342     const Type *Ty = C->getType();
343     unsigned Size = TD->getTypeAllocSize(Ty);
344     FrameSize += Size; 
345     // Emit memory reserve directive.
346     O << FunctionLabelBegin << VarName << "  RES  " << Size << "\n";
347   }
348 }
349
350 void PIC16AsmPrinter::EmitGlobalData (Module &M)
351 {
352   const PIC16TargetAsmInfo *PTAI = static_cast<const PIC16TargetAsmInfo *>(TAI);
353   const_cast<PIC16TargetAsmInfo *>(PTAI)->SetSectionForGVs(M);
354   const TargetData *TD = TM.getTargetData();
355
356   std::vector <PIC16Section *>IDATASections = PTAI->getIDATASections();
357   for (unsigned i = 0; i < IDATASections.size(); i++) {
358     SwitchToSection(IDATASections[i]->S_);
359     std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
360     for (unsigned j = 0; j < Items.size(); j++) {
361       std::string Name = Mang->getValueName(Items[j]);
362       Constant *C = Items[j]->getInitializer();
363       int AddrSpace = Items[j]->getType()->getAddressSpace();
364       O << Name;
365       EmitGlobalConstant(C, AddrSpace);
366     }
367   }
368
369   std::vector <PIC16Section *>BSSSections = PTAI->getBSSSections();
370   for (unsigned i = 0; i < BSSSections.size(); i++) {
371     SwitchToSection(BSSSections[i]->S_);
372     std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
373     for (unsigned j = 0; j < Items.size(); j++) {
374       std::string Name = Mang->getValueName(Items[j]);
375       Constant *C = Items[j]->getInitializer();
376       const Type *Ty = C->getType();
377       unsigned Size = TD->getTypeAllocSize(Ty);
378
379       O << Name << " " <<"RES"<< " " << Size ;
380       O << "\n";
381     }
382   }
383 }
384