1 //===-- PIC16AsmPrinter.cpp - PIC16 LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PIC16 assembly language.
13 //===----------------------------------------------------------------------===//
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/CodeGen/DwarfWriter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/MC/MCSection.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"
32 #include "PIC16GenAsmWriter.inc"
34 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
35 const TargetAsmInfo *T, bool V)
36 : AsmPrinter(O, TM, T, V), DbgInfo(O, T) {
37 PTLI = static_cast<const PIC16TargetLowering*>(TM.getTargetLowering());
38 PTAI = static_cast<const PIC16TargetAsmInfo*>(T);
39 PTOF = (PIC16TargetObjectFile*)&PTLI->getObjFileLowering();
42 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
47 /// runOnMachineFunction - This emits the frame section, autos section and
48 /// assembly for each instruction. Also takes care of function begin debug
49 /// directive and file begin debug directive (if required) for the function.
51 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
54 // This calls the base class function required to be called at beginning
55 // of runOnMachineFunction.
56 SetupMachineFunction(MF);
58 // Get the mangled name.
59 const Function *F = MF.getFunction();
60 CurrentFnName = Mang->getMangledName(F);
62 // Emit the function frame (args and temps).
63 EmitFunctionFrame(MF);
65 DbgInfo.BeginFunction(MF);
67 // Emit the autos section of function.
68 EmitAutos(CurrentFnName);
70 // Now emit the instructions of function in its code section.
71 std::string T = PAN::getCodeSectionName(CurrentFnName);
72 const char *codeSection = T.c_str();
74 const MCSection *fCodeSection =
75 getObjFileLowering().getOrCreateSection(codeSection, false,
76 SectionKind::getText());
77 // Start the Code Section.
79 SwitchToSection(fCodeSection);
81 // Emit the frame address of the function at the beginning of code.
82 O << "\tretlw low(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
83 O << "\tretlw high(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
85 // Emit function start label.
86 O << CurrentFnName << ":\n";
90 // Print out code for the function.
91 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
94 // Print a label for the basic block.
95 if (I != MF.begin()) {
96 printBasicBlockLabel(I, true);
100 // Print a basic block.
101 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
104 // Emit the line directive if source line changed.
105 const DebugLoc DL = II->getDebugLoc();
106 if (!DL.isUnknown() && DL != CurDL) {
107 DbgInfo.ChangeDebugLoc(MF, DL);
111 // Print the assembly for the instruction.
112 printMachineInstruction(II);
116 // Emit function end debug directives.
117 DbgInfo.EndFunction(MF);
119 return false; // we didn't modify anything.
123 // printOperand - print operand of insn.
124 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
125 const MachineOperand &MO = MI->getOperand(opNum);
127 switch (MO.getType()) {
128 case MachineOperand::MO_Register:
129 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
130 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
132 llvm_unreachable("not implemented");
135 case MachineOperand::MO_Immediate:
136 O << (int)MO.getImm();
139 case MachineOperand::MO_GlobalAddress: {
140 std::string Sname = Mang->getMangledName(MO.getGlobal());
141 // FIXME: currently we do not have a memcpy def coming in the module
142 // by any chance, as we do not link in those as .bc lib. So these calls
143 // are always external and it is safe to emit an extern.
144 if (PAN::isMemIntrinsic(Sname)) {
145 LibcallDecls.push_back(createESName(Sname));
151 case MachineOperand::MO_ExternalSymbol: {
152 const char *Sname = MO.getSymbolName();
154 // If its a libcall name, record it to decls section.
155 if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
156 LibcallDecls.push_back(Sname);
159 // Record a call to intrinsic to print the extern declaration for it.
160 std::string Sym = Sname;
161 if (PAN::isMemIntrinsic(Sym)) {
162 Sym = PAN::addPrefix(Sym);
163 LibcallDecls.push_back(createESName(Sym));
169 case MachineOperand::MO_MachineBasicBlock:
170 printBasicBlockLabel(MO.getMBB());
174 llvm_unreachable(" Operand type not supported.");
178 /// printCCOperand - Print the cond code operand.
180 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
181 int CC = (int)MI->getOperand(opNum).getImm();
182 O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
185 // This function is used to sort the decls list.
186 // should return true if s1 should come before s2.
187 static bool is_before(const char *s1, const char *s2) {
188 std::string str1 = s1;
189 std::string str2 = s2;
190 int i = str1.compare(str2);
191 // Return true if s1 is smaller or equal.
192 if (i <= 0) return true;
193 // false if s1 should come after s2.
197 // This is used by list::unique below.
198 // unique will filter out duplicates if it knows them.
199 static bool is_duplicate(const char *s1, const char *s2) {
200 std::string str1 = s1;
201 std::string str2 = s2;
205 /// printLibcallDecls - print the extern declarations for compiler
208 void PIC16AsmPrinter::printLibcallDecls(void) {
209 // If no libcalls used, return.
210 if (LibcallDecls.empty()) return;
212 O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
213 // Remove duplicate entries.
214 LibcallDecls.sort(is_before);
215 LibcallDecls.unique(is_duplicate);
217 for (std::list<const char*>::const_iterator I = LibcallDecls.begin();
218 I != LibcallDecls.end(); I++) {
219 O << TAI->getExternDirective() << *I << "\n";
220 O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
221 O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
223 O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
226 /// doInitialization - Perfrom Module level initializations here.
227 /// One task that we do here is to sectionize all global variables.
228 /// The MemSelOptimizer pass depends on the sectionizing.
230 bool PIC16AsmPrinter::doInitialization(Module &M) {
231 bool Result = AsmPrinter::doInitialization(M);
233 // FIXME:: This is temporary solution to generate the include file.
234 // The processor should be passed to llc as in input and the header file
235 // should be generated accordingly.
236 O << "\n\t#include P16F1937.INC\n";
238 // Set the section names for all globals.
239 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
241 if (!I->isDeclaration())
242 I->setSection(getObjFileLowering().
243 SectionForGlobal(I, Mang,TM)->getName());
245 DbgInfo.BeginModule(M);
246 EmitFunctionDecls(M);
247 EmitUndefinedVars(M);
255 /// Emit extern decls for functions imported from other modules, and emit
256 /// global declarations for function defined in this module and which are
257 /// available to other modules.
259 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
260 // Emit declarations for external functions.
261 O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
262 for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
263 if (I->isIntrinsic())
266 std::string Name = Mang->getMangledName(I);
267 if (Name.compare("@abort") == 0)
270 if (!I->isDeclaration() && !I->hasExternalLinkage())
273 // Do not emit memcpy, memset, and memmove here.
274 // Calls to these routines can be generated in two ways,
275 // 1. User calling the standard lib function
276 // 2. Codegen generating these calls for llvm intrinsics.
277 // In the first case a prototype is alread availale, while in
278 // second case the call is via and externalsym and the prototype is missing.
279 // So declarations for these are currently always getting printing by
280 // tracking both kind of references in printInstrunction.
281 if (I->isDeclaration() && PAN::isMemIntrinsic(Name)) continue;
283 const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
284 TAI->getGlobalDirective();
286 O << directive << Name << "\n";
287 O << directive << PAN::getRetvalLabel(Name) << "\n";
288 O << directive << PAN::getArgsLabel(Name) << "\n";
291 O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
294 // Emit variables imported from other Modules.
295 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
296 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDecls->Items;
297 if (!Items.size()) return;
299 O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
300 for (unsigned j = 0; j < Items.size(); j++) {
301 O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
303 O << TAI->getCommentString() << "Imported Variables - END" << "\n";
306 // Emit variables defined in this module and are available to other modules.
307 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
308 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDefs->Items;
309 if (!Items.size()) return;
311 O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
312 for (unsigned j = 0; j < Items.size(); j++) {
313 O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
315 O << TAI->getCommentString() << "Exported Variables - END" << "\n";
318 // Emit initialized data placed in ROM.
319 void PIC16AsmPrinter::EmitRomData(Module &M) {
320 // Print ROM Data section.
321 const std::vector<PIC16Section*> &ROSections = PTOF->ROSections;
322 for (unsigned i = 0; i < ROSections.size(); i++) {
323 const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
324 if (!Items.size()) continue;
326 SwitchToSection(PTOF->ROSections[i]->S_);
327 for (unsigned j = 0; j < Items.size(); j++) {
328 O << Mang->getMangledName(Items[j]);
329 Constant *C = Items[j]->getInitializer();
330 int AddrSpace = Items[j]->getType()->getAddressSpace();
331 EmitGlobalConstant(C, AddrSpace);
336 bool PIC16AsmPrinter::doFinalization(Module &M) {
338 EmitRemainingAutos();
339 DbgInfo.EndModule(M);
340 O << "\n\t" << "END\n";
341 return AsmPrinter::doFinalization(M);
344 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
345 const Function *F = MF.getFunction();
346 std::string FuncName = Mang->getMangledName(F);
347 const TargetData *TD = TM.getTargetData();
348 // Emit the data section name.
350 std::string T = PAN::getFrameSectionName(CurrentFnName);
351 const char *SectionName = T.c_str();
353 const MCSection *fPDataSection =
354 getObjFileLowering().getOrCreateSection(SectionName, false,
355 SectionKind::getDataRel());
356 SwitchToSection(fPDataSection);
358 // Emit function frame label
359 O << PAN::getFrameLabel(CurrentFnName) << ":\n";
361 const Type *RetType = F->getReturnType();
362 unsigned RetSize = 0;
363 if (RetType->getTypeID() != Type::VoidTyID)
364 RetSize = TD->getTypeAllocSize(RetType);
366 //Emit function return value space
367 // FIXME: Do not emit RetvalLable when retsize is zero. To do this
368 // we will need to avoid printing a global directive for Retval label
369 // in emitExternandGloblas.
371 O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
373 O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
375 // Emit variable to hold the space for function arguments
376 unsigned ArgSize = 0;
377 for (Function::const_arg_iterator argi = F->arg_begin(),
378 arge = F->arg_end(); argi != arge ; ++argi) {
379 const Type *Ty = argi->getType();
380 ArgSize += TD->getTypeAllocSize(Ty);
383 O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
385 // Emit temporary space
386 int TempSize = PTLI->GetTmpSize();
388 O << PAN::getTempdataLabel(CurrentFnName) << " RES " << TempSize << '\n';
391 void PIC16AsmPrinter::EmitIData(Module &M) {
393 // Print all IDATA sections.
394 const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
395 for (unsigned i = 0; i < IDATASections.size(); i++) {
397 if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
399 SwitchToSection(IDATASections[i]->S_);
400 std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
401 for (unsigned j = 0; j < Items.size(); j++) {
402 std::string Name = Mang->getMangledName(Items[j]);
403 Constant *C = Items[j]->getInitializer();
404 int AddrSpace = Items[j]->getType()->getAddressSpace();
406 EmitGlobalConstant(C, AddrSpace);
411 void PIC16AsmPrinter::EmitUData(Module &M) {
412 const TargetData *TD = TM.getTargetData();
414 // Print all BSS sections.
415 const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
416 for (unsigned i = 0; i < BSSSections.size(); i++) {
418 SwitchToSection(BSSSections[i]->S_);
419 std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
420 for (unsigned j = 0; j < Items.size(); j++) {
421 std::string Name = Mang->getMangledName(Items[j]);
422 Constant *C = Items[j]->getInitializer();
423 const Type *Ty = C->getType();
424 unsigned Size = TD->getTypeAllocSize(Ty);
426 O << Name << " RES " << Size << "\n";
431 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
432 // Section names for all globals are already set.
433 const TargetData *TD = TM.getTargetData();
435 // Now print Autos section for this function.
436 std::string SectionName = PAN::getAutosSectionName(FunctName);
437 const std::vector<PIC16Section*> &AutosSections = PTOF->AutosSections;
438 for (unsigned i = 0; i < AutosSections.size(); i++) {
440 if (AutosSections[i]->S_->getName() == SectionName) {
441 // Set the printing status to true
442 AutosSections[i]->setPrintedStatus(true);
443 SwitchToSection(AutosSections[i]->S_);
444 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
445 for (unsigned j = 0; j < Items.size(); j++) {
446 std::string VarName = Mang->getMangledName(Items[j]);
447 Constant *C = Items[j]->getInitializer();
448 const Type *Ty = C->getType();
449 unsigned Size = TD->getTypeAllocSize(Ty);
450 // Emit memory reserve directive.
451 O << VarName << " RES " << Size << "\n";
458 // Print autos that were not printed during the code printing of functions.
459 // As the functions might themselves would have got deleted by the optimizer.
460 void PIC16AsmPrinter::EmitRemainingAutos() {
461 const TargetData *TD = TM.getTargetData();
463 // Now print Autos section for this function.
464 std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
465 for (unsigned i = 0; i < AutosSections.size(); i++) {
467 // if the section is already printed then don't print again
468 if (AutosSections[i]->isPrinted())
471 // Set status as printed
472 AutosSections[i]->setPrintedStatus(true);
475 SwitchToSection(AutosSections[i]->S_);
476 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
477 for (unsigned j = 0; j < Items.size(); j++) {
478 std::string VarName = Mang->getMangledName(Items[j]);
479 Constant *C = Items[j]->getInitializer();
480 const Type *Ty = C->getType();
481 unsigned Size = TD->getTypeAllocSize(Ty);
482 // Emit memory reserve directive.
483 O << VarName << " RES " << Size << "\n";
489 extern "C" void LLVMInitializePIC16Target() {
490 // Register the targets
491 RegisterTargetMachine<PIC16TargetMachine> A(ThePIC16Target);
492 RegisterTargetMachine<CooperTargetMachine> B(TheCooperTarget);
493 RegisterAsmPrinter<PIC16AsmPrinter> C(ThePIC16Target);
494 RegisterAsmPrinter<PIC16AsmPrinter> D(TheCooperTarget);