7 use cranelift_codegen::entity::EntityRef;
8 use cranelift_codegen::ir::{StackSlots, ValueLabel, ValueLoc};
9 use cranelift_codegen::isa::TargetIsa;
10 use cranelift_codegen::ValueLocRange;
13 Address, AttributeValue, DwarfUnit, Expression, LineProgram,
14 LineString, Location, LocationList, Range, RangeList, UnitEntryId,
16 use gimli::{Encoding, Format, LineEncoding, RunTimeEndian, X86_64};
18 pub(crate) use emit::{DebugReloc, DebugRelocName};
19 pub(crate) use unwind::UnwindContext;
21 fn target_endian(tcx: TyCtxt<'_>) -> RunTimeEndian {
22 use rustc_target::abi::Endian;
24 match tcx.data_layout.endian {
25 Endian::Big => RunTimeEndian::Big,
26 Endian::Little => RunTimeEndian::Little,
30 pub(crate) struct DebugContext<'tcx> {
33 endian: RunTimeEndian,
36 unit_range_list: RangeList,
38 clif_types: FxHashMap<Type, UnitEntryId>,
39 types: FxHashMap<Ty<'tcx>, UnitEntryId>,
42 impl<'tcx> DebugContext<'tcx> {
43 pub(crate) fn new(tcx: TyCtxt<'tcx>, isa: &dyn TargetIsa) -> Self {
44 let encoding = Encoding {
45 format: Format::Dwarf32,
46 // TODO: this should be configurable
47 // macOS doesn't seem to support DWARF > 3
48 // 5 version is required for md5 file hash
49 version: if tcx.sess.target.target.options.is_like_osx {
52 // FIXME change to version 5 once the gdb and lldb shipping with the latest debian
56 address_size: isa.frontend_config().pointer_bytes(),
59 let mut dwarf = DwarfUnit::new(encoding);
61 // FIXME: how to get version when building out of tree?
62 // Normally this would use option_env!("CFG_VERSION").
63 let producer = format!("cg_clif (rustc {})", "unknown version");
64 let comp_dir = tcx.sess.working_dir.0.to_string_lossy().into_owned();
65 let (name, file_info) = match tcx.sess.local_crate_source_file.clone() {
67 let name = path.to_string_lossy().into_owned();
70 None => (tcx.crate_name(LOCAL_CRATE).to_string(), None),
73 let mut line_program = LineProgram::new(
75 LineEncoding::default(),
76 LineString::new(comp_dir.as_bytes(), encoding, &mut dwarf.line_strings),
77 LineString::new(name.as_bytes(), encoding, &mut dwarf.line_strings),
80 line_program.file_has_md5 = file_info.is_some();
82 dwarf.unit.line_program = line_program;
85 let name = dwarf.strings.add(name);
86 let comp_dir = dwarf.strings.add(comp_dir);
88 let root = dwarf.unit.root();
89 let root = dwarf.unit.get_mut(root);
91 gimli::DW_AT_producer,
92 AttributeValue::StringRef(dwarf.strings.add(producer)),
95 gimli::DW_AT_language,
96 AttributeValue::Language(gimli::DW_LANG_Rust),
98 root.set(gimli::DW_AT_name, AttributeValue::StringRef(name));
99 root.set(gimli::DW_AT_comp_dir, AttributeValue::StringRef(comp_dir));
102 AttributeValue::Address(Address::Constant(0)),
109 endian: target_endian(tcx),
112 unit_range_list: RangeList(Vec::new()),
114 clif_types: FxHashMap::default(),
115 types: FxHashMap::default(),
119 fn dwarf_ty_for_clif_ty(&mut self, ty: Type) -> UnitEntryId {
120 if let Some(type_id) = self.clif_types.get(&ty) {
124 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
126 let primitive = |dwarf: &mut DwarfUnit, ate| {
127 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
128 let type_entry = dwarf.unit.get_mut(type_id);
129 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
133 let type_id = if ty.is_bool() {
134 primitive(&mut self.dwarf, gimli::DW_ATE_boolean)
135 } else if ty.is_int() {
136 primitive(&mut self.dwarf, gimli::DW_ATE_address)
137 } else if ty.is_float() {
138 primitive(&mut self.dwarf, gimli::DW_ATE_float)
140 new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type)
143 let type_entry = self.dwarf.unit.get_mut(type_id);
144 type_entry.set(gimli::DW_AT_name, AttributeValue::String(format!("{}", ty).replace('i', "u").into_bytes()));
146 gimli::DW_AT_byte_size,
147 AttributeValue::Udata(u64::from(ty.bytes())),
153 fn dwarf_ty(&mut self, ty: Ty<'tcx>) -> UnitEntryId {
154 if let Some(type_id) = self.types.get(ty) {
158 let new_entry = |dwarf: &mut DwarfUnit, tag| dwarf.unit.add(dwarf.unit.root(), tag);
160 let primitive = |dwarf: &mut DwarfUnit, ate| {
161 let type_id = new_entry(dwarf, gimli::DW_TAG_base_type);
162 let type_entry = dwarf.unit.get_mut(type_id);
163 type_entry.set(gimli::DW_AT_encoding, AttributeValue::Encoding(ate));
167 let name = format!("{}", ty);
168 let layout = self.tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap();
170 let type_id = match ty.kind {
171 ty::Bool => primitive(&mut self.dwarf, gimli::DW_ATE_boolean),
172 ty::Char => primitive(&mut self.dwarf, gimli::DW_ATE_UTF),
173 ty::Uint(_) => primitive(&mut self.dwarf, gimli::DW_ATE_unsigned),
174 ty::Int(_) => primitive(&mut self.dwarf, gimli::DW_ATE_signed),
175 ty::Float(_) => primitive(&mut self.dwarf, gimli::DW_ATE_float),
176 ty::Ref(_, pointee_ty, _mutbl)
177 | ty::RawPtr(ty::TypeAndMut {
181 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_pointer_type);
183 // Ensure that type is inserted before recursing to avoid duplicates
184 self.types.insert(ty, type_id);
186 let pointee = self.dwarf_ty(pointee_ty);
188 let type_entry = self.dwarf.unit.get_mut(type_id);
190 //type_entry.set(gimli::DW_AT_mutable, AttributeValue::Flag(mutbl == rustc_hir::Mutability::Mut));
191 type_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(pointee));
195 ty::Adt(adt_def, _substs) if adt_def.is_struct() && !layout.is_unsized() => {
196 let type_id = new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type);
198 // Ensure that type is inserted before recursing to avoid duplicates
199 self.types.insert(ty, type_id);
201 let variant = adt_def.non_enum_variant();
203 for (field_idx, field_def) in variant.fields.iter().enumerate() {
204 let field_offset = layout.fields.offset(field_idx);
205 let field_layout = layout.field(&layout::LayoutCx {
207 param_env: ParamEnv::reveal_all(),
208 }, field_idx).unwrap();
210 let field_type = self.dwarf_ty(field_layout.ty);
212 let field_id = self.dwarf.unit.add(type_id, gimli::DW_TAG_member);
213 let field_entry = self.dwarf.unit.get_mut(field_id);
215 field_entry.set(gimli::DW_AT_name, AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()));
216 field_entry.set(gimli::DW_AT_data_member_location, AttributeValue::Udata(field_offset.bytes()));
217 field_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(field_type));
222 _ => new_entry(&mut self.dwarf, gimli::DW_TAG_structure_type),
225 let type_entry = self.dwarf.unit.get_mut(type_id);
227 type_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
229 gimli::DW_AT_byte_size,
230 AttributeValue::Udata(layout.size.bytes()),
233 self.types.insert(ty, type_id);
238 fn define_local(&mut self, scope: UnitEntryId, name: String, ty: Ty<'tcx>) -> UnitEntryId {
239 let dw_ty = self.dwarf_ty(ty);
244 .add(scope, gimli::DW_TAG_variable);
245 let var_entry = self.dwarf.unit.get_mut(var_id);
247 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
248 var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
253 pub(crate) fn define_function(
255 instance: Instance<'tcx>,
260 source_info_set: &indexmap::IndexSet<SourceInfo>,
261 local_map: FxHashMap<mir::Local, CPlace<'tcx>>,
263 let symbol = func_id.as_u32() as usize;
264 let mir = self.tcx.instance_mir(instance.def);
266 // FIXME: add to appropriate scope instead of root
267 let scope = self.dwarf.unit.root();
272 .add(scope, gimli::DW_TAG_subprogram);
273 let entry = self.dwarf.unit.get_mut(entry_id);
274 let name_id = self.dwarf.strings.add(name);
275 // Gdb requires DW_AT_name. Otherwise the DW_TAG_subprogram is skipped.
278 AttributeValue::StringRef(name_id),
281 gimli::DW_AT_linkage_name,
282 AttributeValue::StringRef(name_id),
285 let end = self.create_debug_lines(isa, symbol, entry_id, context, mir.span, source_info_set);
290 .push(Range::StartLength {
291 begin: Address::Symbol {
295 length: u64::from(end),
298 if isa.get_mach_backend().is_some() {
299 return; // Not yet implemented for the AArch64 backend.
302 let func_entry = self.dwarf.unit.get_mut(entry_id);
303 // Gdb requires both DW_AT_low_pc and DW_AT_high_pc. Otherwise the DW_TAG_subprogram is skipped.
304 func_entry.set(gimli::DW_AT_low_pc, AttributeValue::Address(Address::Symbol {
308 // Using Udata for DW_AT_high_pc requires at least DWARF4
309 func_entry.set(gimli::DW_AT_high_pc, AttributeValue::Udata(u64::from(end)));
311 // FIXME Remove once actual debuginfo for locals works.
312 for (i, (param, &val)) in context.func.signature.params.iter().zip(context.func.dfg.block_params(context.func.layout.entry_block().unwrap())).enumerate() {
313 use cranelift_codegen::ir::ArgumentPurpose;
314 let base_name = match param.purpose {
315 ArgumentPurpose::Normal => "arg",
316 ArgumentPurpose::StructReturn => "sret",
317 ArgumentPurpose::Link | ArgumentPurpose::FramePointer | ArgumentPurpose::CalleeSaved => continue,
318 ArgumentPurpose::VMContext | ArgumentPurpose::SignatureId | ArgumentPurpose::StackLimit => unreachable!(),
320 let name = format!("{}{}", base_name, i);
322 let dw_ty = self.dwarf_ty_for_clif_ty(param.value_type);
323 let loc = translate_loc(isa, context.func.locations[val], &context.func.stack_slots).unwrap();
325 let arg_id = self.dwarf.unit.add(entry_id, gimli::DW_TAG_formal_parameter);
326 let var_entry = self.dwarf.unit.get_mut(arg_id);
328 var_entry.set(gimli::DW_AT_name, AttributeValue::String(name.into_bytes()));
329 var_entry.set(gimli::DW_AT_type, AttributeValue::UnitRef(dw_ty));
330 var_entry.set(gimli::DW_AT_location, AttributeValue::Exprloc(loc));
333 // FIXME make it more reliable and implement scopes before re-enabling this.
335 let value_labels_ranges = context.build_value_labels_ranges(isa).unwrap();
337 for (local, _local_decl) in mir.local_decls.iter_enumerated() {
338 let ty = self.tcx.subst_and_normalize_erasing_regions(
340 ty::ParamEnv::reveal_all(),
341 &mir.local_decls[local].ty,
343 let var_id = self.define_local(entry_id, format!("{:?}", local), ty);
345 let location = place_location(
351 &value_labels_ranges,
354 projection: ty::List::empty(),
358 let var_entry = self.dwarf.unit.get_mut(var_id);
359 var_entry.set(gimli::DW_AT_location, location);
363 // FIXME create locals for all entries in mir.var_debug_info
367 fn place_location<'tcx>(
368 debug_context: &mut DebugContext<'tcx>,
372 local_map: &FxHashMap<mir::Local, CPlace<'tcx>>,
373 #[allow(rustc::default_hash_types)]
374 value_labels_ranges: &std::collections::HashMap<ValueLabel, Vec<ValueLocRange>>,
376 ) -> AttributeValue {
377 assert!(place.projection.is_empty()); // FIXME implement them
379 match local_map[&place.local].inner() {
380 CPlaceInner::Var(_local, var) => {
381 let value_label = cranelift_codegen::ir::ValueLabel::new(var.index());
382 if let Some(value_loc_ranges) = value_labels_ranges.get(&value_label) {
383 let loc_list = LocationList(
386 .map(|value_loc_range| Location::StartEnd {
387 begin: Address::Symbol {
389 addend: i64::from(value_loc_range.start),
391 end: Address::Symbol {
393 addend: i64::from(value_loc_range.end),
395 data: translate_loc(isa, value_loc_range.loc, &context.func.stack_slots).unwrap(),
399 let loc_list_id = debug_context.dwarf.unit.locations.add(loc_list);
401 AttributeValue::LocationListRef(loc_list_id)
403 // FIXME set value labels for unused locals
405 AttributeValue::Exprloc(Expression::new())
408 CPlaceInner::VarPair(_, _, _) => {
409 // FIXME implement this
411 AttributeValue::Exprloc(Expression::new())
413 CPlaceInner::Addr(_, _) => {
414 // FIXME implement this (used by arguments and returns)
416 AttributeValue::Exprloc(Expression::new())
418 // For PointerBase::Stack:
419 //AttributeValue::Exprloc(translate_loc(ValueLoc::Stack(*stack_slot), &context.func.stack_slots).unwrap())
424 // Adapted from https://github.com/CraneStation/wasmtime/blob/5a1845b4caf7a5dba8eda1fef05213a532ed4259/crates/debug/src/transform/expression.rs#L59-L137
425 fn translate_loc(isa: &dyn TargetIsa, loc: ValueLoc, stack_slots: &StackSlots) -> Option<Expression> {
427 ValueLoc::Reg(reg) => {
428 let machine_reg = isa.map_dwarf_register(reg).unwrap();
429 let mut expr = Expression::new();
430 expr.op_reg(gimli::Register(machine_reg));
433 ValueLoc::Stack(ss) => {
434 if let Some(ss_offset) = stack_slots[ss].offset {
435 let mut expr = Expression::new();
436 expr.op_breg(X86_64::RBP, i64::from(ss_offset) + 16);