6a4d0d62712121f73e16410b851158f0591482a1
[oota-llvm.git] / lib / Target / PIC16 / PIC16DebugInfo.cpp
1
2 //===-- PIC16DebugInfo.cpp - Implementation for PIC16 Debug Information ======//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source 
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains the helper functions for representing debug information.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PIC16.h"
16 #include "PIC16ABINames.h"
17 #include "PIC16DebugInfo.h" 
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Support/DebugLoc.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 using namespace llvm;
26
27 /// PopulateDebugInfo - Populate the TypeNo, Aux[] and TagName from Ty.
28 ///
29 void PIC16DbgInfo::PopulateDebugInfo (DIType Ty, unsigned short &TypeNo,
30                                       bool &HasAux, int Aux[], 
31                                       std::string &TagName) {
32   if (Ty.isBasicType())
33     PopulateBasicTypeInfo (Ty, TypeNo);
34   else if (Ty.isCompositeType())
35     PopulateCompositeTypeInfo (Ty, TypeNo, HasAux, Aux, TagName);
36   else if (Ty.isDerivedType())
37     PopulateDerivedTypeInfo (Ty, TypeNo, HasAux, Aux, TagName);
38   else {
39     TypeNo = PIC16Dbg::T_NULL;
40     HasAux = false;
41   }
42   return;
43 }
44
45 /// PopulateBasicTypeInfo- Populate TypeNo for basic type from Ty.
46 ///
47 void PIC16DbgInfo::PopulateBasicTypeInfo (DIType Ty, unsigned short &TypeNo) {
48   std::string Name = Ty.getName();
49   unsigned short BaseTy = GetTypeDebugNumber(Name);
50   TypeNo = TypeNo << PIC16Dbg::S_BASIC;
51   TypeNo = TypeNo | (0xffff & BaseTy);
52 }
53
54 /// PopulateDerivedTypeInfo - Populate TypeNo, Aux[], TagName for derived type 
55 /// from Ty. Derived types are mostly pointers.
56 ///
57 void PIC16DbgInfo::PopulateDerivedTypeInfo (DIType Ty, unsigned short &TypeNo,
58                                             bool &HasAux, int Aux[],
59                                             std::string &TagName) {
60
61   switch(Ty.getTag())
62   {
63     case dwarf::DW_TAG_pointer_type:
64       TypeNo = TypeNo << PIC16Dbg::S_DERIVED;
65       TypeNo = TypeNo | PIC16Dbg::DT_PTR;
66       break;
67     default:
68       TypeNo = TypeNo << PIC16Dbg::S_DERIVED;
69   }
70   
71   // We also need to encode the information about the base type of
72   // pointer in TypeNo.
73   DIType BaseType = DIDerivedType(Ty).getTypeDerivedFrom();
74   PopulateDebugInfo(BaseType, TypeNo, HasAux, Aux, TagName);
75 }
76
77 /// PopulateArrayTypeInfo - Populate TypeNo, Aux[] for array from Ty.
78 void PIC16DbgInfo::PopulateArrayTypeInfo (DIType Ty, unsigned short &TypeNo,
79                                           bool &HasAux, int Aux[],
80                                           std::string &TagName) {
81
82   DICompositeType CTy = DICompositeType(Ty);
83   DIArray Elements = CTy.getTypeArray();
84   unsigned short size = 1;
85   unsigned short Dimension[4]={0,0,0,0};
86   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
87     DIDescriptor Element = Elements.getElement(i);
88     if (Element.getTag() == dwarf::DW_TAG_subrange_type) {
89       TypeNo = TypeNo << PIC16Dbg::S_DERIVED;
90       TypeNo = TypeNo | PIC16Dbg::DT_ARY;
91       DISubrange SubRange = DISubrange(Element);
92       Dimension[i] = SubRange.getHi() - SubRange.getLo() + 1;
93       // Each dimension is represented by 2 bytes starting at byte 9.
94       Aux[8+i*2+0] = Dimension[i];
95       Aux[8+i*2+1] = Dimension[i] >> 8;
96       size = size * Dimension[i];
97     }
98   }
99   HasAux = true;
100   // In auxillary entry for array, 7th and 8th byte represent array size.
101   Aux[6] = size & 0xff;
102   Aux[7] = size >> 8;
103   DIType BaseType = CTy.getTypeDerivedFrom();
104   PopulateDebugInfo(BaseType, TypeNo, HasAux, Aux, TagName);
105 }
106
107 /// PopulateStructOrUnionTypeInfo - Populate TypeNo, Aux[] , TagName for 
108 /// structure or union.
109 ///
110 void PIC16DbgInfo::PopulateStructOrUnionTypeInfo (DIType Ty, 
111                                                   unsigned short &TypeNo,
112                                                   bool &HasAux, int Aux[],
113                                                   std::string &TagName) {
114   DICompositeType CTy = DICompositeType(Ty);
115   TypeNo = TypeNo << PIC16Dbg::S_BASIC;
116   if (Ty.getTag() == dwarf::DW_TAG_structure_type)
117     TypeNo = TypeNo | PIC16Dbg::T_STRUCT;
118   else
119     TypeNo = TypeNo | PIC16Dbg::T_UNION;
120   TagName = CTy.getName();
121   // UniqueSuffix is .number where number is obtained from
122   // llvm.dbg.composite<number>.
123   // FIXME: This will break when composite type is not represented by
124   // llvm.dbg.composite* global variable. Since we need to revisit 
125   // PIC16DebugInfo implementation anyways after the MDNodes based 
126   // framework is done, let us continue with the way it is.
127   std::string UniqueSuffix = "." + Ty->getNameStr().substr(18);
128   TagName += UniqueSuffix;
129   unsigned short size = CTy.getSizeInBits()/8;
130   // 7th and 8th byte represent size.
131   HasAux = true;
132   Aux[6] = size & 0xff;
133   Aux[7] = size >> 8;
134 }
135
136 /// PopulateEnumTypeInfo - Populate TypeNo for enum from Ty.
137 void PIC16DbgInfo::PopulateEnumTypeInfo (DIType Ty, unsigned short &TypeNo) {
138   TypeNo = TypeNo << PIC16Dbg::S_BASIC;
139   TypeNo = TypeNo | PIC16Dbg::T_ENUM;
140 }
141
142 /// PopulateCompositeTypeInfo - Populate TypeNo, Aux[] and TagName for 
143 /// composite types from Ty.
144 ///
145 void PIC16DbgInfo::PopulateCompositeTypeInfo (DIType Ty, unsigned short &TypeNo,
146                                               bool &HasAux, int Aux[],
147                                               std::string &TagName) {
148   switch (Ty.getTag()) {
149     case dwarf::DW_TAG_array_type: {
150       PopulateArrayTypeInfo (Ty, TypeNo, HasAux, Aux, TagName);
151       break;
152     }
153     case dwarf:: DW_TAG_union_type:
154     case dwarf::DW_TAG_structure_type: {
155       PopulateStructOrUnionTypeInfo (Ty, TypeNo, HasAux, Aux, TagName);
156       break;
157     }
158     case dwarf::DW_TAG_enumeration_type: {
159       PopulateEnumTypeInfo (Ty, TypeNo);
160       break;
161     }
162     default:
163       TypeNo = TypeNo << PIC16Dbg::S_DERIVED;
164   }
165 }
166
167 /// GetTypeDebugNumber - Get debug type number for given type.
168 ///
169 unsigned PIC16DbgInfo::GetTypeDebugNumber(std::string &type)  {
170   if (type == "char")
171     return PIC16Dbg::T_CHAR;
172   else if (type == "short")
173     return PIC16Dbg::T_SHORT;
174   else if (type == "int")
175     return PIC16Dbg::T_INT;
176   else if (type == "long")
177     return PIC16Dbg::T_LONG;
178   else if (type == "unsigned char")
179     return PIC16Dbg::T_UCHAR;
180   else if (type == "unsigned short")
181     return PIC16Dbg::T_USHORT;
182   else if (type == "unsigned int")
183     return PIC16Dbg::T_UINT;
184   else if (type == "unsigned long")
185     return PIC16Dbg::T_ULONG;
186   else
187     return 0;
188 }
189  
190 /// GetStorageClass - Get storage class for give debug variable.
191 ///
192 short PIC16DbgInfo::getStorageClass(DIGlobalVariable DIGV) {
193   short ClassNo;
194   if (PAN::isLocalName(DIGV.getName())) {
195     // Generating C_AUTO here fails due to error in linker. Change it once
196     // linker is fixed.
197     ClassNo = PIC16Dbg::C_STAT;
198   }
199   else if (DIGV.isLocalToUnit())
200     ClassNo = PIC16Dbg::C_STAT;
201   else
202     ClassNo = PIC16Dbg::C_EXT;
203   return ClassNo;
204 }
205
206 /// BeginModule - Emit necessary debug info to start a Module and do other
207 /// required initializations.
208 void PIC16DbgInfo::BeginModule(Module &M) {
209   // Emit file directive for module.
210   DebugInfoFinder DbgFinder;
211   DbgFinder.processModule(M);
212   if (DbgFinder.compile_unit_count() != 0) {
213     // FIXME : What if more then one CUs are present in a module ?
214     MDNode *CU = *DbgFinder.compile_unit_begin();
215     EmitDebugDirectives = true;
216     SwitchToCU(CU);
217   }
218   // Emit debug info for decls of composite types.
219   EmitCompositeTypeDecls(M);
220 }
221
222 /// Helper to find first valid debug loc for a function.
223 ///
224 static const DebugLoc GetDebugLocForFunction(const MachineFunction &MF) {
225   DebugLoc DL;
226   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
227        I != E; ++I) {
228     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
229          II != E; ++II) {
230       DL = II->getDebugLoc();
231       if (!DL.isUnknown())
232         return DL;
233     }
234   }
235   return DL;
236 }
237
238 /// BeginFunction - Emit necessary debug info to start a function.
239 ///
240 void PIC16DbgInfo::BeginFunction(const MachineFunction &MF) {
241   if (! EmitDebugDirectives) return;
242   
243   // Retreive the first valid debug Loc and process it.
244   const DebugLoc &DL = GetDebugLocForFunction(MF);
245   // Emit debug info only if valid debug info is available.
246   if (!DL.isUnknown()) {
247     ChangeDebugLoc(MF, DL, true);
248     EmitFunctBeginDI(MF.getFunction());
249   } 
250   // Set current line to 0 so that.line directive is genearted after .bf.
251   CurLine = 0;
252 }
253
254 /// ChangeDebugLoc - Take necessary steps when DebugLoc changes.
255 /// CurFile and CurLine may change as a result of this.
256 ///
257 void PIC16DbgInfo::ChangeDebugLoc(const MachineFunction &MF,  
258                                   const DebugLoc &DL, bool IsInBeginFunction) {
259   if (!EmitDebugDirectives) return;
260   assert(!DL.isUnknown() && "can't change to invalid debug loc");
261
262   SwitchToCU(DL.getScope(MF.getFunction()->getContext()));
263   SwitchToLine(DL.getLine(), IsInBeginFunction);
264 }
265
266 /// SwitchToLine - Emit line directive for a new line.
267 ///
268 void PIC16DbgInfo::SwitchToLine(unsigned Line, bool IsInBeginFunction) {
269   if (CurLine == Line) return;
270   if (!IsInBeginFunction)
271     OS.EmitRawText("\n\t.line " + Twine(Line));
272   CurLine = Line;
273 }
274
275 /// EndFunction - Emit .ef for end of function.
276 ///
277 void PIC16DbgInfo::EndFunction(const MachineFunction &MF) {
278   if (! EmitDebugDirectives) return;
279   const DebugLoc &DL = GetDebugLocForFunction(MF);
280   // Emit debug info only if valid debug info is available.
281   if (!DL.isUnknown())
282     EmitFunctEndDI(MF.getFunction(), CurLine);
283 }
284
285 /// EndModule - Emit .eof for end of module.
286 ///
287 void PIC16DbgInfo::EndModule(Module &M) {
288   if (! EmitDebugDirectives) return;
289   EmitVarDebugInfo(M);
290   if (CurFile != "") OS.EmitRawText(StringRef("\n\t.eof"));
291 }
292  
293 /// EmitCompositeTypeElements - Emit debug information for members of a 
294 /// composite type.
295 /// 
296 void PIC16DbgInfo::EmitCompositeTypeElements (DICompositeType CTy,
297                                               std::string SuffixNo) {
298   unsigned long Value = 0;
299   DIArray Elements = CTy.getTypeArray();
300   for (unsigned i = 0, N = Elements.getNumElements(); i < N; i++) {
301     DIDescriptor Element = Elements.getElement(i);
302     unsigned short TypeNo = 0;
303     bool HasAux = false;
304     int ElementAux[PIC16Dbg::AuxSize] = { 0 };
305     std::string TagName = "";
306     DIDerivedType DITy(Element);
307     unsigned short ElementSize = DITy.getSizeInBits()/8;
308     // Get mangleddd name for this structure/union  element.
309     std::string MangMemName = DITy.getName().str() + SuffixNo;
310     PopulateDebugInfo(DITy, TypeNo, HasAux, ElementAux, TagName);
311     short Class = 0;
312     if( CTy.getTag() == dwarf::DW_TAG_union_type)
313       Class = PIC16Dbg::C_MOU;
314     else if  (CTy.getTag() == dwarf::DW_TAG_structure_type)
315       Class = PIC16Dbg::C_MOS;
316     EmitSymbol(MangMemName.c_str(), Class, TypeNo, Value);
317     if (CTy.getTag() == dwarf::DW_TAG_structure_type)
318       Value += ElementSize;
319     if (HasAux)
320       EmitAuxEntry(MangMemName.c_str(), ElementAux, PIC16Dbg::AuxSize, TagName);
321   }
322 }
323
324 /// EmitCompositeTypeDecls - Emit composite type declarations like structure 
325 /// and union declarations.
326 ///
327 void PIC16DbgInfo::EmitCompositeTypeDecls(Module &M) {
328   DebugInfoFinder DbgFinder;
329   DbgFinder.processModule(M);
330   for (DebugInfoFinder::iterator I = DbgFinder.type_begin(),
331          E = DbgFinder.type_end(); I != E; ++I) {
332     DICompositeType CTy(*I);
333     if (!CTy.Verify())
334       continue;
335     if (CTy.getTag() == dwarf::DW_TAG_union_type ||
336         CTy.getTag() == dwarf::DW_TAG_structure_type ) {
337       // Get the number after llvm.dbg.composite and make UniqueSuffix from 
338       // it.
339       std::string DIVar = CTy->getNameStr();
340       std::string UniqueSuffix = "." + DIVar.substr(18);
341       std::string MangledCTyName = CTy.getName().str() + UniqueSuffix;
342       unsigned short size = CTy.getSizeInBits()/8;
343       int Aux[PIC16Dbg::AuxSize] = {0};
344       // 7th and 8th byte represent size of structure/union.
345       Aux[6] = size & 0xff;
346       Aux[7] = size >> 8;
347       // Emit .def for structure/union tag.
348       if( CTy.getTag() == dwarf::DW_TAG_union_type)
349         EmitSymbol(MangledCTyName.c_str(), PIC16Dbg::C_UNTAG);
350       else if  (CTy.getTag() == dwarf::DW_TAG_structure_type) 
351         EmitSymbol(MangledCTyName.c_str(), PIC16Dbg::C_STRTAG);
352       
353       // Emit auxiliary debug information for structure/union tag. 
354       EmitAuxEntry(MangledCTyName.c_str(), Aux, PIC16Dbg::AuxSize);
355       
356       // Emit members.
357       EmitCompositeTypeElements (CTy, UniqueSuffix);
358       
359       // Emit mangled Symbol for end of structure/union.
360       std::string EOSSymbol = ".eos" + UniqueSuffix;
361       EmitSymbol(EOSSymbol.c_str(), PIC16Dbg::C_EOS);
362       EmitAuxEntry(EOSSymbol.c_str(), Aux, PIC16Dbg::AuxSize, 
363                    MangledCTyName.c_str());
364     }
365   }
366 }
367
368
369 /// EmitFunctBeginDI - Emit .bf for function.
370 ///
371 void PIC16DbgInfo::EmitFunctBeginDI(const Function *F) {
372   std::string FunctName = F->getName();
373   if (EmitDebugDirectives) {
374     std::string FunctBeginSym = ".bf." + FunctName;
375     std::string BlockBeginSym = ".bb." + FunctName;
376
377     int BFAux[PIC16Dbg::AuxSize] = {0};
378     BFAux[4] = CurLine;
379     BFAux[5] = CurLine >> 8;
380
381     // Emit debug directives for beginning of function.
382     EmitSymbol(FunctBeginSym, PIC16Dbg::C_FCN);
383     EmitAuxEntry(FunctBeginSym, BFAux, PIC16Dbg::AuxSize);
384
385     EmitSymbol(BlockBeginSym, PIC16Dbg::C_BLOCK);
386     EmitAuxEntry(BlockBeginSym, BFAux, PIC16Dbg::AuxSize);
387   }
388 }
389
390 /// EmitFunctEndDI - Emit .ef for function end.
391 ///
392 void PIC16DbgInfo::EmitFunctEndDI(const Function *F, unsigned Line) {
393   std::string FunctName = F->getName();
394   if (EmitDebugDirectives) {
395     std::string FunctEndSym = ".ef." + FunctName;
396     std::string BlockEndSym = ".eb." + FunctName;
397
398     // Emit debug directives for end of function.
399     EmitSymbol(BlockEndSym, PIC16Dbg::C_BLOCK);
400     int EFAux[PIC16Dbg::AuxSize] = {0};
401     // 5th and 6th byte stand for line number.
402     EFAux[4] = CurLine;
403     EFAux[5] = CurLine >> 8;
404     EmitAuxEntry(BlockEndSym, EFAux, PIC16Dbg::AuxSize);
405     EmitSymbol(FunctEndSym, PIC16Dbg::C_FCN);
406     EmitAuxEntry(FunctEndSym, EFAux, PIC16Dbg::AuxSize);
407   }
408 }
409
410 /// EmitAuxEntry - Emit Auxiliary debug information.
411 ///
412 void PIC16DbgInfo::EmitAuxEntry(const std::string VarName, int Aux[], int Num,
413                                 std::string TagName) {
414   std::string Tmp;
415   // TagName is emitted in case of structure/union objects.
416   if (!TagName.empty()) Tmp += ", " + TagName;
417   
418   for (int i = 0; i<Num; i++)
419     Tmp += "," + utostr(Aux[i] && 0xff);
420   
421   OS.EmitRawText("\n\t.dim " + Twine(VarName) + ", 1" + Tmp);
422 }
423
424 /// EmitSymbol - Emit .def for a symbol. Value is offset for the member.
425 ///
426 void PIC16DbgInfo::EmitSymbol(std::string Name, short Class,
427                               unsigned short Type, unsigned long Value) {
428   std::string Tmp;
429   if (Value > 0)
430     Tmp = ", value = " + utostr(Value);
431   
432   OS.EmitRawText("\n\t.def " + Twine(Name) + ", type = " + utostr(Type) +
433                  ", class = " + utostr(Class) + Tmp);
434 }
435
436 /// EmitVarDebugInfo - Emit debug information for all variables.
437 ///
438 void PIC16DbgInfo::EmitVarDebugInfo(Module &M) {
439   DebugInfoFinder DbgFinder;
440   DbgFinder.processModule(M);
441   
442   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
443          E = DbgFinder.global_variable_end(); I != E; ++I) {
444     DIGlobalVariable DIGV(*I);
445     DIType Ty = DIGV.getType();
446     unsigned short TypeNo = 0;
447     bool HasAux = false;
448     int Aux[PIC16Dbg::AuxSize] = { 0 };
449     std::string TagName = "";
450     std::string VarName = DIGV.getName();
451     VarName = MAI->getGlobalPrefix() + VarName;
452     PopulateDebugInfo(Ty, TypeNo, HasAux, Aux, TagName);
453     // Emit debug info only if type information is availaible.
454     if (TypeNo != PIC16Dbg::T_NULL) {
455       OS.EmitRawText("\t.type " + Twine(VarName) + ", " + Twine(TypeNo));
456       short ClassNo = getStorageClass(DIGV);
457       OS.EmitRawText("\t.class " + Twine(VarName) + ", " + Twine(ClassNo));
458       if (HasAux)
459         EmitAuxEntry(VarName, Aux, PIC16Dbg::AuxSize, TagName);
460     }
461   }
462 }
463
464 /// SwitchToCU - Switch to a new compilation unit.
465 ///
466 void PIC16DbgInfo::SwitchToCU(MDNode *CU) {
467   // Get the file path from CU.
468   DICompileUnit cu(CU);
469   std::string DirName = cu.getDirectory();
470   std::string FileName = cu.getFilename();
471   std::string FilePath = DirName + "/" + FileName;
472
473   // Nothing to do if source file is still same.
474   if ( FilePath == CurFile ) return;
475
476   // Else, close the current one and start a new.
477   if (CurFile != "")
478     OS.EmitRawText(StringRef("\t.eof"));
479   OS.EmitRawText("\n\t.file\t\"" + Twine(FilePath) + "\"");
480   CurFile = FilePath;
481   CurLine = 0;
482 }
483
484 /// EmitEOF - Emit .eof for end of file.
485 ///
486 void PIC16DbgInfo::EmitEOF() {
487   if (CurFile != "")
488     OS.EmitRawText(StringRef("\t.EOF"));
489 }
490