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 "PIC16ABINames.h"
16 #include "PIC16AsmPrinter.h"
17 #include "PIC16Section.h"
18 #include "PIC16MCAsmInfo.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/DwarfWriter.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
35 #include "PIC16GenAsmWriter.inc"
37 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
38 MCContext &Ctx, MCStreamer &Streamer,
40 : AsmPrinter(O, TM, Ctx, Streamer, T), DbgInfo(O, T) {
41 PTLI = static_cast<PIC16TargetLowering*>(TM.getTargetLowering());
42 PMAI = static_cast<const PIC16MCAsmInfo*>(T);
43 PTOF = (PIC16TargetObjectFile *)&PTLI->getObjFileLowering();
46 void PIC16AsmPrinter::EmitInstruction(const MachineInstr *MI) {
48 OutStreamer.AddBlankLine();
51 static int getFunctionColor(const Function *F) {
52 if (F->hasSection()) {
53 std::string Sectn = F->getSection();
54 std::string StrToFind = "Overlay=";
55 std::string::size_type Pos = Sectn.find(StrToFind);
57 // Retreive the color number if the key is found.
58 if (Pos != std::string::npos) {
59 Pos += StrToFind.length();
60 std::string Color = "";
61 char c = Sectn.at(Pos);
62 // A Color can only consist of digits.
63 while (c >= '0' && c<= '9') {
66 if (Pos >= Sectn.length())
70 return atoi(Color.c_str());
74 // Color was not set for function, so return -1.
78 // Color the Auto section of the given function.
79 void PIC16AsmPrinter::ColorAutoSection(const Function *F) {
80 std::string SectionName = PAN::getAutosSectionName(CurrentFnSym->getName());
81 PIC16Section* Section = PTOF->findPIC16Section(SectionName);
82 if (Section != NULL) {
83 int Color = getFunctionColor(F);
85 Section->setColor(Color);
90 /// runOnMachineFunction - This emits the frame section, autos section and
91 /// assembly for each instruction. Also takes care of function begin debug
92 /// directive and file begin debug directive (if required) for the function.
94 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
95 // This calls the base class function required to be called at beginning
96 // of runOnMachineFunction.
97 SetupMachineFunction(MF);
99 // Put the color information from function to its auto section.
100 const Function *F = MF.getFunction();
103 // Emit the function frame (args and temps).
104 EmitFunctionFrame(MF);
106 DbgInfo.BeginFunction(MF);
108 // Now emit the instructions of function in its code section.
109 const MCSection *fCodeSection
110 = getObjFileLowering().SectionForCode(CurrentFnSym->getName());
112 // Start the Code Section.
114 OutStreamer.SwitchSection(fCodeSection);
116 // Emit the frame address of the function at the beginning of code.
117 O << "\tretlw low(" << PAN::getFrameLabel(CurrentFnSym->getName()) << ")\n";
118 O << "\tretlw high(" << PAN::getFrameLabel(CurrentFnSym->getName()) << ")\n";
120 // Emit function start label.
121 O << *CurrentFnSym << ":\n";
125 // Print out code for the function.
126 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
129 // Print a label for the basic block.
130 if (I != MF.begin()) {
131 EmitBasicBlockStart(I);
134 // Print a basic block.
135 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
138 // Emit the line directive if source line changed.
139 const DebugLoc DL = II->getDebugLoc();
140 if (!DL.isUnknown() && DL != CurDL) {
141 DbgInfo.ChangeDebugLoc(MF, DL);
145 // Print the assembly for the instruction.
150 // Emit function end debug directives.
151 DbgInfo.EndFunction(MF);
153 return false; // we didn't modify anything.
157 // printOperand - print operand of insn.
158 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
159 const MachineOperand &MO = MI->getOperand(opNum);
161 switch (MO.getType()) {
162 case MachineOperand::MO_Register:
164 // For indirect load/store insns, the fsr name is printed as INDF.
165 std::string RegName = getRegisterName(MO.getReg());
166 if ((MI->getOpcode() == PIC16::load_indirect) ||
167 (MI->getOpcode() == PIC16::store_indirect))
169 RegName.replace (0, 3, "INDF");
175 case MachineOperand::MO_Immediate:
176 O << (int)MO.getImm();
179 case MachineOperand::MO_GlobalAddress: {
180 MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
181 // FIXME: currently we do not have a memcpy def coming in the module
182 // by any chance, as we do not link in those as .bc lib. So these calls
183 // are always external and it is safe to emit an extern.
184 if (PAN::isMemIntrinsic(Sym->getName()))
185 LibcallDecls.push_back(createESName(Sym->getName()));
190 case MachineOperand::MO_ExternalSymbol: {
191 const char *Sname = MO.getSymbolName();
193 // If its a libcall name, record it to decls section.
194 if (PAN::getSymbolTag(Sname) == PAN::LIBCALL)
195 LibcallDecls.push_back(Sname);
197 // Record a call to intrinsic to print the extern declaration for it.
198 std::string Sym = Sname;
199 if (PAN::isMemIntrinsic(Sym)) {
200 Sym = PAN::addPrefix(Sym);
201 LibcallDecls.push_back(createESName(Sym));
207 case MachineOperand::MO_MachineBasicBlock:
208 O << *MO.getMBB()->getSymbol(OutContext);
212 llvm_unreachable(" Operand type not supported.");
216 /// printCCOperand - Print the cond code operand.
218 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
219 int CC = (int)MI->getOperand(opNum).getImm();
220 O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
223 // This function is used to sort the decls list.
224 // should return true if s1 should come before s2.
225 static bool is_before(const char *s1, const char *s2) {
226 return strcmp(s1, s2) <= 0;
229 // This is used by list::unique below.
230 // unique will filter out duplicates if it knows them.
231 static bool is_duplicate(const char *s1, const char *s2) {
232 return !strcmp(s1, s2);
235 /// printLibcallDecls - print the extern declarations for compiler
238 void PIC16AsmPrinter::printLibcallDecls() {
239 // If no libcalls used, return.
240 if (LibcallDecls.empty()) return;
242 O << MAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
243 // Remove duplicate entries.
244 LibcallDecls.sort(is_before);
245 LibcallDecls.unique(is_duplicate);
247 for (std::list<const char*>::const_iterator I = LibcallDecls.begin();
248 I != LibcallDecls.end(); I++) {
249 O << MAI->getExternDirective() << *I << "\n";
250 O << MAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
251 O << MAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
253 O << MAI->getCommentString() << "External decls for libcalls - END." <<"\n";
256 /// doInitialization - Perform Module level initializations here.
257 /// One task that we do here is to sectionize all global variables.
258 /// The MemSelOptimizer pass depends on the sectionizing.
260 bool PIC16AsmPrinter::doInitialization(Module &M) {
261 bool Result = AsmPrinter::doInitialization(M);
263 // Every asmbly contains these std headers.
264 O << "\n#include p16f1xxx.inc";
265 O << "\n#include stdmacros.inc";
267 // Set the section names for all globals.
268 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
271 // Record External Var Decls.
272 if (I->isDeclaration()) {
273 ExternalVarDecls.push_back(I);
277 // Record Exteranl Var Defs.
278 if (I->hasExternalLinkage() || I->hasCommonLinkage()) {
279 ExternalVarDefs.push_back(I);
282 // Sectionify actual data.
283 if (!I->hasAvailableExternallyLinkage()) {
284 const MCSection *S = getObjFileLowering().SectionForGlobal(I, Mang, TM);
286 I->setSection(((const PIC16Section *)S)->getName());
290 DbgInfo.BeginModule(M);
291 EmitFunctionDecls(M);
292 EmitUndefinedVars(M);
302 /// Emit extern decls for functions imported from other modules, and emit
303 /// global declarations for function defined in this module and which are
304 /// available to other modules.
306 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
307 // Emit declarations for external functions.
308 O <<"\n"<<MAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
309 for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
310 if (I->isIntrinsic() || I->getName() == "@abort")
313 if (!I->isDeclaration() && !I->hasExternalLinkage())
316 MCSymbol *Sym = GetGlobalValueSymbol(I);
318 // Do not emit memcpy, memset, and memmove here.
319 // Calls to these routines can be generated in two ways,
320 // 1. User calling the standard lib function
321 // 2. Codegen generating these calls for llvm intrinsics.
322 // In the first case a prototype is alread availale, while in
323 // second case the call is via and externalsym and the prototype is missing.
324 // So declarations for these are currently always getting printing by
325 // tracking both kind of references in printInstrunction.
326 if (I->isDeclaration() && PAN::isMemIntrinsic(Sym->getName())) continue;
328 const char *directive = I->isDeclaration() ? MAI->getExternDirective() :
329 MAI->getGlobalDirective();
331 O << directive << Sym->getName() << "\n";
332 O << directive << PAN::getRetvalLabel(Sym->getName()) << "\n";
333 O << directive << PAN::getArgsLabel(Sym->getName()) << "\n";
336 O << MAI->getCommentString() << "Function Declarations - END." <<"\n";
339 // Emit variables imported from other Modules.
340 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
341 std::vector<const GlobalVariable*> Items = ExternalVarDecls;
342 if (!Items.size()) return;
344 O << "\n" << MAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
345 for (unsigned j = 0; j < Items.size(); j++)
346 O << MAI->getExternDirective() << *GetGlobalValueSymbol(Items[j]) << "\n";
347 O << MAI->getCommentString() << "Imported Variables - END" << "\n";
350 // Emit variables defined in this module and are available to other modules.
351 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
352 std::vector<const GlobalVariable*> Items = ExternalVarDefs;
353 if (!Items.size()) return;
355 O << "\n" << MAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
356 for (unsigned j = 0; j < Items.size(); j++)
357 O << MAI->getGlobalDirective() << *GetGlobalValueSymbol(Items[j]) << "\n";
358 O << MAI->getCommentString() << "Exported Variables - END" << "\n";
361 // Emit initialized data placed in ROM.
362 void PIC16AsmPrinter::EmitRomData(Module &M) {
363 EmitSingleSection(PTOF->ROMDATASection());
366 // Emit Shared section udata.
367 void PIC16AsmPrinter::EmitSharedUdata(Module &M) {
368 EmitSingleSection(PTOF->SHAREDUDATASection());
371 bool PIC16AsmPrinter::doFinalization(Module &M) {
374 DbgInfo.EndModule(M);
375 O << "\n\t" << "END\n";
376 return AsmPrinter::doFinalization(M);
379 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
380 const Function *F = MF.getFunction();
381 const TargetData *TD = TM.getTargetData();
382 // Emit the data section name.
385 PIC16Section *fPDataSection =
386 const_cast<PIC16Section *>(getObjFileLowering().
387 SectionForFrame(CurrentFnSym->getName()));
389 fPDataSection->setColor(getFunctionColor(F));
390 OutStreamer.SwitchSection(fPDataSection);
392 // Emit function frame label
393 O << PAN::getFrameLabel(CurrentFnSym->getName()) << ":\n";
395 const Type *RetType = F->getReturnType();
396 unsigned RetSize = 0;
397 if (RetType->getTypeID() != Type::VoidTyID)
398 RetSize = TD->getTypeAllocSize(RetType);
400 //Emit function return value space
401 // FIXME: Do not emit RetvalLable when retsize is zero. To do this
402 // we will need to avoid printing a global directive for Retval label
403 // in emitExternandGloblas.
405 O << PAN::getRetvalLabel(CurrentFnSym->getName())
406 << " RES " << RetSize << "\n";
408 O << PAN::getRetvalLabel(CurrentFnSym->getName()) << ": \n";
410 // Emit variable to hold the space for function arguments
411 unsigned ArgSize = 0;
412 for (Function::const_arg_iterator argi = F->arg_begin(),
413 arge = F->arg_end(); argi != arge ; ++argi) {
414 const Type *Ty = argi->getType();
415 ArgSize += TD->getTypeAllocSize(Ty);
418 O << PAN::getArgsLabel(CurrentFnSym->getName()) << " RES " << ArgSize << "\n";
420 // Emit temporary space
421 int TempSize = PTLI->GetTmpSize();
423 O << PAN::getTempdataLabel(CurrentFnSym->getName()) << " RES "
428 void PIC16AsmPrinter::EmitInitializedDataSection(const PIC16Section *S) {
429 /// Emit Section header.
430 OutStreamer.SwitchSection(S);
432 std::vector<const GlobalVariable*> Items = S->Items;
433 for (unsigned j = 0; j < Items.size(); j++) {
434 Constant *C = Items[j]->getInitializer();
435 int AddrSpace = Items[j]->getType()->getAddressSpace();
436 O << *GetGlobalValueSymbol(Items[j]);
437 EmitGlobalConstant(C, AddrSpace);
441 // Print all IDATA sections.
442 void PIC16AsmPrinter::EmitIData(Module &M) {
443 EmitSectionList (M, PTOF->IDATASections());
446 void PIC16AsmPrinter::
447 EmitUninitializedDataSection(const PIC16Section *S) {
448 const TargetData *TD = TM.getTargetData();
449 OutStreamer.SwitchSection(S);
450 std::vector<const GlobalVariable*> Items = S->Items;
451 for (unsigned j = 0; j < Items.size(); j++) {
452 Constant *C = Items[j]->getInitializer();
453 const Type *Ty = C->getType();
454 unsigned Size = TD->getTypeAllocSize(Ty);
455 O << *GetGlobalValueSymbol(Items[j]) << " RES " << Size << "\n";
459 // Print all UDATA sections.
460 void PIC16AsmPrinter::EmitUData(Module &M) {
461 EmitSectionList (M, PTOF->UDATASections());
464 // Print all USER sections.
465 void PIC16AsmPrinter::EmitUserSections(Module &M) {
466 EmitSectionList (M, PTOF->USERSections());
469 // Print all AUTO sections.
470 void PIC16AsmPrinter::EmitAllAutos(Module &M) {
471 EmitSectionList (M, PTOF->AUTOSections());
474 extern "C" void LLVMInitializePIC16AsmPrinter() {
475 RegisterAsmPrinter<PIC16AsmPrinter> X(ThePIC16Target);
478 // Emit one data section using correct section emitter based on section type.
479 void PIC16AsmPrinter::EmitSingleSection(const PIC16Section *S) {
480 if (S == NULL) return;
482 switch (S->getType()) {
483 default: llvm_unreachable ("unknow user section type");
487 EmitUninitializedDataSection(S);
491 EmitInitializedDataSection(S);
496 // Emit a list of sections.
497 void PIC16AsmPrinter::
498 EmitSectionList(Module &M, const std::vector<PIC16Section *> &SList) {
499 for (unsigned i = 0; i < SList.size(); i++) {
500 // Exclude llvm specific metadata sections.
501 if (SList[i]->getName().find("llvm.") != std::string::npos)
504 EmitSingleSection(SList[i]);