7ca061b1bda4b6c6788dd1f8dab498aea55dcd20
[oota-llvm.git] / lib / CodeGen / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Module.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineDebugInfo.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Mangler.h"
23 #include "llvm/Target/TargetMachine.h"
24
25 #include <iostream>
26
27 using namespace llvm;
28
29 static cl::opt<bool>
30 DwarfVerbose("dwarf-verbose", cl::Hidden,
31                                 cl::desc("Add comments to Dwarf directives."));
32
33 //===----------------------------------------------------------------------===//
34
35 /// TagString - Return the string for the specified tag.
36 ///
37 static const char *TagString(unsigned Tag) {
38   switch(Tag) {
39     case DW_TAG_array_type:                return "TAG_array_type";
40     case DW_TAG_class_type:                return "TAG_class_type";
41     case DW_TAG_entry_point:               return "TAG_entry_point";
42     case DW_TAG_enumeration_type:          return "TAG_enumeration_type";
43     case DW_TAG_formal_parameter:          return "TAG_formal_parameter";
44     case DW_TAG_imported_declaration:      return "TAG_imported_declaration";
45     case DW_TAG_label:                     return "TAG_label";
46     case DW_TAG_lexical_block:             return "TAG_lexical_block";
47     case DW_TAG_member:                    return "TAG_member";
48     case DW_TAG_pointer_type:              return "TAG_pointer_type";
49     case DW_TAG_reference_type:            return "TAG_reference_type";
50     case DW_TAG_compile_unit:              return "TAG_compile_unit";
51     case DW_TAG_string_type:               return "TAG_string_type";
52     case DW_TAG_structure_type:            return "TAG_structure_type";
53     case DW_TAG_subroutine_type:           return "TAG_subroutine_type";
54     case DW_TAG_typedef:                   return "TAG_typedef";
55     case DW_TAG_union_type:                return "TAG_union_type";
56     case DW_TAG_unspecified_parameters:    return "TAG_unspecified_parameters";
57     case DW_TAG_variant:                   return "TAG_variant";
58     case DW_TAG_common_block:              return "TAG_common_block";
59     case DW_TAG_common_inclusion:          return "TAG_common_inclusion";
60     case DW_TAG_inheritance:               return "TAG_inheritance";
61     case DW_TAG_inlined_subroutine:        return "TAG_inlined_subroutine";
62     case DW_TAG_module:                    return "TAG_module";
63     case DW_TAG_ptr_to_member_type:        return "TAG_ptr_to_member_type";
64     case DW_TAG_set_type:                  return "TAG_set_type";
65     case DW_TAG_subrange_type:             return "TAG_subrange_type";
66     case DW_TAG_with_stmt:                 return "TAG_with_stmt";
67     case DW_TAG_access_declaration:        return "TAG_access_declaration";
68     case DW_TAG_base_type:                 return "TAG_base_type";
69     case DW_TAG_catch_block:               return "TAG_catch_block";
70     case DW_TAG_const_type:                return "TAG_const_type";
71     case DW_TAG_constant:                  return "TAG_constant";
72     case DW_TAG_enumerator:                return "TAG_enumerator";
73     case DW_TAG_file_type:                 return "TAG_file_type";
74     case DW_TAG_friend:                    return "TAG_friend";
75     case DW_TAG_namelist:                  return "TAG_namelist";
76     case DW_TAG_namelist_item:             return "TAG_namelist_item";
77     case DW_TAG_packed_type:               return "TAG_packed_type";
78     case DW_TAG_subprogram:                return "TAG_subprogram";
79     case DW_TAG_template_type_parameter:   return "TAG_template_type_parameter";
80     case DW_TAG_template_value_parameter: return "TAG_template_value_parameter";
81     case DW_TAG_thrown_type:               return "TAG_thrown_type";
82     case DW_TAG_try_block:                 return "TAG_try_block";
83     case DW_TAG_variant_part:              return "TAG_variant_part";
84     case DW_TAG_variable:                  return "TAG_variable";
85     case DW_TAG_volatile_type:             return "TAG_volatile_type";
86     case DW_TAG_dwarf_procedure:           return "TAG_dwarf_procedure";
87     case DW_TAG_restrict_type:             return "TAG_restrict_type";
88     case DW_TAG_interface_type:            return "TAG_interface_type";
89     case DW_TAG_namespace:                 return "TAG_namespace";
90     case DW_TAG_imported_module:           return "TAG_imported_module";
91     case DW_TAG_unspecified_type:          return "TAG_unspecified_type";
92     case DW_TAG_partial_unit:              return "TAG_partial_unit";
93     case DW_TAG_imported_unit:             return "TAG_imported_unit";
94     case DW_TAG_condition:                 return "TAG_condition";
95     case DW_TAG_shared_type:               return "TAG_shared_type";
96     case DW_TAG_lo_user:                   return "TAG_lo_user";
97     case DW_TAG_hi_user:                   return "TAG_hi_user";
98   }
99   assert(0 && "Unknown Dwarf Tag");
100   return "";
101 }
102
103 /// ChildrenString - Return the string for the specified children flag.
104 ///
105 static const char *ChildrenString(unsigned Children) {
106   switch(Children) {
107     case DW_CHILDREN_no:                   return "CHILDREN_no";
108     case DW_CHILDREN_yes:                  return "CHILDREN_yes";
109   }
110   assert(0 && "Unknown Dwarf ChildrenFlag");
111   return "";
112 }
113
114 /// AttributeString - Return the string for the specified attribute.
115 ///
116 static const char *AttributeString(unsigned Attribute) {
117   switch(Attribute) {
118     case DW_AT_sibling:                    return "AT_sibling";
119     case DW_AT_location:                   return "AT_location";
120     case DW_AT_name:                       return "AT_name";
121     case DW_AT_ordering:                   return "AT_ordering";
122     case DW_AT_byte_size:                  return "AT_byte_size";
123     case DW_AT_bit_offset:                 return "AT_bit_offset";
124     case DW_AT_bit_size:                   return "AT_bit_size";
125     case DW_AT_stmt_list:                  return "AT_stmt_list";
126     case DW_AT_low_pc:                     return "AT_low_pc";
127     case DW_AT_high_pc:                    return "AT_high_pc";
128     case DW_AT_language:                   return "AT_language";
129     case DW_AT_discr:                      return "AT_discr";
130     case DW_AT_discr_value:                return "AT_discr_value";
131     case DW_AT_visibility:                 return "AT_visibility";
132     case DW_AT_import:                     return "AT_import";
133     case DW_AT_string_length:              return "AT_string_length";
134     case DW_AT_common_reference:           return "AT_common_reference";
135     case DW_AT_comp_dir:                   return "AT_comp_dir";
136     case DW_AT_const_value:                return "AT_const_value";
137     case DW_AT_containing_type:            return "AT_containing_type";
138     case DW_AT_default_value:              return "AT_default_value";
139     case DW_AT_inline:                     return "AT_inline";
140     case DW_AT_is_optional:                return "AT_is_optional";
141     case DW_AT_lower_bound:                return "AT_lower_bound";
142     case DW_AT_producer:                   return "AT_producer";
143     case DW_AT_prototyped:                 return "AT_prototyped";
144     case DW_AT_return_addr:                return "AT_return_addr";
145     case DW_AT_start_scope:                return "AT_start_scope";
146     case DW_AT_bit_stride:                 return "AT_bit_stride";
147     case DW_AT_upper_bound:                return "AT_upper_bound";
148     case DW_AT_abstract_origin:            return "AT_abstract_origin";
149     case DW_AT_accessibility:              return "AT_accessibility";
150     case DW_AT_address_class:              return "AT_address_class";
151     case DW_AT_artificial:                 return "AT_artificial";
152     case DW_AT_base_types:                 return "AT_base_types";
153     case DW_AT_calling_convention:         return "AT_calling_convention";
154     case DW_AT_count:                      return "AT_count";
155     case DW_AT_data_member_location:       return "AT_data_member_location";
156     case DW_AT_decl_column:                return "AT_decl_column";
157     case DW_AT_decl_file:                  return "AT_decl_file";
158     case DW_AT_decl_line:                  return "AT_decl_line";
159     case DW_AT_declaration:                return "AT_declaration";
160     case DW_AT_discr_list:                 return "AT_discr_list";
161     case DW_AT_encoding:                   return "AT_encoding";
162     case DW_AT_external:                   return "AT_external";
163     case DW_AT_frame_base:                 return "AT_frame_base";
164     case DW_AT_friend:                     return "AT_friend";
165     case DW_AT_identifier_case:            return "AT_identifier_case";
166     case DW_AT_macro_info:                 return "AT_macro_info";
167     case DW_AT_namelist_item:              return "AT_namelist_item";
168     case DW_AT_priority:                   return "AT_priority";
169     case DW_AT_segment:                    return "AT_segment";
170     case DW_AT_specification:              return "AT_specification";
171     case DW_AT_static_link:                return "AT_static_link";
172     case DW_AT_type:                       return "AT_type";
173     case DW_AT_use_location:               return "AT_use_location";
174     case DW_AT_variable_parameter:         return "AT_variable_parameter";
175     case DW_AT_virtuality:                 return "AT_virtuality";
176     case DW_AT_vtable_elem_location:       return "AT_vtable_elem_location";
177     case DW_AT_allocated:                  return "AT_allocated";
178     case DW_AT_associated:                 return "AT_associated";
179     case DW_AT_data_location:              return "AT_data_location";
180     case DW_AT_byte_stride:                return "AT_byte_stride";
181     case DW_AT_entry_pc:                   return "AT_entry_pc";
182     case DW_AT_use_UTF8:                   return "AT_use_UTF8";
183     case DW_AT_extension:                  return "AT_extension";
184     case DW_AT_ranges:                     return "AT_ranges";
185     case DW_AT_trampoline:                 return "AT_trampoline";
186     case DW_AT_call_column:                return "AT_call_column";
187     case DW_AT_call_file:                  return "AT_call_file";
188     case DW_AT_call_line:                  return "AT_call_line";
189     case DW_AT_description:                return "AT_description";
190     case DW_AT_binary_scale:               return "AT_binary_scale";
191     case DW_AT_decimal_scale:              return "AT_decimal_scale";
192     case DW_AT_small:                      return "AT_small";
193     case DW_AT_decimal_sign:               return "AT_decimal_sign";
194     case DW_AT_digit_count:                return "AT_digit_count";
195     case DW_AT_picture_string:             return "AT_picture_string";
196     case DW_AT_mutable:                    return "AT_mutable";
197     case DW_AT_threads_scaled:             return "AT_threads_scaled";
198     case DW_AT_explicit:                   return "AT_explicit";
199     case DW_AT_object_pointer:             return "AT_object_pointer";
200     case DW_AT_endianity:                  return "AT_endianity";
201     case DW_AT_elemental:                  return "AT_elemental";
202     case DW_AT_pure:                       return "AT_pure";
203     case DW_AT_recursive:                  return "AT_recursive";
204     case DW_AT_lo_user:                    return "AT_lo_user";
205     case DW_AT_hi_user:                    return "AT_hi_user";
206   }
207   assert(0 && "Unknown Dwarf Attribute");
208   return "";
209 }
210
211 /// FormEncodingString - Return the string for the specified form encoding.
212 ///
213 static const char *FormEncodingString(unsigned Encoding) {
214   switch(Encoding) {
215     case DW_FORM_addr:                     return "FORM_addr";
216     case DW_FORM_block2:                   return "FORM_block2";
217     case DW_FORM_block4:                   return "FORM_block4";
218     case DW_FORM_data2:                    return "FORM_data2";
219     case DW_FORM_data4:                    return "FORM_data4";
220     case DW_FORM_data8:                    return "FORM_data8";
221     case DW_FORM_string:                   return "FORM_string";
222     case DW_FORM_block:                    return "FORM_block";
223     case DW_FORM_block1:                   return "FORM_block1";
224     case DW_FORM_data1:                    return "FORM_data1";
225     case DW_FORM_flag:                     return "FORM_flag";
226     case DW_FORM_sdata:                    return "FORM_sdata";
227     case DW_FORM_strp:                     return "FORM_strp";
228     case DW_FORM_udata:                    return "FORM_udata";
229     case DW_FORM_ref_addr:                 return "FORM_ref_addr";
230     case DW_FORM_ref1:                     return "FORM_ref1";
231     case DW_FORM_ref2:                     return "FORM_ref2";
232     case DW_FORM_ref4:                     return "FORM_ref4";
233     case DW_FORM_ref8:                     return "FORM_ref8";
234     case DW_FORM_ref_udata:                return "FORM_ref_udata";
235     case DW_FORM_indirect:                 return "FORM_indirect";
236   }
237   assert(0 && "Unknown Dwarf Form Encoding");
238   return "";
239 }
240
241 /// OperationEncodingString - Return the string for the specified operation
242 /// encoding.
243 static const char *OperationEncodingString(unsigned Encoding) {
244   switch(Encoding) {
245     case DW_OP_addr:                       return "OP_addr";
246     case DW_OP_deref:                      return "OP_deref";
247     case DW_OP_const1u:                    return "OP_const1u";
248     case DW_OP_const1s:                    return "OP_const1s";
249     case DW_OP_const2u:                    return "OP_const2u";
250     case DW_OP_const2s:                    return "OP_const2s";
251     case DW_OP_const4u:                    return "OP_const4u";
252     case DW_OP_const4s:                    return "OP_const4s";
253     case DW_OP_const8u:                    return "OP_const8u";
254     case DW_OP_const8s:                    return "OP_const8s";
255     case DW_OP_constu:                     return "OP_constu";
256     case DW_OP_consts:                     return "OP_consts";
257     case DW_OP_dup:                        return "OP_dup";
258     case DW_OP_drop:                       return "OP_drop";
259     case DW_OP_over:                       return "OP_over";
260     case DW_OP_pick:                       return "OP_pick";
261     case DW_OP_swap:                       return "OP_swap";
262     case DW_OP_rot:                        return "OP_rot";
263     case DW_OP_xderef:                     return "OP_xderef";
264     case DW_OP_abs:                        return "OP_abs";
265     case DW_OP_and:                        return "OP_and";
266     case DW_OP_div:                        return "OP_div";
267     case DW_OP_minus:                      return "OP_minus";
268     case DW_OP_mod:                        return "OP_mod";
269     case DW_OP_mul:                        return "OP_mul";
270     case DW_OP_neg:                        return "OP_neg";
271     case DW_OP_not:                        return "OP_not";
272     case DW_OP_or:                         return "OP_or";
273     case DW_OP_plus:                       return "OP_plus";
274     case DW_OP_plus_uconst:                return "OP_plus_uconst";
275     case DW_OP_shl:                        return "OP_shl";
276     case DW_OP_shr:                        return "OP_shr";
277     case DW_OP_shra:                       return "OP_shra";
278     case DW_OP_xor:                        return "OP_xor";
279     case DW_OP_skip:                       return "OP_skip";
280     case DW_OP_bra:                        return "OP_bra";
281     case DW_OP_eq:                         return "OP_eq";
282     case DW_OP_ge:                         return "OP_ge";
283     case DW_OP_gt:                         return "OP_gt";
284     case DW_OP_le:                         return "OP_le";
285     case DW_OP_lt:                         return "OP_lt";
286     case DW_OP_ne:                         return "OP_ne";
287     case DW_OP_lit0:                       return "OP_lit0";
288     case DW_OP_lit1:                       return "OP_lit1";
289     case DW_OP_lit31:                      return "OP_lit31";
290     case DW_OP_reg0:                       return "OP_reg0";
291     case DW_OP_reg1:                       return "OP_reg1";
292     case DW_OP_reg31:                      return "OP_reg31";
293     case DW_OP_breg0:                      return "OP_breg0";
294     case DW_OP_breg1:                      return "OP_breg1";
295     case DW_OP_breg31:                     return "OP_breg31";
296     case DW_OP_regx:                       return "OP_regx";
297     case DW_OP_fbreg:                      return "OP_fbreg";
298     case DW_OP_bregx:                      return "OP_bregx";
299     case DW_OP_piece:                      return "OP_piece";
300     case DW_OP_deref_size:                 return "OP_deref_size";
301     case DW_OP_xderef_size:                return "OP_xderef_size";
302     case DW_OP_nop:                        return "OP_nop";
303     case DW_OP_push_object_address:        return "OP_push_object_address";
304     case DW_OP_call2:                      return "OP_call2";
305     case DW_OP_call4:                      return "OP_call4";
306     case DW_OP_call_ref:                   return "OP_call_ref";
307     case DW_OP_form_tls_address:           return "OP_form_tls_address";
308     case DW_OP_call_frame_cfa:             return "OP_call_frame_cfa";
309     case DW_OP_lo_user:                    return "OP_lo_user";
310     case DW_OP_hi_user:                    return "OP_hi_user";
311   }
312   assert(0 && "Unknown Dwarf Operation Encoding");
313   return "";
314 }
315
316 /// AttributeEncodingString - Return the string for the specified attribute
317 /// encoding.
318 static const char *AttributeEncodingString(unsigned Encoding) {
319   switch(Encoding) {
320     case DW_ATE_address:                   return "ATE_address";
321     case DW_ATE_boolean:                   return "ATE_boolean";
322     case DW_ATE_complex_float:             return "ATE_complex_float";
323     case DW_ATE_float:                     return "ATE_float";
324     case DW_ATE_signed:                    return "ATE_signed";
325     case DW_ATE_signed_char:               return "ATE_signed_char";
326     case DW_ATE_unsigned:                  return "ATE_unsigned";
327     case DW_ATE_unsigned_char:             return "ATE_unsigned_char";
328     case DW_ATE_imaginary_float:           return "ATE_imaginary_float";
329     case DW_ATE_packed_decimal:            return "ATE_packed_decimal";
330     case DW_ATE_numeric_string:            return "ATE_numeric_string";
331     case DW_ATE_edited:                    return "ATE_edited";
332     case DW_ATE_signed_fixed:              return "ATE_signed_fixed";
333     case DW_ATE_unsigned_fixed:            return "ATE_unsigned_fixed";
334     case DW_ATE_decimal_float:             return "ATE_decimal_float";
335     case DW_ATE_lo_user:                   return "ATE_lo_user";
336     case DW_ATE_hi_user:                   return "ATE_hi_user";
337   }
338   assert(0 && "Unknown Dwarf Attribute Encoding");
339   return "";
340 }
341
342 /// DecimalSignString - Return the string for the specified decimal sign
343 /// attribute.
344 static const char *DecimalSignString(unsigned Sign) {
345   switch(Sign) {
346     case DW_DS_unsigned:                   return "DS_unsigned";
347     case DW_DS_leading_overpunch:          return "DS_leading_overpunch";
348     case DW_DS_trailing_overpunch:         return "DS_trailing_overpunch";
349     case DW_DS_leading_separate:           return "DS_leading_separate";
350     case DW_DS_trailing_separate:          return "DS_trailing_separate";
351   }
352   assert(0 && "Unknown Dwarf Decimal Sign Attribute");
353   return "";
354 }
355
356 /// EndianityString - Return the string for the specified endianity.
357 ///
358 static const char *EndianityString(unsigned Endian) {
359   switch(Endian) {
360     case DW_END_default:                   return "END_default";
361     case DW_END_big:                       return "END_big";
362     case DW_END_little:                    return "END_little";
363     case DW_END_lo_user:                   return "END_lo_user";
364     case DW_END_hi_user:                   return "END_hi_user";
365   }
366   assert(0 && "Unknown Dwarf Endianity");
367   return "";
368 }
369
370 /// AccessibilityString - Return the string for the specified accessibility.
371 ///
372 static const char *AccessibilityString(unsigned Access) {
373   switch(Access) {
374     // Accessibility codes
375     case DW_ACCESS_public:                 return "ACCESS_public";
376     case DW_ACCESS_protected:              return "ACCESS_protected";
377     case DW_ACCESS_private:                return "ACCESS_private";
378   }
379   assert(0 && "Unknown Dwarf Accessibility");
380   return "";
381 }
382
383 /// VisibilityString - Return the string for the specified visibility.
384 ///
385 static const char *VisibilityString(unsigned Visibility) {
386   switch(Visibility) {
387     case DW_VIS_local:                     return "VIS_local";
388     case DW_VIS_exported:                  return "VIS_exported";
389     case DW_VIS_qualified:                 return "VIS_qualified";
390   }
391   assert(0 && "Unknown Dwarf Visibility");
392   return "";
393 }
394
395 /// VirtualityString - Return the string for the specified virtuality.
396 ///
397 static const char *VirtualityString(unsigned Virtuality) {
398   switch(Virtuality) {
399     case DW_VIRTUALITY_none:               return "VIRTUALITY_none";
400     case DW_VIRTUALITY_virtual:            return "VIRTUALITY_virtual";
401     case DW_VIRTUALITY_pure_virtual:       return "VIRTUALITY_pure_virtual";
402   }
403   assert(0 && "Unknown Dwarf Virtuality");
404   return "";
405 }
406
407 /// LanguageString - Return the string for the specified language.
408 ///
409 static const char *LanguageString(unsigned Language) {
410   switch(Language) {
411     case DW_LANG_C89:                      return "LANG_C89";
412     case DW_LANG_C:                        return "LANG_C";
413     case DW_LANG_Ada83:                    return "LANG_Ada83";
414     case DW_LANG_C_plus_plus:              return "LANG_C_plus_plus";
415     case DW_LANG_Cobol74:                  return "LANG_Cobol74";
416     case DW_LANG_Cobol85:                  return "LANG_Cobol85";
417     case DW_LANG_Fortran77:                return "LANG_Fortran77";
418     case DW_LANG_Fortran90:                return "LANG_Fortran90";
419     case DW_LANG_Pascal83:                 return "LANG_Pascal83";
420     case DW_LANG_Modula2:                  return "LANG_Modula2";
421     case DW_LANG_Java:                     return "LANG_Java";
422     case DW_LANG_C99:                      return "LANG_C99";
423     case DW_LANG_Ada95:                    return "LANG_Ada95";
424     case DW_LANG_Fortran95:                return "LANG_Fortran95";
425     case DW_LANG_PLI:                      return "LANG_PLI";
426     case DW_LANG_ObjC:                     return "LANG_ObjC";
427     case DW_LANG_ObjC_plus_plus:           return "LANG_ObjC_plus_plus";
428     case DW_LANG_UPC:                      return "LANG_UPC";
429     case DW_LANG_D:                        return "LANG_D";
430     case DW_LANG_lo_user:                  return "LANG_lo_user";
431     case DW_LANG_hi_user:                  return "LANG_hi_user";
432   }
433   assert(0 && "Unknown Dwarf Language");
434   return "";
435 }
436
437 /// CaseString - Return the string for the specified identifier case.
438 ///
439 static const char *CaseString(unsigned Case) {
440    switch(Case) {
441     case DW_ID_case_sensitive:             return "ID_case_sensitive";
442     case DW_ID_up_case:                    return "ID_up_case";
443     case DW_ID_down_case:                  return "ID_down_case";
444     case DW_ID_case_insensitive:           return "ID_case_insensitive";
445   }
446   assert(0 && "Unknown Dwarf Identifier Case");
447   return "";
448 }
449
450 /// ConventionString - Return the string for the specified calling convention.
451 ///
452 static const char *ConventionString(unsigned Convention) {
453    switch(Convention) {
454     case DW_CC_normal:                     return "CC_normal";
455     case DW_CC_program:                    return "CC_program";
456     case DW_CC_nocall:                     return "CC_nocall";
457     case DW_CC_lo_user:                    return "CC_lo_user";
458     case DW_CC_hi_user:                    return "CC_hi_user";
459   }
460   assert(0 && "Unknown Dwarf Calling Convention");
461   return "";
462 }
463
464 /// InlineCodeString - Return the string for the specified inline code.
465 ///
466 static const char *InlineCodeString(unsigned Code) {
467    switch(Code) {
468     case DW_INL_not_inlined:               return "INL_not_inlined";
469     case DW_INL_inlined:                   return "INL_inlined";
470     case DW_INL_declared_not_inlined:      return "INL_declared_not_inlined";
471     case DW_INL_declared_inlined:          return "INL_declared_inlined";
472   }
473   assert(0 && "Unknown Dwarf Inline Code");
474   return "";
475 }
476
477 /// ArrayOrderString - Return the string for the specified array order.
478 ///
479 static const char *ArrayOrderString(unsigned Order) {
480    switch(Order) {
481     case DW_ORD_row_major:                 return "ORD_row_major";
482     case DW_ORD_col_major:                 return "ORD_col_major";
483   }
484   assert(0 && "Unknown Dwarf Array Order");
485   return "";
486 }
487
488 /// DiscriminantString - Return the string for the specified discriminant
489 /// descriptor.
490 static const char *DiscriminantString(unsigned Discriminant) {
491    switch(Discriminant) {
492     case DW_DSC_label:                     return "DSC_label";
493     case DW_DSC_range:                     return "DSC_range";
494   }
495   assert(0 && "Unknown Dwarf Discriminant Descriptor");
496   return "";
497 }
498
499 /// LNStandardString - Return the string for the specified line number standard.
500 ///
501 static const char *LNStandardString(unsigned Standard) {
502    switch(Standard) {
503     case DW_LNS_copy:                      return "LNS_copy";
504     case DW_LNS_advance_pc:                return "LNS_advance_pc";
505     case DW_LNS_advance_line:              return "LNS_advance_line";
506     case DW_LNS_set_file:                  return "LNS_set_file";
507     case DW_LNS_set_column:                return "LNS_set_column";
508     case DW_LNS_negate_stmt:               return "LNS_negate_stmt";
509     case DW_LNS_set_basic_block:           return "LNS_set_basic_block";
510     case DW_LNS_const_add_pc:              return "LNS_const_add_pc";
511     case DW_LNS_fixed_advance_pc:          return "LNS_fixed_advance_pc";
512     case DW_LNS_set_prologue_end:          return "LNS_set_prologue_end";
513     case DW_LNS_set_epilogue_begin:        return "LNS_set_epilogue_begin";
514     case DW_LNS_set_isa:                   return "LNS_set_isa";
515   }
516   assert(0 && "Unknown Dwarf Line Number Standard");
517   return "";
518 }
519
520 /// LNExtendedString - Return the string for the specified line number extended
521 /// opcode encodings.
522 static const char *LNExtendedString(unsigned Encoding) {
523    switch(Encoding) {
524     // Line Number Extended Opcode Encodings
525     case DW_LNE_end_sequence:              return "LNE_end_sequence";
526     case DW_LNE_set_address:               return "LNE_set_address";
527     case DW_LNE_define_file:               return "LNE_define_file";
528     case DW_LNE_lo_user:                   return "LNE_lo_user";
529     case DW_LNE_hi_user:                   return "LNE_hi_user";
530   }
531   assert(0 && "Unknown Dwarf Line Number Extended Opcode Encoding");
532   return "";
533 }
534
535 /// MacinfoString - Return the string for the specified macinfo type encodings.
536 ///
537 static const char *MacinfoString(unsigned Encoding) {
538    switch(Encoding) {
539     // Macinfo Type Encodings
540     case DW_MACINFO_define:                return "MACINFO_define";
541     case DW_MACINFO_undef:                 return "MACINFO_undef";
542     case DW_MACINFO_start_file:            return "MACINFO_start_file";
543     case DW_MACINFO_end_file:              return "MACINFO_end_file";
544     case DW_MACINFO_vendor_ext:            return "MACINFO_vendor_ext";
545   }
546   assert(0 && "Unknown Dwarf Macinfo Type Encodings");
547   return "";
548 }
549
550 /// CallFrameString - Return the string for the specified call frame instruction
551 /// encodings.
552 static const char *CallFrameString(unsigned Encoding) {
553    switch(Encoding) {
554     case DW_CFA_advance_loc:               return "CFA_advance_loc";
555     case DW_CFA_offset:                    return "CFA_offset";
556     case DW_CFA_restore:                   return "CFA_restore";
557     case DW_CFA_set_loc:                   return "CFA_set_loc";
558     case DW_CFA_advance_loc1:              return "CFA_advance_loc1";
559     case DW_CFA_advance_loc2:              return "CFA_advance_loc2";
560     case DW_CFA_advance_loc4:              return "CFA_advance_loc4";
561     case DW_CFA_offset_extended:           return "CFA_offset_extended";
562     case DW_CFA_restore_extended:          return "CFA_restore_extended";
563     case DW_CFA_undefined:                 return "CFA_undefined";
564     case DW_CFA_same_value:                return "CFA_same_value";
565     case DW_CFA_register:                  return "CFA_register";
566     case DW_CFA_remember_state:            return "CFA_remember_state";
567     case DW_CFA_restore_state:             return "CFA_restore_state";
568     case DW_CFA_def_cfa:                   return "CFA_def_cfa";
569     case DW_CFA_def_cfa_register:          return "CFA_def_cfa_register";
570     case DW_CFA_def_cfa_offset:            return "CFA_def_cfa_offset";
571     case DW_CFA_def_cfa_expression:        return "CFA_def_cfa_expression";
572     case DW_CFA_expression:                return "CFA_expression";
573     case DW_CFA_offset_extended_sf:        return "CFA_offset_extended_sf";
574     case DW_CFA_def_cfa_sf:                return "CFA_def_cfa_sf";
575     case DW_CFA_def_cfa_offset_sf:         return "CFA_def_cfa_offset_sf";
576     case DW_CFA_val_offset:                return "CFA_val_offset";
577     case DW_CFA_val_offset_sf:             return "CFA_val_offset_sf";
578     case DW_CFA_val_expression:            return "CFA_val_expression";
579     case DW_CFA_lo_user:                   return "CFA_lo_user";
580     case DW_CFA_hi_user:                   return "CFA_hi_user";
581   }
582   assert(0 && "Unknown Dwarf Call Frame Instruction Encodings");
583   return "";
584 }
585
586 //===----------------------------------------------------------------------===//
587
588 /// operator== - Used by UniqueVector to locate entry.
589 ///
590 bool DIEAbbrev::operator==(const DIEAbbrev &DA) const {
591   if (Tag != DA.Tag) return false;
592   if (ChildrenFlag != DA.ChildrenFlag) return false;
593   if (Data.size() != DA.Data.size()) return false;
594   
595   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
596     if (Data[i] != DA.Data[i]) return false;
597   }
598   
599   return true;
600 }
601
602 /// operator< - Used by UniqueVector to locate entry.
603 ///
604 bool DIEAbbrev::operator<(const DIEAbbrev &DA) const {
605   if (Tag != DA.Tag) return Tag < DA.Tag;
606   if (ChildrenFlag != DA.ChildrenFlag) return ChildrenFlag < DA.ChildrenFlag;
607   if (Data.size() != DA.Data.size()) return Data.size() < DA.Data.size();
608   
609   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
610     if (Data[i] != DA.Data[i]) return Data[i] < DA.Data[i];
611   }
612   
613   return false;
614 }
615     
616 /// Emit - Print the abbreviation using the specified Dwarf writer.
617 ///
618 void DIEAbbrev::Emit(const DwarfWriter &DW) const {
619   // Emit its Dwarf tag type.
620   DW.EmitULEB128Bytes(Tag);
621   DW.EOL(TagString(Tag));
622   
623   // Emit whether it has children DIEs.
624   DW.EmitULEB128Bytes(ChildrenFlag);
625   DW.EOL(ChildrenString(ChildrenFlag));
626   
627   // For each attribute description.
628   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
629     const DIEAbbrevData &AttrData = Data[i];
630     
631     // Emit attribute type.
632     DW.EmitULEB128Bytes(AttrData.getAttribute());
633     DW.EOL(AttributeString(AttrData.getAttribute()));
634     
635     // Emit form type.
636     DW.EmitULEB128Bytes(AttrData.getForm());
637     DW.EOL(FormEncodingString(AttrData.getForm()));
638   }
639
640   // Mark end of abbreviation.
641   DW.EmitULEB128Bytes(0); DW.EOL("EOM(1)");
642   DW.EmitULEB128Bytes(0); DW.EOL("EOM(2)");
643 }
644
645 #ifndef NDEBUG
646   void DIEAbbrev::print(std::ostream &O) {
647     O << "Abbreviation @"
648       << std::hex << (unsigned)this << std::dec
649       << "  "
650       << TagString(Tag)
651       << " "
652       << ChildrenString(ChildrenFlag)
653       << "\n";
654     
655     for (unsigned i = 0, N = Data.size(); i < N; ++i) {
656       O << "  "
657         << AttributeString(Data[i].getAttribute())
658         << "  "
659         << FormEncodingString(Data[i].getForm())
660         << "\n";
661     }
662   }
663   void DIEAbbrev::dump() { print(std::cerr); }
664 #endif
665
666 //===----------------------------------------------------------------------===//
667
668 /// EmitValue - Emit integer of appropriate size.
669 ///
670 void DIEInteger::EmitValue(const DwarfWriter &DW, unsigned Form) const {
671   switch (Form) {
672   case DW_FORM_flag:  // Fall thru
673   case DW_FORM_data1: DW.EmitByte(Integer);         break;
674   case DW_FORM_data2: DW.EmitShort(Integer);        break;
675   case DW_FORM_data4: DW.EmitLong(Integer);         break;
676   case DW_FORM_udata: DW.EmitULEB128Bytes(Integer); break;
677   case DW_FORM_sdata: DW.EmitSLEB128Bytes(Integer); break;
678   default: assert(0 && "DIE Value form not supported yet"); break;
679   }
680 }
681
682 /// SizeOf - Determine size of integer value in bytes.
683 ///
684 unsigned DIEInteger::SizeOf(const DwarfWriter &DW, unsigned Form) const {
685   switch (Form) {
686   case DW_FORM_flag:  // Fall thru
687   case DW_FORM_data1: return sizeof(int8_t);
688   case DW_FORM_data2: return sizeof(int16_t);
689   case DW_FORM_data4: return sizeof(int32_t);
690   case DW_FORM_udata: return DW.SizeULEB128(Integer);
691   case DW_FORM_sdata: return DW.SizeSLEB128(Integer);
692   default: assert(0 && "DIE Value form not supported yet"); break;
693   }
694   return 0;
695 }
696
697 //===----------------------------------------------------------------------===//
698
699 /// EmitValue - Emit string value.
700 ///
701 void DIEString::EmitValue(const DwarfWriter &DW, unsigned Form) const {
702   DW.EmitString(String);
703 }
704
705 /// SizeOf - Determine size of string value in bytes.
706 ///
707 unsigned DIEString::SizeOf(const DwarfWriter &DW, unsigned Form) const {
708   return String.size() + sizeof(char); // sizeof('\0');
709 }
710
711 //===----------------------------------------------------------------------===//
712
713 /// EmitValue - Emit label value.
714 ///
715 void DIEDwarfLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
716   DW.EmitReference(Label);
717 }
718
719 /// SizeOf - Determine size of label value in bytes.
720 ///
721 unsigned DIEDwarfLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
722   return DW.getAddressSize();
723 }
724     
725 //===----------------------------------------------------------------------===//
726
727 /// EmitValue - Emit label value.
728 ///
729 void DIEObjectLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
730   DW.EmitByte(sizeof(int8_t) + DW.getAddressSize());
731   DW.EOL("DW_FORM_block1 length");
732   
733   DW.EmitByte(DW_OP_addr);
734   DW.EOL("DW_OP_addr");
735   
736   DW.EmitReference(Label);
737 }
738
739 /// SizeOf - Determine size of label value in bytes.
740 ///
741 unsigned DIEObjectLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
742   return sizeof(int8_t) + sizeof(int8_t) + DW.getAddressSize();
743 }
744     
745 //===----------------------------------------------------------------------===//
746
747 /// EmitValue - Emit delta value.
748 ///
749 void DIEDelta::EmitValue(const DwarfWriter &DW, unsigned Form) const {
750   DW.EmitDifference(LabelHi, LabelLo);
751 }
752
753 /// SizeOf - Determine size of delta value in bytes.
754 ///
755 unsigned DIEDelta::SizeOf(const DwarfWriter &DW, unsigned Form) const {
756   return DW.getAddressSize();
757 }
758
759 //===----------------------------------------------------------------------===//
760 /// EmitValue - Emit extry offset.
761 ///
762 void DIEntry::EmitValue(const DwarfWriter &DW, unsigned Form) const {
763   DW.EmitLong(Entry->getOffset());
764 }
765
766 /// SizeOf - Determine size of label value in bytes.
767 ///
768 unsigned DIEntry::SizeOf(const DwarfWriter &DW, unsigned Form) const {
769   return sizeof(int32_t);
770 }
771     
772 //===----------------------------------------------------------------------===//
773
774 DIE::DIE(unsigned Tag, unsigned ChildrenFlag)
775 : Abbrev(new DIEAbbrev(Tag, ChildrenFlag))
776 , AbbrevID(0)
777 , Offset(0)
778 , Size(0)
779 , Context(NULL)
780 , Children()
781 , Values()
782 {}
783
784 DIE::~DIE() {
785   if (Abbrev) delete Abbrev;
786   
787   for (unsigned i = 0, N = Children.size(); i < N; ++i) {
788     delete Children[i];
789   }
790
791   for (unsigned j = 0, M = Values.size(); j < M; ++j) {
792     delete Values[j];
793   }
794   
795   if (Context) delete Context;
796 }
797     
798 /// AddInt - Add a simple integer attribute data and value.
799 ///
800 void DIE::AddInt(unsigned Attribute, unsigned Form,
801                  int Integer, bool IsSigned) {
802   if (Form == 0) {
803     if (IsSigned) {
804       if ((char)Integer == Integer)       Form = DW_FORM_data1;
805       else if ((short)Integer == Integer) Form = DW_FORM_data2;
806       else                                Form = DW_FORM_data4;
807     } else {
808       if ((unsigned char)Integer == Integer)       Form = DW_FORM_data1;
809       else if ((unsigned short)Integer == Integer) Form = DW_FORM_data2;
810       else                                         Form = DW_FORM_data4;
811     }
812   }
813   Abbrev->AddAttribute(Attribute, Form);
814   Values.push_back(new DIEInteger(Integer));
815 }
816     
817 /// AddString - Add a std::string attribute data and value.
818 ///
819 void DIE::AddString(unsigned Attribute, unsigned Form,
820                     const std::string &String) {
821   Abbrev->AddAttribute(Attribute, Form);
822   Values.push_back(new DIEString(String));
823 }
824     
825 /// AddLabel - Add a Dwarf label attribute data and value.
826 ///
827 void DIE::AddLabel(unsigned Attribute, unsigned Form,
828                    const DWLabel &Label) {
829   Abbrev->AddAttribute(Attribute, Form);
830   Values.push_back(new DIEDwarfLabel(Label));
831 }
832     
833 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
834 ///
835 void DIE::AddObjectLabel(unsigned Attribute, unsigned Form,
836                          const std::string &Label) {
837   Abbrev->AddAttribute(Attribute, Form);
838   Values.push_back(new DIEObjectLabel(Label));
839 }
840     
841 /// AddDelta - Add a label delta attribute data and value.
842 ///
843 void DIE::AddDelta(unsigned Attribute, unsigned Form,
844                    const DWLabel &Hi, const DWLabel &Lo) {
845   Abbrev->AddAttribute(Attribute, Form);
846   Values.push_back(new DIEDelta(Hi, Lo));
847 }
848     
849 /// AddDIEntry - Add a DIE attribute data and value.
850 ///
851 void DIE::AddDIEntry(unsigned Attribute,
852                      unsigned Form, DIE *Entry) {
853   Abbrev->AddAttribute(Attribute, Form);
854   Values.push_back(new DIEntry(Entry));
855 }
856
857 /// Complete - Indicate that all attributes have been added and ready to get an
858 /// abbreviation ID.
859 void DIE::Complete(DwarfWriter &DW) {
860   AbbrevID = DW.NewAbbreviation(Abbrev);
861   delete Abbrev;
862   Abbrev = NULL;
863 }
864
865 /// AddChild - Add a child to the DIE.
866 ///
867 void DIE::AddChild(DIE *Child) {
868   Children.push_back(Child);
869 }
870
871 //===----------------------------------------------------------------------===//
872
873 /// NewBasicType - Creates a new basic type if necessary, then adds to the
874 /// context and owner.
875 DIE *DWContext::NewBasicType(const Type *Ty, unsigned Size, unsigned Align) {
876   DIE *TypeDie = Types[Ty];
877   
878   char *Name;
879   unsigned Encoding;
880   
881   // If first occurance of type.
882   if (!TypeDie) {
883     const char *Name;
884     unsigned Encoding = 0;
885     
886     switch (Ty->getTypeID()) {
887     case Type::UByteTyID:
888       Name = "unsigned char";
889       Encoding = DW_ATE_unsigned_char;
890       break;
891     case Type::SByteTyID:
892       Name = "char";
893       Encoding = DW_ATE_signed_char;
894       break;
895     case Type::UShortTyID:
896       Name = "unsigned short";
897       Encoding = DW_ATE_unsigned;
898       break;
899     case Type::ShortTyID:
900       Name = "short";
901       Encoding = DW_ATE_signed;
902       break;
903     case Type::UIntTyID:
904       Name = "unsigned int";
905       Encoding = DW_ATE_unsigned;
906       break;
907     case Type::IntTyID:
908       Name = "int";
909       Encoding = DW_ATE_signed;
910       break;
911     case Type::ULongTyID:
912       Name = "unsigned long long";
913       Encoding = DW_ATE_unsigned;
914       break;
915     case Type::LongTyID:
916       Name = "long long";
917       Encoding = DW_ATE_signed;
918       break;
919     case Type::FloatTyID:
920       Name = "float";
921       Encoding = DW_ATE_float;
922       break;
923     case Type::DoubleTyID:
924       Name = "float";
925       Encoding = DW_ATE_float;
926       break;
927     default: 
928     // FIXME - handle more complex types.
929       Name = "unknown";
930       Encoding = DW_ATE_address;
931       break;
932     }
933     
934     // construct the type DIE.
935     TypeDie = new DIE(DW_TAG_base_type, DW_CHILDREN_no);
936     TypeDie->AddString(DW_AT_name,      DW_FORM_string, Name);
937     TypeDie->AddInt   (DW_AT_byte_size, DW_FORM_data1,  Size);
938     TypeDie->AddInt   (DW_AT_encoding,  DW_FORM_data1,  Encoding);
939     TypeDie->Complete(DW);
940     
941     // Add to context owner.
942     Owner->AddChild(TypeDie);
943
944     // Add to map.
945     Types[Ty] = TypeDie;
946   }
947   
948   return TypeDie;
949 }
950
951 /// NewGlobalVariable - Creates a global variable, if necessary, then adds in
952 /// the context and owner.
953 DIE *DWContext::NewGlobalVariable(const std::string &Name,
954                                   const std::string &MangledName,
955                                   DIE *Type) {
956   DIE *VariableDie = Variables[MangledName];
957   
958   // If first occurance of variable.
959   if (!VariableDie) {
960     // FIXME - need source file name line number.
961     VariableDie = new DIE(DW_TAG_variable, DW_CHILDREN_no);
962     VariableDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
963     VariableDie->AddInt        (DW_AT_decl_file, 0,              0);
964     VariableDie->AddInt        (DW_AT_decl_line, 0,              0);
965     VariableDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
966     VariableDie->AddInt        (DW_AT_external,  DW_FORM_flag,   1);
967     // FIXME - needs to be a proper expression.
968     VariableDie->AddObjectLabel(DW_AT_location,  DW_FORM_block1, MangledName);
969     VariableDie->Complete(DW);
970  
971     // Add to context owner.
972     Owner->AddChild(VariableDie);
973     
974     // Add to map.
975     Variables[MangledName] = VariableDie;
976   }
977   
978   return VariableDie;
979 }
980
981 //===----------------------------------------------------------------------===//
982
983 /// PrintHex - Print a value as a hexidecimal value.
984 ///
985 void DwarfWriter::PrintHex(int Value) const { 
986   O << "0x" << std::hex << Value << std::dec;
987 }
988
989 /// EOL - Print a newline character to asm stream.  If a comment is present
990 /// then it will be printed first.  Comments should not contain '\n'.
991 void DwarfWriter::EOL(const std::string &Comment) const {
992   if (DwarfVerbose) {
993     O << "\t"
994       << Asm->CommentString
995       << " "
996       << Comment;
997   }
998   O << "\n";
999 }
1000
1001 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
1002 /// unsigned leb128 value.
1003 void DwarfWriter::EmitULEB128Bytes(unsigned Value) const {
1004   if (hasLEB128) {
1005     O << "\t.uleb128\t"
1006       << Value;
1007   } else {
1008     O << Asm->Data8bitsDirective;
1009     PrintULEB128(Value);
1010   }
1011 }
1012
1013 /// EmitSLEB128Bytes - Emit an assembler byte data directive to compose a
1014 /// signed leb128 value.
1015 void DwarfWriter::EmitSLEB128Bytes(int Value) const {
1016   if (hasLEB128) {
1017     O << "\t.sleb128\t"
1018       << Value;
1019   } else {
1020     O << Asm->Data8bitsDirective;
1021     PrintSLEB128(Value);
1022   }
1023 }
1024
1025 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
1026 /// representing an unsigned leb128 value.
1027 void DwarfWriter::PrintULEB128(unsigned Value) const {
1028   do {
1029     unsigned Byte = Value & 0x7f;
1030     Value >>= 7;
1031     if (Value) Byte |= 0x80;
1032     PrintHex(Byte);
1033     if (Value) O << ", ";
1034   } while (Value);
1035 }
1036
1037 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
1038 /// value.
1039 unsigned DwarfWriter::SizeULEB128(unsigned Value) {
1040   unsigned Size = 0;
1041   do {
1042     Value >>= 7;
1043     Size += sizeof(int8_t);
1044   } while (Value);
1045   return Size;
1046 }
1047
1048 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
1049 /// representing a signed leb128 value.
1050 void DwarfWriter::PrintSLEB128(int Value) const {
1051   int Sign = Value >> (8 * sizeof(Value) - 1);
1052   bool IsMore;
1053   
1054   do {
1055     unsigned Byte = Value & 0x7f;
1056     Value >>= 7;
1057     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1058     if (IsMore) Byte |= 0x80;
1059     PrintHex(Byte);
1060     if (IsMore) O << ", ";
1061   } while (IsMore);
1062 }
1063
1064 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
1065 /// value.
1066 unsigned DwarfWriter::SizeSLEB128(int Value) {
1067   unsigned Size = 0;
1068   int Sign = Value >> (8 * sizeof(Value) - 1);
1069   bool IsMore;
1070   
1071   do {
1072     unsigned Byte = Value & 0x7f;
1073     Value >>= 7;
1074     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1075     Size += sizeof(int8_t);
1076   } while (IsMore);
1077   return Size;
1078 }
1079
1080 /// EmitByte - Emit a byte directive and value.
1081 ///
1082 void DwarfWriter::EmitByte(int Value) const {
1083   O << Asm->Data8bitsDirective;
1084   PrintHex(Value);
1085 }
1086
1087 /// EmitShort - Emit a short directive and value.
1088 ///
1089 void DwarfWriter::EmitShort(int Value) const {
1090   O << Asm->Data16bitsDirective;
1091   PrintHex(Value);
1092 }
1093
1094 /// EmitLong - Emit a long directive and value.
1095 ///
1096 void DwarfWriter::EmitLong(int Value) const {
1097   O << Asm->Data32bitsDirective;
1098   PrintHex(Value);
1099 }
1100
1101 /// EmitString - Emit a string with quotes and a null terminator.
1102 /// Special characters are emitted properly. (Eg. '\t')
1103 void DwarfWriter::EmitString(const std::string &String) const {
1104   O << Asm->AsciiDirective
1105     << "\"";
1106   for (unsigned i = 0, N = String.size(); i < N; ++i) {
1107     unsigned char C = String[i];
1108     
1109     if (!isascii(C) || iscntrl(C)) {
1110       switch(C) {
1111       case '\b': O << "\\b"; break;
1112       case '\f': O << "\\f"; break;
1113       case '\n': O << "\\n"; break;
1114       case '\r': O << "\\r"; break;
1115       case '\t': O << "\\t"; break;
1116       default:
1117         O << '\\';
1118         O << char('0' + (C >> 6));
1119         O << char('0' + (C >> 3));
1120         O << char('0' + (C >> 0));
1121         break;
1122       }
1123     } else if (C == '\"') {
1124       O << "\\\"";
1125     } else if (C == '\'') {
1126       O << "\\\'";
1127     } else {
1128      O << C;
1129     }
1130   }
1131   O << "\\0\"";
1132 }
1133
1134 /// PrintLabelName - Print label name in form used by Dwarf writer.
1135 ///
1136 void DwarfWriter::PrintLabelName(const char *Tag, unsigned Number) const {
1137   O << Asm->PrivateGlobalPrefix
1138     << "debug_"
1139     << Tag
1140     << Number;
1141 }
1142
1143 /// EmitLabel - Emit location label for internal use by Dwarf.
1144 ///
1145 void DwarfWriter::EmitLabel(const char *Tag, unsigned Number) const {
1146   PrintLabelName(Tag, Number);
1147   O << ":\n";
1148 }
1149
1150 /// EmitReference - Emit a reference to a label.
1151 ///
1152 void DwarfWriter::EmitReference(const char *Tag, unsigned Number) const {
1153   if (AddressSize == 4)
1154     O << Asm->Data32bitsDirective;
1155   else
1156     O << Asm->Data64bitsDirective;
1157     
1158   PrintLabelName(Tag, Number);
1159 }
1160 void DwarfWriter::EmitReference(const std::string &Name) const {
1161   if (AddressSize == 4)
1162     O << Asm->Data32bitsDirective;
1163   else
1164     O << Asm->Data64bitsDirective;
1165     
1166   O << Name;
1167 }
1168
1169 /// EmitDifference - Emit an label difference as sizeof(pointer) value.  Some
1170 /// assemblers do not accept absolute expressions with data directives, so there 
1171 /// is an option (needsSet) to use an intermediary 'set' expression.
1172 void DwarfWriter::EmitDifference(const char *TagHi, unsigned NumberHi,
1173                                  const char *TagLo, unsigned NumberLo) const {
1174   if (needsSet) {
1175     static unsigned SetCounter = 0;
1176     
1177     O << "\t.set\t";
1178     PrintLabelName("set", SetCounter);
1179     O << ",";
1180     PrintLabelName(TagHi, NumberHi);
1181     O << "-";
1182     PrintLabelName(TagLo, NumberLo);
1183     O << "\n";
1184     
1185     if (AddressSize == sizeof(int32_t))
1186       O << Asm->Data32bitsDirective;
1187     else
1188       O << Asm->Data64bitsDirective;
1189       
1190     PrintLabelName("set", SetCounter);
1191     
1192     ++SetCounter;
1193   } else {
1194     if (AddressSize == sizeof(int32_t))
1195       O << Asm->Data32bitsDirective;
1196     else
1197       O << Asm->Data64bitsDirective;
1198       
1199     PrintLabelName(TagHi, NumberHi);
1200     O << "-";
1201     PrintLabelName(TagLo, NumberLo);
1202   }
1203 }
1204
1205 /// NewAbbreviation - Add the abbreviation to the Abbreviation vector.
1206 ///  
1207 unsigned DwarfWriter::NewAbbreviation(DIEAbbrev *Abbrev) {
1208   return Abbreviations.insert(*Abbrev);
1209 }
1210
1211 /// NewString - Add a string to the constant pool and returns a label.
1212 ///
1213 DWLabel DwarfWriter::NewString(const std::string &String) {
1214   unsigned StringID = StringPool.insert(String);
1215   return DWLabel("string", StringID);
1216 }
1217
1218 /// NewGlobalType - Make the type visible globally using the given name.
1219 ///
1220 void DwarfWriter::NewGlobalType(const std::string &Name, DIE *Type) {
1221   assert(!GlobalTypes[Name] && "Duplicate global type");
1222   GlobalTypes[Name] = Type;
1223 }
1224
1225 /// NewGlobalEntity - Make the entity visible globally using the given name.
1226 ///
1227 void DwarfWriter::NewGlobalEntity(const std::string &Name, DIE *Entity) {
1228   assert(!GlobalEntities[Name] && "Duplicate global variable or function");
1229   GlobalEntities[Name] = Entity;
1230 }
1231
1232 /// NewGlobalVariable - Add a new global variable DIE to the context.
1233 ///
1234 void DwarfWriter::NewGlobalVariable(DWContext *Context,
1235                                     const std::string &Name,
1236                                     const std::string &MangledName,
1237                                     const Type *Ty,
1238                                     unsigned Size, unsigned Align) {
1239   // Get the DIE type for the global.
1240   DIE *Type = Context->NewBasicType(Ty, Size, Align);
1241   DIE *Variable = Context->NewGlobalVariable(Name, MangledName, Type);
1242   NewGlobalEntity(Name, Variable);
1243 }
1244
1245 /// NewCompileUnit - Create new compile unit information.
1246 ///
1247 DIE *DwarfWriter::NewCompileUnit(const std::string &Directory,
1248                                  const std::string &SourceName) {
1249   DIE *Unit = new DIE(DW_TAG_compile_unit, DW_CHILDREN_yes);
1250   // FIXME - use the correct line set.
1251   Unit->AddLabel (DW_AT_stmt_list, DW_FORM_data4,  DWLabel("line", 0));
1252   Unit->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
1253   Unit->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
1254   // FIXME - The producer needs to be in this form, but should come from
1255   // an appropriate source.
1256   Unit->AddString(DW_AT_producer,  DW_FORM_string,
1257                   "llvm 3.4.x (LLVM Research Group)");
1258   Unit->AddInt   (DW_AT_language,  DW_FORM_data1,  DW_LANG_C89);
1259   Unit->AddString(DW_AT_name,      DW_FORM_string, SourceName);
1260   Unit->AddString(DW_AT_comp_dir,  DW_FORM_string, Directory);
1261   Unit->Complete(*this);
1262   
1263   return Unit;
1264 }
1265
1266 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1267 /// tools to recognize the object file contains Dwarf information.
1268 ///
1269 void DwarfWriter::EmitInitial() const {
1270   // Dwarf sections base addresses.
1271   Asm->SwitchSection(DwarfAbbrevSection, 0);
1272   EmitLabel("abbrev", 0);
1273   Asm->SwitchSection(DwarfInfoSection, 0);
1274   EmitLabel("info", 0);
1275   Asm->SwitchSection(DwarfLineSection, 0);
1276   EmitLabel("line", 0);
1277   
1278   // Standard sections base addresses.
1279   Asm->SwitchSection(TextSection, 0);
1280   EmitLabel("text_begin", 0);
1281   Asm->SwitchSection(DataSection, 0);
1282   EmitLabel("data_begin", 0);
1283 }
1284
1285 /// EmitDIE - Recusively Emits a debug information entry.
1286 ///
1287 void DwarfWriter::EmitDIE(DIE *Die) const {
1288   // Get the abbreviation for this DIE.
1289   unsigned AbbrevID = Die->getAbbrevID();
1290   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1291
1292   // Emit the code (index) for the abbreviation.
1293   EmitULEB128Bytes(AbbrevID);
1294   EOL(std::string("Abbrev [" +
1295       utostr(AbbrevID) +
1296       "] " +
1297       TagString(Abbrev.getTag())) +
1298       " ");
1299   
1300   const std::vector<DIEValue *> &Values = Die->getValues();
1301   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1302   
1303   // Emit the DIE attribute values.
1304   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1305     unsigned Attr = AbbrevData[i].getAttribute();
1306     unsigned Form = AbbrevData[i].getForm();
1307     assert(Form && "Too many attributes for DIE (check abbreviation)");
1308     
1309     switch (Attr) {
1310     case DW_AT_sibling: {
1311       EmitLong(Die->SiblingOffset());
1312       break;
1313     }
1314     default: {
1315       // Emit an attribute using the defined form.
1316       Values[i]->EmitValue(*this, Form);
1317       break;
1318     }
1319     }
1320     
1321     EOL(AttributeString(Attr));
1322   }
1323   
1324   // Emit the DIE children if any.
1325   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
1326     const std::vector<DIE *> &Children = Die->getChildren();
1327     
1328     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1329       // FIXME - handle sibling offsets.
1330       // FIXME - handle all DIE types.
1331       EmitDIE(Children[j]);
1332     }
1333     
1334     EmitByte(0); EOL("End Of Children Mark");
1335   }
1336 }
1337
1338 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1339 ///
1340 unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset) const {
1341   // Get the abbreviation for this DIE.
1342   unsigned AbbrevID = Die->getAbbrevID();
1343   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1344
1345   // Set DIE offset
1346   Die->setOffset(Offset);
1347   
1348   // Start the size with the size of abbreviation code.
1349   Offset += SizeULEB128(AbbrevID);
1350   
1351   const std::vector<DIEValue *> &Values = Die->getValues();
1352   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1353
1354   // Emit the DIE attribute values.
1355   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1356     // Size attribute value.
1357     Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
1358   }
1359   
1360   // Emit the DIE children if any.
1361   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
1362     const std::vector<DIE *> &Children = Die->getChildren();
1363     
1364     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1365       // FIXME - handle sibling offsets.
1366       // FIXME - handle all DIE types.
1367       Offset = SizeAndOffsetDie(Children[j], Offset);
1368     }
1369     
1370     // End of children marker.
1371     Offset += sizeof(int8_t);
1372   }
1373
1374   Die->setSize(Offset - Die->getOffset());
1375   return Offset;
1376 }
1377
1378 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1379 ///
1380 void DwarfWriter::SizeAndOffsets() {
1381   // Compute size of debug unit header
1382   unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
1383                     sizeof(int16_t) + // DWARF version number
1384                     sizeof(int32_t) + // Offset Into Abbrev. Section
1385                     sizeof(int8_t);   // Pointer Size (in bytes)
1386   
1387   // Process each compile unit.
1388   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1389     Offset = SizeAndOffsetDie(CompileUnits[i], Offset);
1390   }
1391 }
1392
1393 /// EmitDebugInfo - Emit the debug info section.
1394 ///
1395 void DwarfWriter::EmitDebugInfo() const {
1396   // Start debug info section.
1397   Asm->SwitchSection(DwarfInfoSection, 0);
1398   
1399   // Get the number of compile units.
1400   unsigned N = CompileUnits.size();
1401   
1402   // If there are any compile units.
1403   if (N) {
1404     EmitLabel("info_begin", 0);
1405     
1406     // Emit the compile units header.
1407
1408     // Emit size of content not including length itself
1409     unsigned ContentSize = CompileUnits[N - 1]->SiblingOffset();
1410     EmitLong(ContentSize - sizeof(int32_t));
1411     EOL("Length of Compilation Unit Info");
1412     
1413     EmitShort(DWARF_VERSION); EOL("DWARF version number");
1414
1415     EmitReference("abbrev_begin", 0); EOL("Offset Into Abbrev. Section");
1416
1417     EmitByte(AddressSize); EOL("Address Size (in bytes)");
1418     
1419     // Process each compile unit.
1420     for (unsigned i = 0; i < N; ++i) {
1421       EmitDIE(CompileUnits[i]);
1422     }
1423     
1424     EmitLabel("info_end", 0);
1425   }
1426 }
1427
1428 /// EmitAbbreviations - Emit the abbreviation section.
1429 ///
1430 void DwarfWriter::EmitAbbreviations() const {
1431   // Check to see if it is worth the effort.
1432   if (!Abbreviations.empty()) {
1433     // Start the debug abbrev section.
1434     Asm->SwitchSection(DwarfAbbrevSection, 0);
1435     
1436     EmitLabel("abbrev_begin", 0);
1437     
1438     // For each abbrevation.
1439     for (unsigned AbbrevID = 1, NAID = Abbreviations.size();
1440                   AbbrevID <= NAID; ++AbbrevID) {
1441       // Get abbreviation data
1442       const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1443       
1444       // Emit the abbrevations code (base 1 index.)
1445       EmitULEB128Bytes(AbbrevID); EOL("Abbreviation Code");
1446       
1447       // Emit the abbreviations data.
1448       Abbrev.Emit(*this);
1449     }
1450     
1451     EmitLabel("abbrev_end", 0);
1452   }
1453 }
1454
1455 /// EmitDebugLines - Emit source line information.
1456 ///
1457 void DwarfWriter::EmitDebugLines() const {
1458   // Minimum line delta, thus ranging from -10..(255-10).
1459   const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
1460   // Maximum line delta, thus ranging from -10..(255-10).
1461   const int MaxLineDelta = 255 + MinLineDelta;
1462
1463   // Start the dwarf line section.
1464   Asm->SwitchSection(DwarfLineSection, 0);
1465   
1466   // Construct the section header.
1467   
1468   EmitDifference("line_end", 0, "line_begin", 0);
1469   EOL("Length of Source Line Info");
1470   EmitLabel("line_begin", 0);
1471   
1472   EmitShort(DWARF_VERSION); EOL("DWARF version number");
1473   
1474   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0);
1475   EOL("Prolog Length");
1476   EmitLabel("line_prolog_begin", 0);
1477   
1478   EmitByte(1); EOL("Minimum Instruction Length");
1479
1480   EmitByte(1); EOL("Default is_stmt_start flag");
1481
1482   EmitByte(MinLineDelta);  EOL("Line Base Value (Special Opcodes)");
1483   
1484   EmitByte(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
1485
1486   EmitByte(-MinLineDelta); EOL("Special Opcode Base");
1487   
1488   // Line number standard opcode encodings argument count
1489   EmitByte(0); EOL("DW_LNS_copy arg count");
1490   EmitByte(1); EOL("DW_LNS_advance_pc arg count");
1491   EmitByte(1); EOL("DW_LNS_advance_line arg count");
1492   EmitByte(1); EOL("DW_LNS_set_file arg count");
1493   EmitByte(1); EOL("DW_LNS_set_column arg count");
1494   EmitByte(0); EOL("DW_LNS_negate_stmt arg count");
1495   EmitByte(0); EOL("DW_LNS_set_basic_block arg count");
1496   EmitByte(0); EOL("DW_LNS_const_add_pc arg count");
1497   EmitByte(1); EOL("DW_LNS_fixed_advance_pc arg count");
1498
1499   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
1500   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
1501
1502   // Emit directories.
1503   for (unsigned DirectoryID = 1, NDID = Directories.size();
1504                 DirectoryID <= NDID; ++DirectoryID) {
1505     EmitString(Directories[DirectoryID]); EOL("Directory");
1506   }
1507   EmitByte(0); EOL("End of directories");
1508   
1509   // Emit files.
1510   for (unsigned SourceID = 1, NSID = SourceFiles.size();
1511                SourceID <= NSID; ++SourceID) {
1512     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
1513     EmitString(SourceFile.getName()); EOL("Source");
1514     EmitULEB128Bytes(SourceFile.getDirectoryID());  EOL("Directory #");
1515     EmitULEB128Bytes(0);  EOL("Mod date");
1516     EmitULEB128Bytes(0);  EOL("File size");
1517   }
1518   EmitByte(0); EOL("End of files");
1519   
1520   EmitLabel("line_prolog_end", 0);
1521   
1522   // Emit line information
1523   const std::vector<SourceLineInfo *> &LineInfos = DebugInfo->getSourceLines();
1524   
1525   // Dwarf assumes we start with first line of first source file.
1526   unsigned Source = 1;
1527   unsigned Line = 1;
1528   
1529   // Construct rows of the address, source, line, column matrix.
1530   for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1531     SourceLineInfo *LineInfo = LineInfos[i];
1532
1533     // Define the line address.
1534     EmitByte(0); EOL("Extended Op");
1535     EmitByte(4 + 1); EOL("Op size");
1536     EmitByte(DW_LNE_set_address); EOL("DW_LNE_set_address");
1537     EmitReference("loc", i + 1); EOL("Location label");
1538     
1539     // If change of source, then switch to the new source.
1540     if (Source != LineInfo->getSourceID()) {
1541       Source = LineInfo->getSourceID();
1542       EmitByte(DW_LNS_set_file); EOL("DW_LNS_set_file");
1543       EmitULEB128Bytes(0); EOL("New Source");
1544     }
1545     
1546     // If change of line.
1547     if (Line != LineInfo->getLine()) {
1548       // Determine offset.
1549       int Offset = LineInfo->getLine() - Line;
1550       int Delta = Offset - MinLineDelta;
1551       
1552       // Update line.
1553       Line = LineInfo->getLine();
1554       
1555       // If delta is small enough and in range...
1556       if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1557         // ... then use fast opcode.
1558         EmitByte(Delta - MinLineDelta); EOL("Line Delta");
1559       } else {
1560         // ... otherwise use long hand.
1561         EmitByte(DW_LNS_advance_line); EOL("DW_LNS_advance_line");
1562         EmitSLEB128Bytes(Offset); EOL("Line Offset");
1563         EmitByte(DW_LNS_copy); EOL("DW_LNS_copy");
1564       }
1565     } else {
1566       // Copy the previous row (different address or source)
1567       EmitByte(DW_LNS_copy); EOL("DW_LNS_copy");
1568     }
1569   }
1570
1571   // Mark end of matrix.
1572   EmitByte(0); EOL("DW_LNE_end_sequence");
1573   EmitULEB128Bytes(1);  O << "\n";
1574   EmitByte(1); O << "\n";
1575   
1576   EmitLabel("line_end", 0);
1577 }
1578   
1579 /// EmitDebugFrame - Emit visible names into a debug frame section.
1580 ///
1581 void DwarfWriter::EmitDebugFrame() {
1582   // FIXME - Should be per frame
1583 }
1584
1585 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1586 ///
1587 void DwarfWriter::EmitDebugPubNames() {
1588   // Check to see if it is worth the effort.
1589   if (!GlobalEntities.empty()) {
1590     // Start the dwarf pubnames section.
1591     Asm->SwitchSection(DwarfPubNamesSection, 0);
1592     
1593     EmitDifference("pubnames_end", 0, "pubnames_begin", 0);
1594     EOL("Length of Public Names Info");
1595     
1596     EmitLabel("pubnames_begin", 0);
1597     
1598     EmitShort(DWARF_VERSION); EOL("DWARF Version");
1599     
1600     EmitReference("info_begin", 0); EOL("Offset of Compilation Unit Info");
1601
1602     EmitDifference("info_end", 0, "info_begin", 0);
1603     EOL("Compilation Unit Length");
1604     
1605     for (std::map<std::string, DIE *>::iterator GI = GlobalEntities.begin(),
1606                                                 GE = GlobalEntities.end();
1607          GI != GE; ++GI) {
1608       const std::string &Name = GI->first;
1609       DIE * Entity = GI->second;
1610       
1611       EmitLong(Entity->getOffset()); EOL("DIE offset");
1612       EmitString(Name); EOL("External Name");
1613       
1614     }
1615   
1616     EmitLong(0); EOL("End Mark");
1617     EmitLabel("pubnames_end", 0);
1618   }
1619 }
1620
1621 /// EmitDebugPubTypes - Emit visible names into a debug pubtypes section.
1622 ///
1623 void DwarfWriter::EmitDebugPubTypes() {
1624   // Check to see if it is worth the effort.
1625   if (!GlobalTypes.empty()) {
1626     // Start the dwarf pubtypes section.
1627     Asm->SwitchSection(DwarfPubTypesSection, 0);
1628   }
1629 }
1630
1631 /// EmitDebugStr - Emit visible names into a debug str section.
1632 ///
1633 void DwarfWriter::EmitDebugStr() {
1634   // Check to see if it is worth the effort.
1635   if (!StringPool.empty()) {
1636     // Start the dwarf str section.
1637     Asm->SwitchSection(DwarfStrSection, 0);
1638     
1639     // For each of strings in teh string pool.
1640     for (unsigned StringID = 1, N = StringPool.size();
1641          StringID <= N; ++StringID) {
1642       // Emit a label for reference from debug information entries.
1643       EmitLabel("string", StringID);
1644       // Emit the string itself.
1645       const std::string &String = StringPool[StringID];
1646       EmitString(String); O << "\n";
1647     }
1648   }
1649 }
1650
1651 /// EmitDebugLoc - Emit visible names into a debug loc section.
1652 ///
1653 void DwarfWriter::EmitDebugLoc() {
1654   // Start the dwarf loc section.
1655   Asm->SwitchSection(DwarfLocSection, 0);
1656 }
1657
1658 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1659 ///
1660 void DwarfWriter::EmitDebugARanges() {
1661   // Start the dwarf aranges section.
1662   Asm->SwitchSection(DwarfARangesSection, 0);
1663   
1664   // FIXME - Mock up
1665
1666   // Don't include size of length
1667   EmitLong(0x1c); EOL("Length of Address Ranges Info");
1668   
1669   EmitShort(DWARF_VERSION); EOL("Dwarf Version");
1670   
1671   EmitReference("info_begin", 0); EOL("Offset of Compilation Unit Info");
1672
1673   EmitByte(AddressSize); EOL("Size of Address");
1674
1675   EmitByte(0); EOL("Size of Segment Descriptor");
1676
1677   EmitShort(0);  EOL("Pad (1)");
1678   EmitShort(0);  EOL("Pad (2)");
1679
1680   // Range 1
1681   EmitReference("text_begin", 0); EOL("Address");
1682   EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
1683
1684   EmitLong(0); EOL("EOM (1)");
1685   EmitLong(0); EOL("EOM (2)");
1686 }
1687
1688 /// EmitDebugRanges - Emit visible names into a debug ranges section.
1689 ///
1690 void DwarfWriter::EmitDebugRanges() {
1691   // Start the dwarf ranges section.
1692   Asm->SwitchSection(DwarfRangesSection, 0);
1693 }
1694
1695 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
1696 ///
1697 void DwarfWriter::EmitDebugMacInfo() {
1698   // Start the dwarf macinfo section.
1699   Asm->SwitchSection(DwarfMacInfoSection, 0);
1700 }
1701
1702 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
1703 /// header file.
1704 void DwarfWriter::ConstructCompileUnitDIEs() {
1705   // Get directory and source information.
1706   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
1707   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
1708
1709   // Construct compile unit DIEs for each source.
1710   for (unsigned SourceID = 1, NSID = SourceFiles.size();
1711                 SourceID <=  NSID; ++SourceID) {
1712     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
1713     const std::string &Directory = Directories[SourceFile.getDirectoryID()];
1714     const std::string &SourceName = SourceFile.getName();
1715     DIE *Unit = NewCompileUnit(Directory, SourceName);
1716     DWContext *Context = new DWContext(*this, NULL, Unit);
1717     CompileUnits.push_back(Unit);
1718   }
1719 }
1720
1721 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
1722 /// variables.
1723 void DwarfWriter::ConstructGlobalDIEs(Module &M) {
1724   const TargetData &TD = Asm->TM.getTargetData();
1725
1726   // Iterate throu each of the globals.
1727   for (Module::const_global_iterator GI = M.global_begin(), GE = M.global_end();
1728        GI != GE; ++GI) {
1729     if (!GI->hasInitializer()) continue;   // External global require no code
1730     
1731     // Check to see if this is a special global used by LLVM, if so, emit it.
1732     if (GI->hasAppendingLinkage() && (GI->getName() == "llvm.global_ctors" ||
1733                                       GI->getName() == "llvm.global_dtors"))
1734       continue;
1735     
1736     std::string Name = Asm->Mang->getValueName(GI);
1737     Constant *C = GI->getInitializer();
1738     const Type *Ty = C->getType();
1739     unsigned Size = TD.getTypeSize(Ty);
1740     unsigned Align = TD.getTypeAlignmentShift(Ty);
1741
1742     if (C->isNullValue() && /* FIXME: Verify correct */
1743         (GI->hasInternalLinkage() || GI->hasWeakLinkage() ||
1744          GI->hasLinkOnceLinkage())) {
1745       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1746       
1747     }
1748
1749     /// FIXME - Get correct compile unit context.
1750     assert(CompileUnits.size() && "No compile units");
1751     DWContext *Context = CompileUnits[0]->getContext();
1752     
1753     /// Create new global.
1754     NewGlobalVariable(Context, GI->getName(), Name, Ty, Size, Align);
1755   }
1756 }
1757
1758
1759 /// ShouldEmitDwarf - Determine if Dwarf declarations should be made.
1760 ///
1761 bool DwarfWriter::ShouldEmitDwarf() {
1762   // Check if debug info is present.
1763   if (!DebugInfo || !DebugInfo->hasInfo()) return false;
1764   
1765   // Make sure initial declarations are made.
1766   if (!didInitial) {
1767     EmitInitial();
1768     didInitial = true;
1769   }
1770   
1771   // Okay to emit.
1772   return true;
1773 }
1774
1775 //===----------------------------------------------------------------------===//
1776 // Main entry points.
1777 //
1778   
1779 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A)
1780 : O(OS)
1781 , Asm(A)
1782 , DebugInfo(NULL)
1783 , didInitial(false)
1784 , CompileUnits()
1785 , Abbreviations()
1786 , GlobalTypes()
1787 , GlobalEntities()
1788 , StringPool()
1789 , AddressSize(sizeof(int32_t))
1790 , hasLEB128(false)
1791 , hasDotLoc(false)
1792 , hasDotFile(false)
1793 , needsSet(false)
1794 , DwarfAbbrevSection(".debug_abbrev")
1795 , DwarfInfoSection(".debug_info")
1796 , DwarfLineSection(".debug_line")
1797 , DwarfFrameSection(".debug_frame")
1798 , DwarfPubNamesSection(".debug_pubnames")
1799 , DwarfPubTypesSection(".debug_pubtypes")
1800 , DwarfStrSection(".debug_str")
1801 , DwarfLocSection(".debug_loc")
1802 , DwarfARangesSection(".debug_aranges")
1803 , DwarfRangesSection(".debug_ranges")
1804 , DwarfMacInfoSection(".debug_macinfo")
1805 , TextSection(".text")
1806 , DataSection(".data")
1807 {}
1808 DwarfWriter::~DwarfWriter() {
1809   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1810     delete CompileUnits[i];
1811   }
1812 }
1813
1814 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
1815 ///
1816 void DwarfWriter::BeginModule(Module &M) {
1817   if (!ShouldEmitDwarf()) return;
1818   EOL("Dwarf Begin Module");
1819 }
1820
1821 /// EndModule - Emit all Dwarf sections that should come after the content.
1822 ///
1823 void DwarfWriter::EndModule(Module &M) {
1824   if (!ShouldEmitDwarf()) return;
1825   EOL("Dwarf End Module");
1826   
1827   // Standard sections final addresses.
1828   Asm->SwitchSection(TextSection, 0);
1829   EmitLabel("text_end", 0);
1830   Asm->SwitchSection(DataSection, 0);
1831   EmitLabel("data_end", 0);
1832   
1833   // Create all the compile unit DIEs.
1834   ConstructCompileUnitDIEs();
1835   
1836   // Create DIEs for each of the externally visible global variables.
1837   ConstructGlobalDIEs(M);
1838
1839   // Compute DIE offsets and sizes.
1840   SizeAndOffsets();
1841   
1842   // Emit all the DIEs into a debug info section
1843   EmitDebugInfo();
1844   
1845   // Corresponding abbreviations into a abbrev section.
1846   EmitAbbreviations();
1847   
1848   // Emit source line correspondence into a debug line section.
1849   EmitDebugLines();
1850   
1851   // Emit info into a debug frame section.
1852   EmitDebugFrame();
1853   
1854   // Emit info into a debug pubnames section.
1855   EmitDebugPubNames();
1856   
1857   // Emit info into a debug pubtypes section.
1858   EmitDebugPubTypes();
1859   
1860   // Emit info into a debug str section.
1861   EmitDebugStr();
1862   
1863   // Emit info into a debug loc section.
1864   EmitDebugLoc();
1865   
1866   // Emit info into a debug aranges section.
1867   EmitDebugARanges();
1868   
1869   // Emit info into a debug ranges section.
1870   EmitDebugRanges();
1871   
1872   // Emit info into a debug macinfo section.
1873   EmitDebugMacInfo();
1874 }
1875
1876 /// BeginFunction - Gather pre-function debug information.
1877 ///
1878 void DwarfWriter::BeginFunction(MachineFunction &MF) {
1879   if (!ShouldEmitDwarf()) return;
1880   EOL("Dwarf Begin Function");
1881 }
1882
1883 /// EndFunction - Gather and emit post-function debug information.
1884 ///
1885 void DwarfWriter::EndFunction(MachineFunction &MF) {
1886   if (!ShouldEmitDwarf()) return;
1887   EOL("Dwarf End Function");
1888 }