]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Remove `in_band_lifetimes` from `rustc_codegen_llvm`
[rust.git] / compiler / rustc_codegen_llvm / src / debuginfo / metadata.rs
1 use self::MemberDescriptionFactory::*;
2 use self::RecursiveTypeDescription::*;
3
4 use super::namespace::mangled_name_of_instance;
5 use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name};
6 use super::utils::{
7     create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB,
8 };
9 use super::CrateDebugContext;
10
11 use crate::abi;
12 use crate::common::CodegenCx;
13 use crate::llvm;
14 use crate::llvm::debuginfo::{
15     DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType,
16     DebugEmissionKind,
17 };
18 use crate::value::Value;
19
20 use cstr::cstr;
21 use rustc_codegen_ssa::traits::*;
22 use rustc_data_structures::fingerprint::Fingerprint;
23 use rustc_data_structures::fx::FxHashMap;
24 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
25 use rustc_fs_util::path_to_c_string;
26 use rustc_hir::def::CtorKind;
27 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
28 use rustc_index::vec::{Idx, IndexVec};
29 use rustc_middle::mir::{self, GeneratorLayout};
30 use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout};
31 use rustc_middle::ty::subst::GenericArgKind;
32 use rustc_middle::ty::{
33     self, AdtKind, GeneratorSubsts, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES,
34 };
35 use rustc_middle::{bug, span_bug};
36 use rustc_query_system::ich::NodeIdHashingMode;
37 use rustc_session::config::{self, DebugInfo};
38 use rustc_span::symbol::Symbol;
39 use rustc_span::FileNameDisplayPreference;
40 use rustc_span::{self, SourceFile, SourceFileHash, Span};
41 use rustc_target::abi::{Abi, Align, HasDataLayout, Integer, TagEncoding};
42 use rustc_target::abi::{Int, Pointer, F32, F64};
43 use rustc_target::abi::{Primitive, Size, VariantIdx, Variants};
44 use tracing::debug;
45
46 use libc::{c_longlong, c_uint};
47 use std::collections::hash_map::Entry;
48 use std::fmt::{self, Write};
49 use std::hash::{Hash, Hasher};
50 use std::iter;
51 use std::path::{Path, PathBuf};
52 use std::ptr;
53
54 impl PartialEq for llvm::Metadata {
55     fn eq(&self, other: &Self) -> bool {
56         ptr::eq(self, other)
57     }
58 }
59
60 impl Eq for llvm::Metadata {}
61
62 impl Hash for llvm::Metadata {
63     fn hash<H: Hasher>(&self, hasher: &mut H) {
64         (self as *const Self).hash(hasher);
65     }
66 }
67
68 impl fmt::Debug for llvm::Metadata {
69     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70         (self as *const Self).fmt(f)
71     }
72 }
73
74 // From DWARF 5.
75 // See http://www.dwarfstd.org/ShowIssue.php?issue=140129.1.
76 const DW_LANG_RUST: c_uint = 0x1c;
77 #[allow(non_upper_case_globals)]
78 const DW_ATE_boolean: c_uint = 0x02;
79 #[allow(non_upper_case_globals)]
80 const DW_ATE_float: c_uint = 0x04;
81 #[allow(non_upper_case_globals)]
82 const DW_ATE_signed: c_uint = 0x05;
83 #[allow(non_upper_case_globals)]
84 const DW_ATE_unsigned: c_uint = 0x07;
85 #[allow(non_upper_case_globals)]
86 const DW_ATE_unsigned_char: c_uint = 0x08;
87
88 pub const UNKNOWN_LINE_NUMBER: c_uint = 0;
89 pub const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
90
91 pub const NO_SCOPE_METADATA: Option<&DIScope> = None;
92
93 mod unique_type_id {
94     use super::*;
95     use rustc_arena::DroplessArena;
96
97     #[derive(Copy, Hash, Eq, PartialEq, Clone)]
98     pub(super) struct UniqueTypeId(u32);
99
100     // The `&'static str`s in this type actually point into the arena.
101     //
102     // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278
103     // found that to regress performance up to 2% in some cases. This might be
104     // revisited after further improvements to `indexmap`.
105     #[derive(Default)]
106     pub(super) struct TypeIdInterner {
107         arena: DroplessArena,
108         names: FxHashMap<&'static str, UniqueTypeId>,
109         strings: Vec<&'static str>,
110     }
111
112     impl TypeIdInterner {
113         #[inline]
114         pub(super) fn intern(&mut self, string: &str) -> UniqueTypeId {
115             if let Some(&name) = self.names.get(string) {
116                 return name;
117             }
118
119             let name = UniqueTypeId(self.strings.len() as u32);
120
121             // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be
122             // UTF-8.
123             let string: &str =
124                 unsafe { std::str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) };
125             // It is safe to extend the arena allocation to `'static` because we only access
126             // these while the arena is still alive.
127             let string: &'static str = unsafe { &*(string as *const str) };
128             self.strings.push(string);
129             self.names.insert(string, name);
130             name
131         }
132
133         // Get the symbol as a string. `Symbol::as_str()` should be used in
134         // preference to this function.
135         pub(super) fn get(&self, symbol: UniqueTypeId) -> &str {
136             self.strings[symbol.0 as usize]
137         }
138     }
139 }
140 use unique_type_id::*;
141
142 /// The `TypeMap` is where the `CrateDebugContext` holds the type metadata nodes
143 /// created so far. The metadata nodes are indexed by `UniqueTypeId`, and, for
144 /// faster lookup, also by `Ty`. The `TypeMap` is responsible for creating
145 /// `UniqueTypeId`s.
146 #[derive(Default)]
147 pub struct TypeMap<'ll, 'tcx> {
148     /// The `UniqueTypeId`s created so far.
149     unique_id_interner: TypeIdInterner,
150     /// A map from `UniqueTypeId` to debuginfo metadata for that type. This is a 1:1 mapping.
151     unique_id_to_metadata: FxHashMap<UniqueTypeId, &'ll DIType>,
152     /// A map from types to debuginfo metadata. This is an N:1 mapping.
153     type_to_metadata: FxHashMap<Ty<'tcx>, &'ll DIType>,
154     /// A map from types to `UniqueTypeId`. This is an N:1 mapping.
155     type_to_unique_id: FxHashMap<Ty<'tcx>, UniqueTypeId>,
156 }
157
158 impl<'ll, 'tcx> TypeMap<'ll, 'tcx> {
159     /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if
160     /// the mapping already exists.
161     fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) {
162         if self.type_to_metadata.insert(type_, metadata).is_some() {
163             bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_);
164         }
165     }
166
167     /// Removes a `Ty`-to-metadata mapping.
168     /// This is useful when computing the metadata for a potentially
169     /// recursive type (e.g., a function pointer of the form:
170     ///
171     ///     fn foo() -> impl Copy { foo }
172     ///
173     /// This kind of type cannot be properly represented
174     /// via LLVM debuginfo. As a workaround,
175     /// we register a temporary Ty to metadata mapping
176     /// for the function before we compute its actual metadata.
177     /// If the metadata computation ends up recursing back to the
178     /// original function, it will use the temporary mapping
179     /// for the inner self-reference, preventing us from
180     /// recursing forever.
181     ///
182     /// This function is used to remove the temporary metadata
183     /// mapping after we've computed the actual metadata.
184     fn remove_type(&mut self, type_: Ty<'tcx>) {
185         if self.type_to_metadata.remove(type_).is_none() {
186             bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_);
187         }
188     }
189
190     /// Adds a `UniqueTypeId` to metadata mapping to the `TypeMap`. The method will
191     /// fail if the mapping already exists.
192     fn register_unique_id_with_metadata(
193         &mut self,
194         unique_type_id: UniqueTypeId,
195         metadata: &'ll DIType,
196     ) {
197         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
198             bug!(
199                 "type metadata for unique ID '{}' is already in the `TypeMap`!",
200                 self.get_unique_type_id_as_string(unique_type_id)
201             );
202         }
203     }
204
205     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<&'ll DIType> {
206         self.type_to_metadata.get(&type_).cloned()
207     }
208
209     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<&'ll DIType> {
210         self.unique_id_to_metadata.get(&unique_type_id).cloned()
211     }
212
213     /// Gets the string representation of a `UniqueTypeId`. This method will fail if
214     /// the ID is unknown.
215     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> &str {
216         self.unique_id_interner.get(unique_type_id)
217     }
218
219     /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given
220     /// type has been requested before, this is just a table lookup. Otherwise, an
221     /// ID will be generated and stored for later lookup.
222     fn get_unique_type_id_of_type<'a>(
223         &mut self,
224         cx: &CodegenCx<'a, 'tcx>,
225         type_: Ty<'tcx>,
226     ) -> UniqueTypeId {
227         // Let's see if we already have something in the cache.
228         if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() {
229             return unique_type_id;
230         }
231         // If not, generate one.
232
233         // The hasher we are using to generate the UniqueTypeId. We want
234         // something that provides more than the 64 bits of the DefaultHasher.
235         let mut hasher = StableHasher::new();
236         let mut hcx = cx.tcx.create_stable_hashing_context();
237         let type_ = cx.tcx.erase_regions(type_);
238         hcx.while_hashing_spans(false, |hcx| {
239             hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
240                 type_.hash_stable(hcx, &mut hasher);
241             });
242         });
243         let unique_type_id = hasher.finish::<Fingerprint>().to_hex();
244
245         let key = self.unique_id_interner.intern(&unique_type_id);
246         self.type_to_unique_id.insert(type_, key);
247
248         key
249     }
250
251     /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really
252     /// types of their own, so they need special handling. We still need a
253     /// `UniqueTypeId` for them, since to debuginfo they *are* real types.
254     fn get_unique_type_id_of_enum_variant<'a>(
255         &mut self,
256         cx: &CodegenCx<'a, 'tcx>,
257         enum_type: Ty<'tcx>,
258         variant_name: &str,
259     ) -> UniqueTypeId {
260         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
261         let enum_variant_type_id =
262             format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name);
263         let interner_key = self.unique_id_interner.intern(&enum_variant_type_id);
264         interner_key
265     }
266
267     /// Gets the unique type ID string for an enum variant part.
268     /// Variant parts are not types and shouldn't really have their own ID,
269     /// but it makes `set_members_of_composite_type()` simpler.
270     fn get_unique_type_id_str_of_enum_variant_part(
271         &mut self,
272         enum_type_id: UniqueTypeId,
273     ) -> String {
274         format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id))
275     }
276 }
277
278 /// A description of some recursive type. It can either be already finished (as
279 /// with `FinalMetadata`) or it is not yet finished, but contains all information
280 /// needed to generate the missing parts of the description. See the
281 /// documentation section on Recursive Types at the top of this file for more
282 /// information.
283 enum RecursiveTypeDescription<'ll, 'tcx> {
284     UnfinishedMetadata {
285         unfinished_type: Ty<'tcx>,
286         unique_type_id: UniqueTypeId,
287         metadata_stub: &'ll DICompositeType,
288         member_holding_stub: &'ll DICompositeType,
289         member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
290     },
291     FinalMetadata(&'ll DICompositeType),
292 }
293
294 fn create_and_register_recursive_type_forward_declaration<'ll, 'tcx>(
295     cx: &CodegenCx<'ll, 'tcx>,
296     unfinished_type: Ty<'tcx>,
297     unique_type_id: UniqueTypeId,
298     metadata_stub: &'ll DICompositeType,
299     member_holding_stub: &'ll DICompositeType,
300     member_description_factory: MemberDescriptionFactory<'ll, 'tcx>,
301 ) -> RecursiveTypeDescription<'ll, 'tcx> {
302     // Insert the stub into the `TypeMap` in order to allow for recursive references.
303     let mut type_map = debug_context(cx).type_map.borrow_mut();
304     type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub);
305     type_map.register_type_with_metadata(unfinished_type, metadata_stub);
306
307     UnfinishedMetadata {
308         unfinished_type,
309         unique_type_id,
310         metadata_stub,
311         member_holding_stub,
312         member_description_factory,
313     }
314 }
315
316 impl<'ll, 'tcx> RecursiveTypeDescription<'ll, 'tcx> {
317     /// Finishes up the description of the type in question (mostly by providing
318     /// descriptions of the fields of the given type) and returns the final type
319     /// metadata.
320     fn finalize(&self, cx: &CodegenCx<'ll, 'tcx>) -> MetadataCreationResult<'ll> {
321         match *self {
322             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
323             UnfinishedMetadata {
324                 unfinished_type,
325                 unique_type_id,
326                 metadata_stub,
327                 member_holding_stub,
328                 ref member_description_factory,
329             } => {
330                 // Make sure that we have a forward declaration of the type in
331                 // the TypeMap so that recursive references are possible. This
332                 // will always be the case if the RecursiveTypeDescription has
333                 // been properly created through the
334                 // `create_and_register_recursive_type_forward_declaration()`
335                 // function.
336                 {
337                     let type_map = debug_context(cx).type_map.borrow();
338                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none()
339                         || type_map.find_metadata_for_type(unfinished_type).is_none()
340                     {
341                         bug!(
342                             "Forward declaration of potentially recursive type \
343                               '{:?}' was not found in TypeMap!",
344                             unfinished_type
345                         );
346                     }
347                 }
348
349                 // ... then create the member descriptions ...
350                 let member_descriptions = member_description_factory.create_member_descriptions(cx);
351
352                 // ... and attach them to the stub to complete it.
353                 set_members_of_composite_type(
354                     cx,
355                     unfinished_type,
356                     member_holding_stub,
357                     member_descriptions,
358                     None,
359                 );
360                 MetadataCreationResult::new(metadata_stub, true)
361             }
362         }
363     }
364 }
365
366 /// Returns from the enclosing function if the type metadata with the given
367 /// unique ID can be found in the type map.
368 macro_rules! return_if_metadata_created_in_meantime {
369     ($cx: expr, $unique_type_id: expr) => {
370         if let Some(metadata) =
371             debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id)
372         {
373             return MetadataCreationResult::new(metadata, true);
374         }
375     };
376 }
377
378 fn fixed_vec_metadata<'ll, 'tcx>(
379     cx: &CodegenCx<'ll, 'tcx>,
380     unique_type_id: UniqueTypeId,
381     array_or_slice_type: Ty<'tcx>,
382     element_type: Ty<'tcx>,
383     span: Span,
384 ) -> MetadataCreationResult<'ll> {
385     let element_type_metadata = type_metadata(cx, element_type, span);
386
387     return_if_metadata_created_in_meantime!(cx, unique_type_id);
388
389     let (size, align) = cx.size_and_align_of(array_or_slice_type);
390
391     let upper_bound = match array_or_slice_type.kind() {
392         ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong,
393         _ => -1,
394     };
395
396     let subrange =
397         unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) };
398
399     let subscripts = create_DIArray(DIB(cx), &[subrange]);
400     let metadata = unsafe {
401         llvm::LLVMRustDIBuilderCreateArrayType(
402             DIB(cx),
403             size.bits(),
404             align.bits() as u32,
405             element_type_metadata,
406             subscripts,
407         )
408     };
409
410     MetadataCreationResult::new(metadata, false)
411 }
412
413 fn vec_slice_metadata<'ll, 'tcx>(
414     cx: &CodegenCx<'ll, 'tcx>,
415     slice_ptr_type: Ty<'tcx>,
416     element_type: Ty<'tcx>,
417     unique_type_id: UniqueTypeId,
418     span: Span,
419 ) -> MetadataCreationResult<'ll> {
420     let data_ptr_type = cx.tcx.mk_imm_ptr(element_type);
421
422     let data_ptr_metadata = type_metadata(cx, data_ptr_type, span);
423
424     return_if_metadata_created_in_meantime!(cx, unique_type_id);
425
426     let slice_type_name = compute_debuginfo_type_name(cx.tcx, slice_ptr_type, true);
427
428     let (pointer_size, pointer_align) = cx.size_and_align_of(data_ptr_type);
429     let (usize_size, usize_align) = cx.size_and_align_of(cx.tcx.types.usize);
430
431     let member_descriptions = vec![
432         MemberDescription {
433             name: "data_ptr".to_owned(),
434             type_metadata: data_ptr_metadata,
435             offset: Size::ZERO,
436             size: pointer_size,
437             align: pointer_align,
438             flags: DIFlags::FlagZero,
439             discriminant: None,
440             source_info: None,
441         },
442         MemberDescription {
443             name: "length".to_owned(),
444             type_metadata: type_metadata(cx, cx.tcx.types.usize, span),
445             offset: pointer_size,
446             size: usize_size,
447             align: usize_align,
448             flags: DIFlags::FlagZero,
449             discriminant: None,
450             source_info: None,
451         },
452     ];
453
454     let file_metadata = unknown_file_metadata(cx);
455
456     let metadata = composite_type_metadata(
457         cx,
458         slice_ptr_type,
459         &slice_type_name,
460         unique_type_id,
461         member_descriptions,
462         NO_SCOPE_METADATA,
463         file_metadata,
464         span,
465     );
466     MetadataCreationResult::new(metadata, false)
467 }
468
469 fn subroutine_type_metadata<'ll, 'tcx>(
470     cx: &CodegenCx<'ll, 'tcx>,
471     unique_type_id: UniqueTypeId,
472     signature: ty::PolyFnSig<'tcx>,
473     span: Span,
474 ) -> MetadataCreationResult<'ll> {
475     let signature =
476         cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), signature);
477
478     let signature_metadata: Vec<_> = iter::once(
479         // return type
480         match signature.output().kind() {
481             ty::Tuple(tys) if tys.is_empty() => None,
482             _ => Some(type_metadata(cx, signature.output(), span)),
483         },
484     )
485     .chain(
486         // regular arguments
487         signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type, span))),
488     )
489     .collect();
490
491     return_if_metadata_created_in_meantime!(cx, unique_type_id);
492
493     MetadataCreationResult::new(
494         unsafe {
495             llvm::LLVMRustDIBuilderCreateSubroutineType(
496                 DIB(cx),
497                 create_DIArray(DIB(cx), &signature_metadata[..]),
498             )
499         },
500         false,
501     )
502 }
503
504 // FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill-
505 // defined concept. For the case of an actual trait pointer (i.e., `Box<Trait>`,
506 // `&Trait`), `trait_object_type` should be the whole thing (e.g, `Box<Trait>`) and
507 // `trait_type` should be the actual trait (e.g., `Trait`). Where the trait is part
508 // of a DST struct, there is no `trait_object_type` and the results of this
509 // function will be a little bit weird.
510 fn trait_pointer_metadata<'ll, 'tcx>(
511     cx: &CodegenCx<'ll, 'tcx>,
512     trait_type: Ty<'tcx>,
513     trait_object_type: Option<Ty<'tcx>>,
514     unique_type_id: UniqueTypeId,
515 ) -> &'ll DIType {
516     // The implementation provided here is a stub. It makes sure that the trait
517     // type is assigned the correct name, size, namespace, and source location.
518     // However, it does not describe the trait's methods.
519
520     let (containing_scope, trait_type_name) = match trait_object_type {
521         Some(trait_object_type) => match trait_object_type.kind() {
522             ty::Adt(def, _) => (
523                 Some(get_namespace_for_item(cx, def.did)),
524                 compute_debuginfo_type_name(cx.tcx, trait_object_type, false),
525             ),
526             ty::RawPtr(_) | ty::Ref(..) => {
527                 (NO_SCOPE_METADATA, compute_debuginfo_type_name(cx.tcx, trait_object_type, true))
528             }
529             _ => {
530                 bug!(
531                     "debuginfo: unexpected trait-object type in \
532                       trait_pointer_metadata(): {:?}",
533                     trait_object_type
534                 );
535             }
536         },
537
538         // No object type, use the trait type directly (no scope here since the type
539         // will be wrapped in the dyn$ synthetic type).
540         None => (NO_SCOPE_METADATA, compute_debuginfo_type_name(cx.tcx, trait_type, true)),
541     };
542
543     let file_metadata = unknown_file_metadata(cx);
544
545     let layout = cx.layout_of(cx.tcx.mk_mut_ptr(trait_type));
546
547     assert_eq!(abi::FAT_PTR_ADDR, 0);
548     assert_eq!(abi::FAT_PTR_EXTRA, 1);
549
550     let data_ptr_field = layout.field(cx, 0);
551     let vtable_field = layout.field(cx, 1);
552     let member_descriptions = vec![
553         MemberDescription {
554             name: "pointer".to_owned(),
555             type_metadata: type_metadata(
556                 cx,
557                 cx.tcx.mk_mut_ptr(cx.tcx.types.u8),
558                 rustc_span::DUMMY_SP,
559             ),
560             offset: layout.fields.offset(0),
561             size: data_ptr_field.size,
562             align: data_ptr_field.align.abi,
563             flags: DIFlags::FlagArtificial,
564             discriminant: None,
565             source_info: None,
566         },
567         MemberDescription {
568             name: "vtable".to_owned(),
569             type_metadata: type_metadata(cx, vtable_field.ty, rustc_span::DUMMY_SP),
570             offset: layout.fields.offset(1),
571             size: vtable_field.size,
572             align: vtable_field.align.abi,
573             flags: DIFlags::FlagArtificial,
574             discriminant: None,
575             source_info: None,
576         },
577     ];
578
579     composite_type_metadata(
580         cx,
581         trait_object_type.unwrap_or(trait_type),
582         &trait_type_name,
583         unique_type_id,
584         member_descriptions,
585         containing_scope,
586         file_metadata,
587         rustc_span::DUMMY_SP,
588     )
589 }
590
591 pub fn type_metadata<'ll, 'tcx>(
592     cx: &CodegenCx<'ll, 'tcx>,
593     t: Ty<'tcx>,
594     usage_site_span: Span,
595 ) -> &'ll DIType {
596     // Get the unique type ID of this type.
597     let unique_type_id = {
598         let mut type_map = debug_context(cx).type_map.borrow_mut();
599         // First, try to find the type in `TypeMap`. If we have seen it before, we
600         // can exit early here.
601         match type_map.find_metadata_for_type(t) {
602             Some(metadata) => {
603                 return metadata;
604             }
605             None => {
606                 // The Ty is not in the `TypeMap` but maybe we have already seen
607                 // an equivalent type (e.g., only differing in region arguments).
608                 // In order to find out, generate the unique type ID and look
609                 // that up.
610                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
611                 match type_map.find_metadata_for_unique_id(unique_type_id) {
612                     Some(metadata) => {
613                         // There is already an equivalent type in the TypeMap.
614                         // Register this Ty as an alias in the cache and
615                         // return the cached metadata.
616                         type_map.register_type_with_metadata(t, metadata);
617                         return metadata;
618                     }
619                     None => {
620                         // There really is no type metadata for this type, so
621                         // proceed by creating it.
622                         unique_type_id
623                     }
624                 }
625             }
626         }
627     };
628
629     debug!("type_metadata: {:?}", t);
630
631     let ptr_metadata = |ty: Ty<'tcx>| match *ty.kind() {
632         ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
633         ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
634         ty::Dynamic(..) => Ok(MetadataCreationResult::new(
635             trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
636             false,
637         )),
638         _ => {
639             let pointee_metadata = type_metadata(cx, ty, usage_site_span);
640
641             if let Some(metadata) =
642                 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
643             {
644                 return Err(metadata);
645             }
646
647             Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false))
648         }
649     };
650
651     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *t.kind() {
652         ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
653             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
654         }
655         ty::Tuple(elements) if elements.is_empty() => {
656             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
657         }
658         ty::Array(typ, _) | ty::Slice(typ) => {
659             fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
660         }
661         ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
662         ty::Dynamic(..) => {
663             MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
664         }
665         ty::Foreign(..) => {
666             MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false)
667         }
668         ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) {
669             Ok(res) => res,
670             Err(metadata) => return metadata,
671         },
672         ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) {
673             Ok(res) => res,
674             Err(metadata) => return metadata,
675         },
676         ty::FnDef(..) | ty::FnPtr(_) => {
677             if let Some(metadata) =
678                 debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id)
679             {
680                 return metadata;
681             }
682
683             // It's possible to create a self-referential
684             // type in Rust by using 'impl trait':
685             //
686             // fn foo() -> impl Copy { foo }
687             //
688             // See `TypeMap::remove_type` for more detals
689             // about the workaround.
690
691             let temp_type = {
692                 unsafe {
693                     // The choice of type here is pretty arbitrary -
694                     // anything reading the debuginfo for a recursive
695                     // type is going to see *something* weird - the only
696                     // question is what exactly it will see.
697                     let name = "<recur_type>";
698                     llvm::LLVMRustDIBuilderCreateBasicType(
699                         DIB(cx),
700                         name.as_ptr().cast(),
701                         name.len(),
702                         cx.size_of(t).bits(),
703                         DW_ATE_unsigned,
704                     )
705                 }
706             };
707
708             let type_map = &debug_context(cx).type_map;
709             type_map.borrow_mut().register_type_with_metadata(t, temp_type);
710
711             let fn_metadata =
712                 subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span)
713                     .metadata;
714
715             type_map.borrow_mut().remove_type(t);
716
717             // This is actually a function pointer, so wrap it in pointer DI.
718             MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false)
719         }
720         ty::Closure(def_id, substs) => {
721             let upvar_tys: Vec<_> = substs.as_closure().upvar_tys().collect();
722             let containing_scope = get_namespace_for_item(cx, def_id);
723             prepare_tuple_metadata(
724                 cx,
725                 t,
726                 &upvar_tys,
727                 unique_type_id,
728                 usage_site_span,
729                 Some(containing_scope),
730             )
731             .finalize(cx)
732         }
733         ty::Generator(def_id, substs, _) => {
734             let upvar_tys: Vec<_> = substs
735                 .as_generator()
736                 .prefix_tys()
737                 .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t))
738                 .collect();
739             prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys)
740                 .finalize(cx)
741         }
742         ty::Adt(def, ..) => match def.adt_kind() {
743             AdtKind::Struct => {
744                 prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
745             }
746             AdtKind::Union => {
747                 prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx)
748             }
749             AdtKind::Enum => {
750                 prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![])
751                     .finalize(cx)
752             }
753         },
754         ty::Tuple(elements) => {
755             let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect();
756             prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA)
757                 .finalize(cx)
758         }
759         // Type parameters from polymorphized functions.
760         ty::Param(_) => MetadataCreationResult::new(param_type_metadata(cx, t), false),
761         _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t),
762     };
763
764     {
765         let mut type_map = debug_context(cx).type_map.borrow_mut();
766
767         if already_stored_in_typemap {
768             // Also make sure that we already have a `TypeMap` entry for the unique type ID.
769             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
770                 Some(metadata) => metadata,
771                 None => {
772                     span_bug!(
773                         usage_site_span,
774                         "expected type metadata for unique \
775                                type ID '{}' to already be in \
776                                the `debuginfo::TypeMap` but it \
777                                was not. (Ty = {})",
778                         type_map.get_unique_type_id_as_string(unique_type_id),
779                         t
780                     );
781                 }
782             };
783
784             match type_map.find_metadata_for_type(t) {
785                 Some(metadata) => {
786                     if metadata != metadata_for_uid {
787                         span_bug!(
788                             usage_site_span,
789                             "mismatch between `Ty` and \
790                                    `UniqueTypeId` maps in \
791                                    `debuginfo::TypeMap`. \
792                                    UniqueTypeId={}, Ty={}",
793                             type_map.get_unique_type_id_as_string(unique_type_id),
794                             t
795                         );
796                     }
797                 }
798                 None => {
799                     type_map.register_type_with_metadata(t, metadata);
800                 }
801             }
802         } else {
803             type_map.register_type_with_metadata(t, metadata);
804             type_map.register_unique_id_with_metadata(unique_type_id, metadata);
805         }
806     }
807
808     metadata
809 }
810
811 fn hex_encode(data: &[u8]) -> String {
812     let mut hex_string = String::with_capacity(data.len() * 2);
813     for byte in data.iter() {
814         write!(&mut hex_string, "{:02x}", byte).unwrap();
815     }
816     hex_string
817 }
818
819 pub fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFile) -> &'ll DIFile {
820     debug!("file_metadata: file_name: {:?}", source_file.name);
821
822     let hash = Some(&source_file.src_hash);
823     let file_name = Some(source_file.name.prefer_remapped().to_string());
824     let directory = if source_file.is_real_file() && !source_file.is_imported() {
825         Some(
826             cx.sess()
827                 .opts
828                 .working_dir
829                 .to_string_lossy(FileNameDisplayPreference::Remapped)
830                 .to_string(),
831         )
832     } else {
833         // If the path comes from an upstream crate we assume it has been made
834         // independent of the compiler's working directory one way or another.
835         None
836     };
837     file_metadata_raw(cx, file_name, directory, hash)
838 }
839
840 pub fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
841     file_metadata_raw(cx, None, None, None)
842 }
843
844 fn file_metadata_raw<'ll>(
845     cx: &CodegenCx<'ll, '_>,
846     file_name: Option<String>,
847     directory: Option<String>,
848     hash: Option<&SourceFileHash>,
849 ) -> &'ll DIFile {
850     let key = (file_name, directory);
851
852     match debug_context(cx).created_files.borrow_mut().entry(key) {
853         Entry::Occupied(o) => o.get(),
854         Entry::Vacant(v) => {
855             let (file_name, directory) = v.key();
856             debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory);
857
858             let file_name = file_name.as_deref().unwrap_or("<unknown>");
859             let directory = directory.as_deref().unwrap_or("");
860
861             let (hash_kind, hash_value) = match hash {
862                 Some(hash) => {
863                     let kind = match hash.kind {
864                         rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5,
865                         rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1,
866                         rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256,
867                     };
868                     (kind, hex_encode(hash.hash_bytes()))
869                 }
870                 None => (llvm::ChecksumKind::None, String::new()),
871             };
872
873             let file_metadata = unsafe {
874                 llvm::LLVMRustDIBuilderCreateFile(
875                     DIB(cx),
876                     file_name.as_ptr().cast(),
877                     file_name.len(),
878                     directory.as_ptr().cast(),
879                     directory.len(),
880                     hash_kind,
881                     hash_value.as_ptr().cast(),
882                     hash_value.len(),
883                 )
884             };
885
886             v.insert(file_metadata);
887             file_metadata
888         }
889     }
890 }
891
892 trait MsvcBasicName {
893     fn msvc_basic_name(self) -> &'static str;
894 }
895
896 impl MsvcBasicName for ty::IntTy {
897     fn msvc_basic_name(self) -> &'static str {
898         match self {
899             ty::IntTy::Isize => "ptrdiff_t",
900             ty::IntTy::I8 => "__int8",
901             ty::IntTy::I16 => "__int16",
902             ty::IntTy::I32 => "__int32",
903             ty::IntTy::I64 => "__int64",
904             ty::IntTy::I128 => "__int128",
905         }
906     }
907 }
908
909 impl MsvcBasicName for ty::UintTy {
910     fn msvc_basic_name(self) -> &'static str {
911         match self {
912             ty::UintTy::Usize => "size_t",
913             ty::UintTy::U8 => "unsigned __int8",
914             ty::UintTy::U16 => "unsigned __int16",
915             ty::UintTy::U32 => "unsigned __int32",
916             ty::UintTy::U64 => "unsigned __int64",
917             ty::UintTy::U128 => "unsigned __int128",
918         }
919     }
920 }
921
922 impl MsvcBasicName for ty::FloatTy {
923     fn msvc_basic_name(self) -> &'static str {
924         match self {
925             ty::FloatTy::F32 => "float",
926             ty::FloatTy::F64 => "double",
927         }
928     }
929 }
930
931 fn basic_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
932     debug!("basic_type_metadata: {:?}", t);
933
934     // When targeting MSVC, emit MSVC style type names for compatibility with
935     // .natvis visualizers (and perhaps other existing native debuggers?)
936     let msvc_like_names = cx.tcx.sess.target.is_like_msvc;
937
938     let (name, encoding) = match t.kind() {
939         ty::Never => ("!", DW_ATE_unsigned),
940         ty::Tuple(elements) if elements.is_empty() => ("()", DW_ATE_unsigned),
941         ty::Bool => ("bool", DW_ATE_boolean),
942         ty::Char => ("char", DW_ATE_unsigned_char),
943         ty::Int(int_ty) if msvc_like_names => (int_ty.msvc_basic_name(), DW_ATE_signed),
944         ty::Uint(uint_ty) if msvc_like_names => (uint_ty.msvc_basic_name(), DW_ATE_unsigned),
945         ty::Float(float_ty) if msvc_like_names => (float_ty.msvc_basic_name(), DW_ATE_float),
946         ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed),
947         ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned),
948         ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float),
949         _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"),
950     };
951
952     let ty_metadata = unsafe {
953         llvm::LLVMRustDIBuilderCreateBasicType(
954             DIB(cx),
955             name.as_ptr().cast(),
956             name.len(),
957             cx.size_of(t).bits(),
958             encoding,
959         )
960     };
961
962     if !msvc_like_names {
963         return ty_metadata;
964     }
965
966     let typedef_name = match t.kind() {
967         ty::Int(int_ty) => int_ty.name_str(),
968         ty::Uint(uint_ty) => uint_ty.name_str(),
969         ty::Float(float_ty) => float_ty.name_str(),
970         _ => return ty_metadata,
971     };
972
973     let typedef_metadata = unsafe {
974         llvm::LLVMRustDIBuilderCreateTypedef(
975             DIB(cx),
976             ty_metadata,
977             typedef_name.as_ptr().cast(),
978             typedef_name.len(),
979             unknown_file_metadata(cx),
980             0,
981             None,
982         )
983     };
984
985     typedef_metadata
986 }
987
988 fn foreign_type_metadata<'ll, 'tcx>(
989     cx: &CodegenCx<'ll, 'tcx>,
990     t: Ty<'tcx>,
991     unique_type_id: UniqueTypeId,
992 ) -> &'ll DIType {
993     debug!("foreign_type_metadata: {:?}", t);
994
995     let name = compute_debuginfo_type_name(cx.tcx, t, false);
996     create_struct_stub(cx, t, &name, unique_type_id, NO_SCOPE_METADATA, DIFlags::FlagZero)
997 }
998
999 fn pointer_type_metadata<'ll, 'tcx>(
1000     cx: &CodegenCx<'ll, 'tcx>,
1001     pointer_type: Ty<'tcx>,
1002     pointee_type_metadata: &'ll DIType,
1003 ) -> &'ll DIType {
1004     let (pointer_size, pointer_align) = cx.size_and_align_of(pointer_type);
1005     let name = compute_debuginfo_type_name(cx.tcx, pointer_type, false);
1006     unsafe {
1007         llvm::LLVMRustDIBuilderCreatePointerType(
1008             DIB(cx),
1009             pointee_type_metadata,
1010             pointer_size.bits(),
1011             pointer_align.bits() as u32,
1012             0, // Ignore DWARF address space.
1013             name.as_ptr().cast(),
1014             name.len(),
1015         )
1016     }
1017 }
1018
1019 fn param_type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType {
1020     debug!("param_type_metadata: {:?}", t);
1021     let name = format!("{:?}", t);
1022     unsafe {
1023         llvm::LLVMRustDIBuilderCreateBasicType(
1024             DIB(cx),
1025             name.as_ptr().cast(),
1026             name.len(),
1027             Size::ZERO.bits(),
1028             DW_ATE_unsigned,
1029         )
1030     }
1031 }
1032
1033 pub fn compile_unit_metadata<'ll, 'tcx>(
1034     tcx: TyCtxt<'tcx>,
1035     codegen_unit_name: &str,
1036     debug_context: &CrateDebugContext<'ll, 'tcx>,
1037 ) -> &'ll DIDescriptor {
1038     let mut name_in_debuginfo = match tcx.sess.local_crate_source_file {
1039         Some(ref path) => path.clone(),
1040         None => PathBuf::from(&*tcx.crate_name(LOCAL_CRATE).as_str()),
1041     };
1042
1043     // The OSX linker has an idiosyncrasy where it will ignore some debuginfo
1044     // if multiple object files with the same `DW_AT_name` are linked together.
1045     // As a workaround we generate unique names for each object file. Those do
1046     // not correspond to an actual source file but that is harmless.
1047     if tcx.sess.target.is_like_osx {
1048         name_in_debuginfo.push("@");
1049         name_in_debuginfo.push(codegen_unit_name);
1050     }
1051
1052     debug!("compile_unit_metadata: {:?}", name_in_debuginfo);
1053     let rustc_producer =
1054         format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),);
1055     // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice.
1056     let producer = format!("clang LLVM ({})", rustc_producer);
1057
1058     let name_in_debuginfo = name_in_debuginfo.to_string_lossy();
1059     let work_dir = tcx.sess.opts.working_dir.to_string_lossy(FileNameDisplayPreference::Remapped);
1060     let flags = "\0";
1061     let output_filenames = tcx.output_filenames(());
1062     let out_dir = &output_filenames.out_directory;
1063     let split_name = if tcx.sess.target_can_use_split_dwarf() {
1064         output_filenames
1065             .split_dwarf_path(tcx.sess.split_debuginfo(), Some(codegen_unit_name))
1066             .map(|f| out_dir.join(f))
1067     } else {
1068         None
1069     }
1070     .unwrap_or_default();
1071     let split_name = split_name.to_str().unwrap();
1072
1073     // FIXME(#60020):
1074     //
1075     //    This should actually be
1076     //
1077     //        let kind = DebugEmissionKind::from_generic(tcx.sess.opts.debuginfo);
1078     //
1079     //    That is, we should set LLVM's emission kind to `LineTablesOnly` if
1080     //    we are compiling with "limited" debuginfo. However, some of the
1081     //    existing tools relied on slightly more debuginfo being generated than
1082     //    would be the case with `LineTablesOnly`, and we did not want to break
1083     //    these tools in a "drive-by fix", without a good idea or plan about
1084     //    what limited debuginfo should exactly look like. So for now we keep
1085     //    the emission kind as `FullDebug`.
1086     //
1087     //    See https://github.com/rust-lang/rust/issues/60020 for details.
1088     let kind = DebugEmissionKind::FullDebug;
1089     assert!(tcx.sess.opts.debuginfo != DebugInfo::None);
1090
1091     unsafe {
1092         let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
1093             debug_context.builder,
1094             name_in_debuginfo.as_ptr().cast(),
1095             name_in_debuginfo.len(),
1096             work_dir.as_ptr().cast(),
1097             work_dir.len(),
1098             llvm::ChecksumKind::None,
1099             ptr::null(),
1100             0,
1101         );
1102
1103         let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit(
1104             debug_context.builder,
1105             DW_LANG_RUST,
1106             compile_unit_file,
1107             producer.as_ptr().cast(),
1108             producer.len(),
1109             tcx.sess.opts.optimize != config::OptLevel::No,
1110             flags.as_ptr().cast(),
1111             0,
1112             // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
1113             // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
1114             // output(s).
1115             split_name.as_ptr().cast(),
1116             split_name.len(),
1117             kind,
1118             0,
1119             tcx.sess.opts.debugging_opts.split_dwarf_inlining,
1120         );
1121
1122         if tcx.sess.opts.debugging_opts.profile {
1123             let cu_desc_metadata =
1124                 llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata);
1125             let default_gcda_path = &output_filenames.with_extension("gcda");
1126             let gcda_path =
1127                 tcx.sess.opts.debugging_opts.profile_emit.as_ref().unwrap_or(default_gcda_path);
1128
1129             let gcov_cu_info = [
1130                 path_to_mdstring(debug_context.llcontext, &output_filenames.with_extension("gcno")),
1131                 path_to_mdstring(debug_context.llcontext, gcda_path),
1132                 cu_desc_metadata,
1133             ];
1134             let gcov_metadata = llvm::LLVMMDNodeInContext(
1135                 debug_context.llcontext,
1136                 gcov_cu_info.as_ptr(),
1137                 gcov_cu_info.len() as c_uint,
1138             );
1139
1140             let llvm_gcov_ident = cstr!("llvm.gcov");
1141             llvm::LLVMAddNamedMetadataOperand(
1142                 debug_context.llmod,
1143                 llvm_gcov_ident.as_ptr(),
1144                 gcov_metadata,
1145             );
1146         }
1147
1148         // Insert `llvm.ident` metadata on the wasm targets since that will
1149         // get hooked up to the "producer" sections `processed-by` information.
1150         if tcx.sess.target.is_like_wasm {
1151             let name_metadata = llvm::LLVMMDStringInContext(
1152                 debug_context.llcontext,
1153                 rustc_producer.as_ptr().cast(),
1154                 rustc_producer.as_bytes().len() as c_uint,
1155             );
1156             llvm::LLVMAddNamedMetadataOperand(
1157                 debug_context.llmod,
1158                 cstr!("llvm.ident").as_ptr(),
1159                 llvm::LLVMMDNodeInContext(debug_context.llcontext, &name_metadata, 1),
1160             );
1161         }
1162
1163         return unit_metadata;
1164     };
1165
1166     fn path_to_mdstring<'ll>(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value {
1167         let path_str = path_to_c_string(path);
1168         unsafe {
1169             llvm::LLVMMDStringInContext(
1170                 llcx,
1171                 path_str.as_ptr(),
1172                 path_str.as_bytes().len() as c_uint,
1173             )
1174         }
1175     }
1176 }
1177
1178 struct MetadataCreationResult<'ll> {
1179     metadata: &'ll DIType,
1180     already_stored_in_typemap: bool,
1181 }
1182
1183 impl<'ll> MetadataCreationResult<'ll> {
1184     fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self {
1185         MetadataCreationResult { metadata, already_stored_in_typemap }
1186     }
1187 }
1188
1189 #[derive(Debug)]
1190 struct SourceInfo<'ll> {
1191     file: &'ll DIFile,
1192     line: u32,
1193 }
1194
1195 /// Description of a type member, which can either be a regular field (as in
1196 /// structs or tuples) or an enum variant.
1197 #[derive(Debug)]
1198 struct MemberDescription<'ll> {
1199     name: String,
1200     type_metadata: &'ll DIType,
1201     offset: Size,
1202     size: Size,
1203     align: Align,
1204     flags: DIFlags,
1205     discriminant: Option<u64>,
1206     source_info: Option<SourceInfo<'ll>>,
1207 }
1208
1209 impl<'ll> MemberDescription<'ll> {
1210     fn into_metadata(
1211         self,
1212         cx: &CodegenCx<'ll, '_>,
1213         composite_type_metadata: &'ll DIScope,
1214     ) -> &'ll DIType {
1215         let (file, line) = self
1216             .source_info
1217             .map(|info| (info.file, info.line))
1218             .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER));
1219         unsafe {
1220             llvm::LLVMRustDIBuilderCreateVariantMemberType(
1221                 DIB(cx),
1222                 composite_type_metadata,
1223                 self.name.as_ptr().cast(),
1224                 self.name.len(),
1225                 file,
1226                 line,
1227                 self.size.bits(),
1228                 self.align.bits() as u32,
1229                 self.offset.bits(),
1230                 self.discriminant.map(|v| cx.const_u64(v)),
1231                 self.flags,
1232                 self.type_metadata,
1233             )
1234         }
1235     }
1236 }
1237
1238 /// A factory for `MemberDescription`s. It produces a list of member descriptions
1239 /// for some record-like type. `MemberDescriptionFactory`s are used to defer the
1240 /// creation of type member descriptions in order to break cycles arising from
1241 /// recursive type definitions.
1242 enum MemberDescriptionFactory<'ll, 'tcx> {
1243     StructMDF(StructMemberDescriptionFactory<'tcx>),
1244     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1245     EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>),
1246     UnionMDF(UnionMemberDescriptionFactory<'tcx>),
1247     VariantMDF(VariantMemberDescriptionFactory<'tcx>),
1248 }
1249
1250 impl<'ll, 'tcx> MemberDescriptionFactory<'ll, 'tcx> {
1251     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1252         match *self {
1253             StructMDF(ref this) => this.create_member_descriptions(cx),
1254             TupleMDF(ref this) => this.create_member_descriptions(cx),
1255             EnumMDF(ref this) => this.create_member_descriptions(cx),
1256             UnionMDF(ref this) => this.create_member_descriptions(cx),
1257             VariantMDF(ref this) => this.create_member_descriptions(cx),
1258         }
1259     }
1260 }
1261
1262 //=-----------------------------------------------------------------------------
1263 // Structs
1264 //=-----------------------------------------------------------------------------
1265
1266 /// Creates `MemberDescription`s for the fields of a struct.
1267 struct StructMemberDescriptionFactory<'tcx> {
1268     ty: Ty<'tcx>,
1269     variant: &'tcx ty::VariantDef,
1270     span: Span,
1271 }
1272
1273 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
1274     fn create_member_descriptions<'ll>(
1275         &self,
1276         cx: &CodegenCx<'ll, 'tcx>,
1277     ) -> Vec<MemberDescription<'ll>> {
1278         let layout = cx.layout_of(self.ty);
1279         self.variant
1280             .fields
1281             .iter()
1282             .enumerate()
1283             .map(|(i, f)| {
1284                 let name = if self.variant.ctor_kind == CtorKind::Fn {
1285                     format!("__{}", i)
1286                 } else {
1287                     f.ident.to_string()
1288                 };
1289                 let field = layout.field(cx, i);
1290                 MemberDescription {
1291                     name,
1292                     type_metadata: type_metadata(cx, field.ty, self.span),
1293                     offset: layout.fields.offset(i),
1294                     size: field.size,
1295                     align: field.align.abi,
1296                     flags: DIFlags::FlagZero,
1297                     discriminant: None,
1298                     source_info: None,
1299                 }
1300             })
1301             .collect()
1302     }
1303 }
1304
1305 fn prepare_struct_metadata<'ll, 'tcx>(
1306     cx: &CodegenCx<'ll, 'tcx>,
1307     struct_type: Ty<'tcx>,
1308     unique_type_id: UniqueTypeId,
1309     span: Span,
1310 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1311     let struct_name = compute_debuginfo_type_name(cx.tcx, struct_type, false);
1312
1313     let (struct_def_id, variant) = match struct_type.kind() {
1314         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1315         _ => bug!("prepare_struct_metadata on a non-ADT"),
1316     };
1317
1318     let containing_scope = get_namespace_for_item(cx, struct_def_id);
1319
1320     let struct_metadata_stub = create_struct_stub(
1321         cx,
1322         struct_type,
1323         &struct_name,
1324         unique_type_id,
1325         Some(containing_scope),
1326         DIFlags::FlagZero,
1327     );
1328
1329     create_and_register_recursive_type_forward_declaration(
1330         cx,
1331         struct_type,
1332         unique_type_id,
1333         struct_metadata_stub,
1334         struct_metadata_stub,
1335         StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }),
1336     )
1337 }
1338
1339 //=-----------------------------------------------------------------------------
1340 // Tuples
1341 //=-----------------------------------------------------------------------------
1342
1343 /// Returns names of captured upvars for closures and generators.
1344 ///
1345 /// Here are some examples:
1346 ///  - `name__field1__field2` when the upvar is captured by value.
1347 ///  - `_ref__name__field` when the upvar is captured by reference.
1348 fn closure_saved_names_of_captured_variables(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<String> {
1349     let body = tcx.optimized_mir(def_id);
1350
1351     body.var_debug_info
1352         .iter()
1353         .filter_map(|var| {
1354             let is_ref = match var.value {
1355                 mir::VarDebugInfoContents::Place(place) if place.local == mir::Local::new(1) => {
1356                     // The projection is either `[.., Field, Deref]` or `[.., Field]`. It
1357                     // implies whether the variable is captured by value or by reference.
1358                     matches!(place.projection.last().unwrap(), mir::ProjectionElem::Deref)
1359                 }
1360                 _ => return None,
1361             };
1362             let prefix = if is_ref { "_ref__" } else { "" };
1363             Some(prefix.to_owned() + &var.name.as_str())
1364         })
1365         .collect::<Vec<_>>()
1366 }
1367
1368 /// Creates `MemberDescription`s for the fields of a tuple.
1369 struct TupleMemberDescriptionFactory<'tcx> {
1370     ty: Ty<'tcx>,
1371     component_types: Vec<Ty<'tcx>>,
1372     span: Span,
1373 }
1374
1375 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
1376     fn create_member_descriptions<'ll>(
1377         &self,
1378         cx: &CodegenCx<'ll, 'tcx>,
1379     ) -> Vec<MemberDescription<'ll>> {
1380         let mut capture_names = match *self.ty.kind() {
1381             ty::Generator(def_id, ..) | ty::Closure(def_id, ..) => {
1382                 Some(closure_saved_names_of_captured_variables(cx.tcx, def_id).into_iter())
1383             }
1384             _ => None,
1385         };
1386         let layout = cx.layout_of(self.ty);
1387         self.component_types
1388             .iter()
1389             .enumerate()
1390             .map(|(i, &component_type)| {
1391                 let (size, align) = cx.size_and_align_of(component_type);
1392                 let name = if let Some(names) = capture_names.as_mut() {
1393                     names.next().unwrap()
1394                 } else {
1395                     format!("__{}", i)
1396                 };
1397                 MemberDescription {
1398                     name,
1399                     type_metadata: type_metadata(cx, component_type, self.span),
1400                     offset: layout.fields.offset(i),
1401                     size,
1402                     align,
1403                     flags: DIFlags::FlagZero,
1404                     discriminant: None,
1405                     source_info: None,
1406                 }
1407             })
1408             .collect()
1409     }
1410 }
1411
1412 fn prepare_tuple_metadata<'ll, 'tcx>(
1413     cx: &CodegenCx<'ll, 'tcx>,
1414     tuple_type: Ty<'tcx>,
1415     component_types: &[Ty<'tcx>],
1416     unique_type_id: UniqueTypeId,
1417     span: Span,
1418     containing_scope: Option<&'ll DIScope>,
1419 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1420     let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false);
1421
1422     let struct_stub = create_struct_stub(
1423         cx,
1424         tuple_type,
1425         &tuple_name[..],
1426         unique_type_id,
1427         containing_scope,
1428         DIFlags::FlagZero,
1429     );
1430
1431     create_and_register_recursive_type_forward_declaration(
1432         cx,
1433         tuple_type,
1434         unique_type_id,
1435         struct_stub,
1436         struct_stub,
1437         TupleMDF(TupleMemberDescriptionFactory {
1438             ty: tuple_type,
1439             component_types: component_types.to_vec(),
1440             span,
1441         }),
1442     )
1443 }
1444
1445 //=-----------------------------------------------------------------------------
1446 // Unions
1447 //=-----------------------------------------------------------------------------
1448
1449 struct UnionMemberDescriptionFactory<'tcx> {
1450     layout: TyAndLayout<'tcx>,
1451     variant: &'tcx ty::VariantDef,
1452     span: Span,
1453 }
1454
1455 impl<'tcx> UnionMemberDescriptionFactory<'tcx> {
1456     fn create_member_descriptions<'ll>(
1457         &self,
1458         cx: &CodegenCx<'ll, 'tcx>,
1459     ) -> Vec<MemberDescription<'ll>> {
1460         self.variant
1461             .fields
1462             .iter()
1463             .enumerate()
1464             .map(|(i, f)| {
1465                 let field = self.layout.field(cx, i);
1466                 MemberDescription {
1467                     name: f.ident.to_string(),
1468                     type_metadata: type_metadata(cx, field.ty, self.span),
1469                     offset: Size::ZERO,
1470                     size: field.size,
1471                     align: field.align.abi,
1472                     flags: DIFlags::FlagZero,
1473                     discriminant: None,
1474                     source_info: None,
1475                 }
1476             })
1477             .collect()
1478     }
1479 }
1480
1481 fn prepare_union_metadata<'ll, 'tcx>(
1482     cx: &CodegenCx<'ll, 'tcx>,
1483     union_type: Ty<'tcx>,
1484     unique_type_id: UniqueTypeId,
1485     span: Span,
1486 ) -> RecursiveTypeDescription<'ll, 'tcx> {
1487     let union_name = compute_debuginfo_type_name(cx.tcx, union_type, false);
1488
1489     let (union_def_id, variant) = match union_type.kind() {
1490         ty::Adt(def, _) => (def.did, def.non_enum_variant()),
1491         _ => bug!("prepare_union_metadata on a non-ADT"),
1492     };
1493
1494     let containing_scope = get_namespace_for_item(cx, union_def_id);
1495
1496     let union_metadata_stub =
1497         create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope);
1498
1499     create_and_register_recursive_type_forward_declaration(
1500         cx,
1501         union_type,
1502         unique_type_id,
1503         union_metadata_stub,
1504         union_metadata_stub,
1505         UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }),
1506     )
1507 }
1508
1509 //=-----------------------------------------------------------------------------
1510 // Enums
1511 //=-----------------------------------------------------------------------------
1512
1513 /// DWARF variant support is only available starting in LLVM 8, but
1514 /// on MSVC we have to use the fallback mode, because LLVM doesn't
1515 /// lower variant parts to PDB.
1516 fn use_enum_fallback(cx: &CodegenCx<'_, '_>) -> bool {
1517     cx.sess().target.is_like_msvc
1518 }
1519
1520 // FIXME(eddyb) maybe precompute this? Right now it's computed once
1521 // per generator monomorphization, but it doesn't depend on substs.
1522 fn generator_layout_and_saved_local_names<'tcx>(
1523     tcx: TyCtxt<'tcx>,
1524     def_id: DefId,
1525 ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>) {
1526     let body = tcx.optimized_mir(def_id);
1527     let generator_layout = body.generator_layout().unwrap();
1528     let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys);
1529
1530     let state_arg = mir::Local::new(1);
1531     for var in &body.var_debug_info {
1532         let place = if let mir::VarDebugInfoContents::Place(p) = var.value { p } else { continue };
1533         if place.local != state_arg {
1534             continue;
1535         }
1536         match place.projection[..] {
1537             [
1538                 // Deref of the `Pin<&mut Self>` state argument.
1539                 mir::ProjectionElem::Field(..),
1540                 mir::ProjectionElem::Deref,
1541                 // Field of a variant of the state.
1542                 mir::ProjectionElem::Downcast(_, variant),
1543                 mir::ProjectionElem::Field(field, _),
1544             ] => {
1545                 let name = &mut generator_saved_local_names
1546                     [generator_layout.variant_fields[variant][field]];
1547                 if name.is_none() {
1548                     name.replace(var.name);
1549                 }
1550             }
1551             _ => {}
1552         }
1553     }
1554     (generator_layout, generator_saved_local_names)
1555 }
1556
1557 /// Describes the members of an enum value; an enum is described as a union of
1558 /// structs in DWARF. This `MemberDescriptionFactory` provides the description for
1559 /// the members of this union; so for every variant of the given enum, this
1560 /// factory will produce one `MemberDescription` (all with no name and a fixed
1561 /// offset of zero bytes).
1562 struct EnumMemberDescriptionFactory<'ll, 'tcx> {
1563     enum_type: Ty<'tcx>,
1564     layout: TyAndLayout<'tcx>,
1565     tag_type_metadata: Option<&'ll DIType>,
1566     common_members: Vec<Option<&'ll DIType>>,
1567     span: Span,
1568 }
1569
1570 impl<'ll, 'tcx> EnumMemberDescriptionFactory<'ll, 'tcx> {
1571     fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<MemberDescription<'ll>> {
1572         let generator_variant_info_data = match *self.enum_type.kind() {
1573             ty::Generator(def_id, ..) => {
1574                 Some(generator_layout_and_saved_local_names(cx.tcx, def_id))
1575             }
1576             _ => None,
1577         };
1578
1579         let variant_info_for = |index: VariantIdx| match *self.enum_type.kind() {
1580             ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]),
1581             ty::Generator(def_id, _, _) => {
1582                 let (generator_layout, generator_saved_local_names) =
1583                     generator_variant_info_data.as_ref().unwrap();
1584                 VariantInfo::Generator {
1585                     def_id,
1586                     generator_layout: *generator_layout,
1587                     generator_saved_local_names,
1588                     variant_index: index,
1589                 }
1590             }
1591             _ => bug!(),
1592         };
1593
1594         let fallback = use_enum_fallback(cx);
1595         // This will always find the metadata in the type map.
1596         let self_metadata = type_metadata(cx, self.enum_type, self.span);
1597
1598         match self.layout.variants {
1599             Variants::Single { index } => {
1600                 if let ty::Adt(adt, _) = self.enum_type.kind() {
1601                     if adt.variants.is_empty() {
1602                         return vec![];
1603                     }
1604                 }
1605
1606                 let variant_info = variant_info_for(index);
1607                 let (variant_type_metadata, member_description_factory) =
1608                     describe_enum_variant(cx, self.layout, variant_info, self_metadata, self.span);
1609
1610                 let member_descriptions = member_description_factory.create_member_descriptions(cx);
1611
1612                 set_members_of_composite_type(
1613                     cx,
1614                     self.enum_type,
1615                     variant_type_metadata,
1616                     member_descriptions,
1617                     Some(&self.common_members),
1618                 );
1619                 vec![MemberDescription {
1620                     name: variant_info.variant_name(),
1621                     type_metadata: variant_type_metadata,
1622                     offset: Size::ZERO,
1623                     size: self.layout.size,
1624                     align: self.layout.align.abi,
1625                     flags: DIFlags::FlagZero,
1626                     discriminant: None,
1627                     source_info: variant_info.source_info(cx),
1628                 }]
1629             }
1630             Variants::Multiple {
1631                 tag_encoding: TagEncoding::Direct,
1632                 tag_field,
1633                 ref variants,
1634                 ..
1635             } => {
1636                 let fallback_discr_variant = if fallback {
1637                     // For MSVC, we generate a union of structs for each variant and an
1638                     // explicit discriminant field roughly equivalent to the following C:
1639                     // ```c
1640                     // union enum$<{name}> {
1641                     //   struct {variant 0 name} {
1642                     //     <variant 0 fields>
1643                     //   } variant0;
1644                     //   <other variant structs>
1645                     //   {name} discriminant;
1646                     // }
1647                     // ```
1648                     // The natvis in `intrinsic.natvis` then matches on `this.discriminant` to
1649                     // determine which variant is active and then displays it.
1650                     let enum_layout = self.layout;
1651                     let offset = enum_layout.fields.offset(tag_field);
1652                     let discr_ty = enum_layout.field(cx, tag_field).ty;
1653                     let (size, align) = cx.size_and_align_of(discr_ty);
1654                     Some(MemberDescription {
1655                         name: "discriminant".into(),
1656                         type_metadata: self.tag_type_metadata.unwrap(),
1657                         offset,
1658                         size,
1659                         align,
1660                         flags: DIFlags::FlagZero,
1661                         discriminant: None,
1662                         source_info: None,
1663                     })
1664                 } else {
1665                     None
1666                 };
1667
1668                 variants
1669                     .iter_enumerated()
1670                     .map(|(i, _)| {
1671                         let variant = self.layout.for_variant(cx, i);
1672                         let variant_info = variant_info_for(i);
1673                         let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1674                             cx,
1675                             variant,
1676                             variant_info,
1677                             self_metadata,
1678                             self.span,
1679                         );
1680
1681                         let member_descriptions =
1682                             member_desc_factory.create_member_descriptions(cx);
1683
1684                         set_members_of_composite_type(
1685                             cx,
1686                             self.enum_type,
1687                             variant_type_metadata,
1688                             member_descriptions,
1689                             Some(&self.common_members),
1690                         );
1691
1692                         MemberDescription {
1693                             name: if fallback {
1694                                 format!("variant{}", i.as_u32())
1695                             } else {
1696                                 variant_info.variant_name()
1697                             },
1698                             type_metadata: variant_type_metadata,
1699                             offset: Size::ZERO,
1700                             size: self.layout.size,
1701                             align: self.layout.align.abi,
1702                             flags: DIFlags::FlagZero,
1703                             discriminant: Some(
1704                                 self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val
1705                                     as u64,
1706                             ),
1707                             source_info: variant_info.source_info(cx),
1708                         }
1709                     })
1710                     .chain(fallback_discr_variant.into_iter())
1711                     .collect()
1712             }
1713             Variants::Multiple {
1714                 tag_encoding:
1715                     TagEncoding::Niche { ref niche_variants, niche_start, dataful_variant },
1716                 tag,
1717                 ref variants,
1718                 tag_field,
1719             } => {
1720                 let calculate_niche_value = |i: VariantIdx| {
1721                     if i == dataful_variant {
1722                         None
1723                     } else {
1724                         let value = (i.as_u32() as u128)
1725                             .wrapping_sub(niche_variants.start().as_u32() as u128)
1726                             .wrapping_add(niche_start);
1727                         let value = tag.value.size(cx).truncate(value);
1728                         // NOTE(eddyb) do *NOT* remove this assert, until
1729                         // we pass the full 128-bit value to LLVM, otherwise
1730                         // truncation will be silent and remain undetected.
1731                         assert_eq!(value as u64 as u128, value);
1732                         Some(value as u64)
1733                     }
1734                 };
1735
1736                 // For MSVC, we will generate a union of two fields, one for the dataful variant
1737                 // and one that just points to the discriminant. We also create an enum that
1738                 // contains tag values for the non-dataful variants and make the discriminant field
1739                 // that type. We then use natvis to render the enum type correctly in Windbg/VS.
1740                 // This will generate debuginfo roughly equivalent to the following C:
1741                 // ```c
1742                 // union enum$<{name}, {min niche}, {max niche}, {dataful variant name}> {
1743                 //   struct <dataful variant name> {
1744                 //     <fields in dataful variant>
1745                 //   } dataful_variant;
1746                 //   enum Discriminant$ {
1747                 //     <non-dataful variants>
1748                 //   } discriminant;
1749                 // }
1750                 // ```
1751                 // The natvis in `intrinsic.natvis` matches on the type name `enum$<*, *, *, *>`
1752                 // and evaluates `this.discriminant`. If the value is between the min niche and max
1753                 // niche, then the enum is in the dataful variant and `this.dataful_variant` is
1754                 // rendered. Otherwise, the enum is in one of the non-dataful variants. In that
1755                 // case, we just need to render the name of the `this.discriminant` enum.
1756                 if fallback {
1757                     let dataful_variant_layout = self.layout.for_variant(cx, dataful_variant);
1758
1759                     let mut discr_enum_ty = tag.value.to_ty(cx.tcx);
1760                     // If the niche is the NULL value of a reference, then `discr_enum_ty` will be a RawPtr.
1761                     // CodeView doesn't know what to do with enums whose base type is a pointer so we fix this up
1762                     // to just be `usize`.
1763                     if let ty::RawPtr(_) = discr_enum_ty.kind() {
1764                         discr_enum_ty = cx.tcx.types.usize;
1765                     }
1766
1767                     let tags: Vec<_> = variants
1768                         .iter_enumerated()
1769                         .filter_map(|(variant_idx, _)| {
1770                             calculate_niche_value(variant_idx).map(|tag| {
1771                                 let variant = variant_info_for(variant_idx);
1772                                 let name = variant.variant_name();
1773
1774                                 Some(unsafe {
1775                                     llvm::LLVMRustDIBuilderCreateEnumerator(
1776                                         DIB(cx),
1777                                         name.as_ptr().cast(),
1778                                         name.len(),
1779                                         tag as i64,
1780                                         !discr_enum_ty.is_signed(),
1781                                     )
1782                                 })
1783                             })
1784                         })
1785                         .collect();
1786
1787                     let discr_enum = unsafe {
1788                         llvm::LLVMRustDIBuilderCreateEnumerationType(
1789                             DIB(cx),
1790                             self_metadata,
1791                             "Discriminant$".as_ptr().cast(),
1792                             "Discriminant$".len(),
1793                             unknown_file_metadata(cx),
1794                             UNKNOWN_LINE_NUMBER,
1795                             tag.value.size(cx).bits(),
1796                             tag.value.align(cx).abi.bits() as u32,
1797                             create_DIArray(DIB(cx), &tags),
1798                             type_metadata(cx, discr_enum_ty, self.span),
1799                             true,
1800                         )
1801                     };
1802
1803                     let variant_info = variant_info_for(dataful_variant);
1804                     let (variant_type_metadata, member_desc_factory) = describe_enum_variant(
1805                         cx,
1806                         dataful_variant_layout,
1807                         variant_info,
1808                         self_metadata,
1809                         self.span,
1810                     );
1811
1812                     let member_descriptions = member_desc_factory.create_member_descriptions(cx);
1813
1814                     set_members_of_composite_type(
1815                         cx,
1816                         self.enum_type,
1817                         variant_type_metadata,
1818                         member_descriptions,
1819                         Some(&self.common_members),
1820                     );
1821
1822                     let (size, align) =
1823                         cx.size_and_align_of(dataful_variant_layout.field(cx, tag_field).ty);
1824
1825                     vec![
1826                         MemberDescription {
1827                             // Name the dataful variant so that we can identify it for natvis
1828                             name: "dataful_variant".to_string(),
1829                             type_metadata: variant_type_metadata,
1830                             offset: Size::ZERO,
1831                             size: self.layout.size,
1832                             align: self.layout.align.abi,
1833                             flags: DIFlags::FlagZero,
1834                             discriminant: None,
1835                             source_info: variant_info.source_info(cx),
1836                         },
1837                         MemberDescription {
1838                             name: "discriminant".into(),
1839                             type_metadata: discr_enum,
1840                             offset: dataful_variant_layout.fields.offset(tag_field),
1841                             size,
1842                             align,
1843                             flags: DIFlags::FlagZero,
1844                             discriminant: None,
1845                             source_info: None,
1846                         },
1847                     ]
1848                 } else {
1849                     variants
1850                         .iter_enumerated()
1851                         .map(|(i, _)| {
1852                             let variant = self.layout.for_variant(cx, i);
1853                             let variant_info = variant_info_for(i);
1854                             let (variant_type_metadata, member_desc_factory) =
1855                                 describe_enum_variant(
1856                                     cx,
1857                                     variant,
1858                                     variant_info,
1859                                     self_metadata,
1860                                     self.span,
1861                                 );
1862
1863                             let member_descriptions =
1864                                 member_desc_factory.create_member_descriptions(cx);
1865
1866                             set_members_of_composite_type(
1867                                 cx,
1868                                 self.enum_type,
1869                                 variant_type_metadata,
1870                                 member_descriptions,
1871                                 Some(&self.common_members),
1872                             );
1873
1874                             let niche_value = calculate_niche_value(i);
1875
1876                             MemberDescription {
1877                                 name: variant_info.variant_name(),
1878                                 type_metadata: variant_type_metadata,
1879                                 offset: Size::ZERO,
1880                                 size: self.layout.size,
1881                                 align: self.layout.align.abi,
1882                                 flags: DIFlags::FlagZero,
1883                                 discriminant: niche_value,
1884                                 source_info: variant_info.source_info(cx),
1885                             }
1886                         })
1887                         .collect()
1888                 }
1889             }
1890         }
1891     }
1892 }
1893
1894 // Creates `MemberDescription`s for the fields of a single enum variant.
1895 struct VariantMemberDescriptionFactory<'tcx> {
1896     /// Cloned from the `layout::Struct` describing the variant.
1897     offsets: Vec<Size>,
1898     args: Vec<(String, Ty<'tcx>)>,
1899     span: Span,
1900 }
1901
1902 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
1903     fn create_member_descriptions<'ll>(
1904         &self,
1905         cx: &CodegenCx<'ll, 'tcx>,
1906     ) -> Vec<MemberDescription<'ll>> {
1907         self.args
1908             .iter()
1909             .enumerate()
1910             .map(|(i, &(ref name, ty))| {
1911                 let (size, align) = cx.size_and_align_of(ty);
1912                 MemberDescription {
1913                     name: name.to_string(),
1914                     type_metadata: type_metadata(cx, ty, self.span),
1915                     offset: self.offsets[i],
1916                     size,
1917                     align,
1918                     flags: DIFlags::FlagZero,
1919                     discriminant: None,
1920                     source_info: None,
1921                 }
1922             })
1923             .collect()
1924     }
1925 }
1926
1927 #[derive(Copy, Clone)]
1928 enum VariantInfo<'a, 'tcx> {
1929     Adt(&'tcx ty::VariantDef),
1930     Generator {
1931         def_id: DefId,
1932         generator_layout: &'tcx GeneratorLayout<'tcx>,
1933         generator_saved_local_names: &'a IndexVec<mir::GeneratorSavedLocal, Option<Symbol>>,
1934         variant_index: VariantIdx,
1935     },
1936 }
1937
1938 impl<'tcx> VariantInfo<'_, 'tcx> {
1939     fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R {
1940         match self {
1941             VariantInfo::Adt(variant) => f(&variant.ident.as_str()),
1942             VariantInfo::Generator { variant_index, .. } => {
1943                 f(&GeneratorSubsts::variant_name(*variant_index))
1944             }
1945         }
1946     }
1947
1948     fn variant_name(&self) -> String {
1949         match self {
1950             VariantInfo::Adt(variant) => variant.ident.to_string(),
1951             VariantInfo::Generator { variant_index, .. } => {
1952                 // Since GDB currently prints out the raw discriminant along
1953                 // with every variant, make each variant name be just the value
1954                 // of the discriminant. The struct name for the variant includes
1955                 // the actual variant description.
1956                 format!("{}", variant_index.as_usize())
1957             }
1958         }
1959     }
1960
1961     fn field_name(&self, i: usize) -> String {
1962         let field_name = match *self {
1963             VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => {
1964                 Some(variant.fields[i].ident.name)
1965             }
1966             VariantInfo::Generator {
1967                 generator_layout,
1968                 generator_saved_local_names,
1969                 variant_index,
1970                 ..
1971             } => {
1972                 generator_saved_local_names
1973                     [generator_layout.variant_fields[variant_index][i.into()]]
1974             }
1975             _ => None,
1976         };
1977         field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i))
1978     }
1979
1980     fn source_info<'ll>(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option<SourceInfo<'ll>> {
1981         if let VariantInfo::Generator { def_id, variant_index, .. } = self {
1982             let span =
1983                 cx.tcx.generator_layout(*def_id).unwrap().variant_source_info[*variant_index].span;
1984             if !span.is_dummy() {
1985                 let loc = cx.lookup_debug_loc(span.lo());
1986                 return Some(SourceInfo { file: file_metadata(cx, &loc.file), line: loc.line });
1987             }
1988         }
1989         None
1990     }
1991 }
1992
1993 /// Returns a tuple of (1) `type_metadata_stub` of the variant, (2) a
1994 /// `MemberDescriptionFactory` for producing the descriptions of the
1995 /// fields of the variant. This is a rudimentary version of a full
1996 /// `RecursiveTypeDescription`.
1997 fn describe_enum_variant<'ll, 'tcx>(
1998     cx: &CodegenCx<'ll, 'tcx>,
1999     layout: layout::TyAndLayout<'tcx>,
2000     variant: VariantInfo<'_, 'tcx>,
2001     containing_scope: &'ll DIScope,
2002     span: Span,
2003 ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) {
2004     let metadata_stub = variant.map_struct_name(|variant_name| {
2005         let unique_type_id = debug_context(cx)
2006             .type_map
2007             .borrow_mut()
2008             .get_unique_type_id_of_enum_variant(cx, layout.ty, variant_name);
2009         create_struct_stub(
2010             cx,
2011             layout.ty,
2012             variant_name,
2013             unique_type_id,
2014             Some(containing_scope),
2015             DIFlags::FlagZero,
2016         )
2017     });
2018
2019     let offsets = (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect();
2020     let args = (0..layout.fields.count())
2021         .map(|i| (variant.field_name(i), layout.field(cx, i).ty))
2022         .collect();
2023
2024     let member_description_factory =
2025         VariantMDF(VariantMemberDescriptionFactory { offsets, args, span });
2026
2027     (metadata_stub, member_description_factory)
2028 }
2029
2030 fn prepare_enum_metadata<'ll, 'tcx>(
2031     cx: &CodegenCx<'ll, 'tcx>,
2032     enum_type: Ty<'tcx>,
2033     enum_def_id: DefId,
2034     unique_type_id: UniqueTypeId,
2035     span: Span,
2036     outer_field_tys: Vec<Ty<'tcx>>,
2037 ) -> RecursiveTypeDescription<'ll, 'tcx> {
2038     let tcx = cx.tcx;
2039     let enum_name = compute_debuginfo_type_name(tcx, enum_type, false);
2040
2041     let containing_scope = get_namespace_for_item(cx, enum_def_id);
2042     // FIXME: This should emit actual file metadata for the enum, but we
2043     // currently can't get the necessary information when it comes to types
2044     // imported from other crates. Formerly we violated the ODR when performing
2045     // LTO because we emitted debuginfo for the same type with varying file
2046     // metadata, so as a workaround we pretend that the type comes from
2047     // <unknown>
2048     let file_metadata = unknown_file_metadata(cx);
2049
2050     let discriminant_type_metadata = |discr: Primitive| {
2051         let enumerators_metadata: Vec<_> = match enum_type.kind() {
2052             ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants)
2053                 .map(|((_, discr), v)| {
2054                     let name = v.ident.as_str();
2055                     let is_unsigned = match discr.ty.kind() {
2056                         ty::Int(_) => false,
2057                         ty::Uint(_) => true,
2058                         _ => bug!("non integer discriminant"),
2059                     };
2060                     unsafe {
2061                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2062                             DIB(cx),
2063                             name.as_ptr().cast(),
2064                             name.len(),
2065                             // FIXME: what if enumeration has i128 discriminant?
2066                             discr.val as i64,
2067                             is_unsigned,
2068                         ))
2069                     }
2070                 })
2071                 .collect(),
2072             ty::Generator(_, substs, _) => substs
2073                 .as_generator()
2074                 .variant_range(enum_def_id, tcx)
2075                 .map(|variant_index| {
2076                     debug_assert_eq!(tcx.types.u32, substs.as_generator().discr_ty(tcx));
2077                     let name = GeneratorSubsts::variant_name(variant_index);
2078                     unsafe {
2079                         Some(llvm::LLVMRustDIBuilderCreateEnumerator(
2080                             DIB(cx),
2081                             name.as_ptr().cast(),
2082                             name.len(),
2083                             // Generators use u32 as discriminant type, verified above.
2084                             variant_index.as_u32().into(),
2085                             true, // IsUnsigned
2086                         ))
2087                     }
2088                 })
2089                 .collect(),
2090             _ => bug!(),
2091         };
2092
2093         let disr_type_key = (enum_def_id, discr);
2094         let cached_discriminant_type_metadata =
2095             debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned();
2096         match cached_discriminant_type_metadata {
2097             Some(discriminant_type_metadata) => discriminant_type_metadata,
2098             None => {
2099                 let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx));
2100                 let discriminant_base_type_metadata =
2101                     type_metadata(cx, discr.to_ty(tcx), rustc_span::DUMMY_SP);
2102
2103                 let item_name;
2104                 let discriminant_name = match enum_type.kind() {
2105                     ty::Adt(..) => {
2106                         item_name = tcx.item_name(enum_def_id).as_str();
2107                         &*item_name
2108                     }
2109                     ty::Generator(..) => enum_name.as_str(),
2110                     _ => bug!(),
2111                 };
2112
2113                 let discriminant_type_metadata = unsafe {
2114                     llvm::LLVMRustDIBuilderCreateEnumerationType(
2115                         DIB(cx),
2116                         containing_scope,
2117                         discriminant_name.as_ptr().cast(),
2118                         discriminant_name.len(),
2119                         file_metadata,
2120                         UNKNOWN_LINE_NUMBER,
2121                         discriminant_size.bits(),
2122                         discriminant_align.abi.bits() as u32,
2123                         create_DIArray(DIB(cx), &enumerators_metadata),
2124                         discriminant_base_type_metadata,
2125                         true,
2126                     )
2127                 };
2128
2129                 debug_context(cx)
2130                     .created_enum_disr_types
2131                     .borrow_mut()
2132                     .insert(disr_type_key, discriminant_type_metadata);
2133
2134                 discriminant_type_metadata
2135             }
2136         }
2137     };
2138
2139     let layout = cx.layout_of(enum_type);
2140
2141     if let (Abi::Scalar(_), Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. }) =
2142         (layout.abi, &layout.variants)
2143     {
2144         return FinalMetadata(discriminant_type_metadata(tag.value));
2145     }
2146
2147     if use_enum_fallback(cx) {
2148         let discriminant_type_metadata = match layout.variants {
2149             Variants::Single { .. } => None,
2150             Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, .. }
2151             | Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, .. } => {
2152                 Some(discriminant_type_metadata(tag.value))
2153             }
2154         };
2155
2156         let enum_metadata = {
2157             let type_map = debug_context(cx).type_map.borrow();
2158             let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2159
2160             unsafe {
2161                 llvm::LLVMRustDIBuilderCreateUnionType(
2162                     DIB(cx),
2163                     None,
2164                     enum_name.as_ptr().cast(),
2165                     enum_name.len(),
2166                     file_metadata,
2167                     UNKNOWN_LINE_NUMBER,
2168                     layout.size.bits(),
2169                     layout.align.abi.bits() as u32,
2170                     DIFlags::FlagZero,
2171                     None,
2172                     0, // RuntimeLang
2173                     unique_type_id_str.as_ptr().cast(),
2174                     unique_type_id_str.len(),
2175                 )
2176             }
2177         };
2178
2179         return create_and_register_recursive_type_forward_declaration(
2180             cx,
2181             enum_type,
2182             unique_type_id,
2183             enum_metadata,
2184             enum_metadata,
2185             EnumMDF(EnumMemberDescriptionFactory {
2186                 enum_type,
2187                 layout,
2188                 tag_type_metadata: discriminant_type_metadata,
2189                 common_members: vec![],
2190                 span,
2191             }),
2192         );
2193     }
2194
2195     let discriminator_name = match enum_type.kind() {
2196         ty::Generator(..) => "__state",
2197         _ => "",
2198     };
2199     let discriminator_metadata = match layout.variants {
2200         // A single-variant enum has no discriminant.
2201         Variants::Single { .. } => None,
2202
2203         Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, tag, tag_field, .. } => {
2204             // Find the integer type of the correct size.
2205             let size = tag.value.size(cx);
2206             let align = tag.value.align(cx);
2207
2208             let tag_type = match tag.value {
2209                 Int(t, _) => t,
2210                 F32 => Integer::I32,
2211                 F64 => Integer::I64,
2212                 Pointer => cx.data_layout().ptr_sized_integer(),
2213             }
2214             .to_ty(cx.tcx, false);
2215
2216             let tag_metadata = basic_type_metadata(cx, tag_type);
2217             unsafe {
2218                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2219                     DIB(cx),
2220                     containing_scope,
2221                     discriminator_name.as_ptr().cast(),
2222                     discriminator_name.len(),
2223                     file_metadata,
2224                     UNKNOWN_LINE_NUMBER,
2225                     size.bits(),
2226                     align.abi.bits() as u32,
2227                     layout.fields.offset(tag_field).bits(),
2228                     DIFlags::FlagArtificial,
2229                     tag_metadata,
2230                 ))
2231             }
2232         }
2233
2234         Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, tag_field, .. } => {
2235             let discr_type = tag.value.to_ty(cx.tcx);
2236             let (size, align) = cx.size_and_align_of(discr_type);
2237
2238             let discr_metadata = basic_type_metadata(cx, discr_type);
2239             unsafe {
2240                 Some(llvm::LLVMRustDIBuilderCreateMemberType(
2241                     DIB(cx),
2242                     containing_scope,
2243                     discriminator_name.as_ptr().cast(),
2244                     discriminator_name.len(),
2245                     file_metadata,
2246                     UNKNOWN_LINE_NUMBER,
2247                     size.bits(),
2248                     align.bits() as u32,
2249                     layout.fields.offset(tag_field).bits(),
2250                     DIFlags::FlagArtificial,
2251                     discr_metadata,
2252                 ))
2253             }
2254         }
2255     };
2256
2257     let outer_fields = match layout.variants {
2258         Variants::Single { .. } => vec![],
2259         Variants::Multiple { .. } => {
2260             let tuple_mdf = TupleMemberDescriptionFactory {
2261                 ty: enum_type,
2262                 component_types: outer_field_tys,
2263                 span,
2264             };
2265             tuple_mdf
2266                 .create_member_descriptions(cx)
2267                 .into_iter()
2268                 .map(|desc| Some(desc.into_metadata(cx, containing_scope)))
2269                 .collect()
2270         }
2271     };
2272
2273     let variant_part_unique_type_id_str = debug_context(cx)
2274         .type_map
2275         .borrow_mut()
2276         .get_unique_type_id_str_of_enum_variant_part(unique_type_id);
2277     let empty_array = create_DIArray(DIB(cx), &[]);
2278     let name = "";
2279     let variant_part = unsafe {
2280         llvm::LLVMRustDIBuilderCreateVariantPart(
2281             DIB(cx),
2282             containing_scope,
2283             name.as_ptr().cast(),
2284             name.len(),
2285             file_metadata,
2286             UNKNOWN_LINE_NUMBER,
2287             layout.size.bits(),
2288             layout.align.abi.bits() as u32,
2289             DIFlags::FlagZero,
2290             discriminator_metadata,
2291             empty_array,
2292             variant_part_unique_type_id_str.as_ptr().cast(),
2293             variant_part_unique_type_id_str.len(),
2294         )
2295     };
2296
2297     let struct_wrapper = {
2298         // The variant part must be wrapped in a struct according to DWARF.
2299         // All fields except the discriminant (including `outer_fields`)
2300         // should be put into structures inside the variant part, which gives
2301         // an equivalent layout but offers us much better integration with
2302         // debuggers.
2303         let type_array = create_DIArray(DIB(cx), &[Some(variant_part)]);
2304
2305         let type_map = debug_context(cx).type_map.borrow();
2306         let unique_type_id_str = type_map.get_unique_type_id_as_string(unique_type_id);
2307
2308         unsafe {
2309             llvm::LLVMRustDIBuilderCreateStructType(
2310                 DIB(cx),
2311                 Some(containing_scope),
2312                 enum_name.as_ptr().cast(),
2313                 enum_name.len(),
2314                 file_metadata,
2315                 UNKNOWN_LINE_NUMBER,
2316                 layout.size.bits(),
2317                 layout.align.abi.bits() as u32,
2318                 DIFlags::FlagZero,
2319                 None,
2320                 type_array,
2321                 0,
2322                 None,
2323                 unique_type_id_str.as_ptr().cast(),
2324                 unique_type_id_str.len(),
2325             )
2326         }
2327     };
2328
2329     create_and_register_recursive_type_forward_declaration(
2330         cx,
2331         enum_type,
2332         unique_type_id,
2333         struct_wrapper,
2334         variant_part,
2335         EnumMDF(EnumMemberDescriptionFactory {
2336             enum_type,
2337             layout,
2338             tag_type_metadata: None,
2339             common_members: outer_fields,
2340             span,
2341         }),
2342     )
2343 }
2344
2345 /// Creates debug information for a composite type, that is, anything that
2346 /// results in a LLVM struct.
2347 ///
2348 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2349 fn composite_type_metadata<'ll, 'tcx>(
2350     cx: &CodegenCx<'ll, 'tcx>,
2351     composite_type: Ty<'tcx>,
2352     composite_type_name: &str,
2353     composite_type_unique_id: UniqueTypeId,
2354     member_descriptions: Vec<MemberDescription<'ll>>,
2355     containing_scope: Option<&'ll DIScope>,
2356
2357     // Ignore source location information as long as it
2358     // can't be reconstructed for non-local crates.
2359     _file_metadata: &'ll DIFile,
2360     _definition_span: Span,
2361 ) -> &'ll DICompositeType {
2362     // Create the (empty) struct metadata node ...
2363     let composite_type_metadata = create_struct_stub(
2364         cx,
2365         composite_type,
2366         composite_type_name,
2367         composite_type_unique_id,
2368         containing_scope,
2369         DIFlags::FlagZero,
2370     );
2371     // ... and immediately create and add the member descriptions.
2372     set_members_of_composite_type(
2373         cx,
2374         composite_type,
2375         composite_type_metadata,
2376         member_descriptions,
2377         None,
2378     );
2379
2380     composite_type_metadata
2381 }
2382
2383 fn set_members_of_composite_type<'ll, 'tcx>(
2384     cx: &CodegenCx<'ll, 'tcx>,
2385     composite_type: Ty<'tcx>,
2386     composite_type_metadata: &'ll DICompositeType,
2387     member_descriptions: Vec<MemberDescription<'ll>>,
2388     common_members: Option<&Vec<Option<&'ll DIType>>>,
2389 ) {
2390     // In some rare cases LLVM metadata uniquing would lead to an existing type
2391     // description being used instead of a new one created in
2392     // create_struct_stub. This would cause a hard to trace assertion in
2393     // DICompositeType::SetTypeArray(). The following check makes sure that we
2394     // get a better error message if this should happen again due to some
2395     // regression.
2396     {
2397         let mut composite_types_completed =
2398             debug_context(cx).composite_types_completed.borrow_mut();
2399         if !composite_types_completed.insert(composite_type_metadata) {
2400             bug!(
2401                 "debuginfo::set_members_of_composite_type() - \
2402                   Already completed forward declaration re-encountered."
2403             );
2404         }
2405     }
2406
2407     let mut member_metadata: Vec<_> = member_descriptions
2408         .into_iter()
2409         .map(|desc| Some(desc.into_metadata(cx, composite_type_metadata)))
2410         .collect();
2411     if let Some(other_members) = common_members {
2412         member_metadata.extend(other_members.iter());
2413     }
2414
2415     let type_params = compute_type_parameters(cx, composite_type);
2416     unsafe {
2417         let type_array = create_DIArray(DIB(cx), &member_metadata);
2418         llvm::LLVMRustDICompositeTypeReplaceArrays(
2419             DIB(cx),
2420             composite_type_metadata,
2421             Some(type_array),
2422             Some(type_params),
2423         );
2424     }
2425 }
2426
2427 /// Computes the type parameters for a type, if any, for the given metadata.
2428 fn compute_type_parameters<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> &'ll DIArray {
2429     if let ty::Adt(def, substs) = *ty.kind() {
2430         if substs.types().next().is_some() {
2431             let generics = cx.tcx.generics_of(def.did);
2432             let names = get_parameter_names(cx, generics);
2433             let template_params: Vec<_> = iter::zip(substs, names)
2434                 .filter_map(|(kind, name)| {
2435                     if let GenericArgKind::Type(ty) = kind.unpack() {
2436                         let actual_type =
2437                             cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty);
2438                         let actual_type_metadata =
2439                             type_metadata(cx, actual_type, rustc_span::DUMMY_SP);
2440                         let name = &name.as_str();
2441                         Some(unsafe {
2442                             Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
2443                                 DIB(cx),
2444                                 None,
2445                                 name.as_ptr().cast(),
2446                                 name.len(),
2447                                 actual_type_metadata,
2448                             ))
2449                         })
2450                     } else {
2451                         None
2452                     }
2453                 })
2454                 .collect();
2455
2456             return create_DIArray(DIB(cx), &template_params);
2457         }
2458     }
2459     return create_DIArray(DIB(cx), &[]);
2460
2461     fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec<Symbol> {
2462         let mut names = generics
2463             .parent
2464             .map_or_else(Vec::new, |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id)));
2465         names.extend(generics.params.iter().map(|param| param.name));
2466         names
2467     }
2468 }
2469
2470 /// A convenience wrapper around `LLVMRustDIBuilderCreateStructType()`. Does not do
2471 /// any caching, does not add any fields to the struct. This can be done later
2472 /// with `set_members_of_composite_type()`.
2473 fn create_struct_stub<'ll, 'tcx>(
2474     cx: &CodegenCx<'ll, 'tcx>,
2475     struct_type: Ty<'tcx>,
2476     struct_type_name: &str,
2477     unique_type_id: UniqueTypeId,
2478     containing_scope: Option<&'ll DIScope>,
2479     flags: DIFlags,
2480 ) -> &'ll DICompositeType {
2481     let (struct_size, struct_align) = cx.size_and_align_of(struct_type);
2482
2483     let type_map = debug_context(cx).type_map.borrow();
2484     let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2485
2486     let metadata_stub = unsafe {
2487         // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null
2488         // pointer will lead to hard to trace and debug LLVM assertions
2489         // later on in `llvm/lib/IR/Value.cpp`.
2490         let empty_array = create_DIArray(DIB(cx), &[]);
2491
2492         llvm::LLVMRustDIBuilderCreateStructType(
2493             DIB(cx),
2494             containing_scope,
2495             struct_type_name.as_ptr().cast(),
2496             struct_type_name.len(),
2497             unknown_file_metadata(cx),
2498             UNKNOWN_LINE_NUMBER,
2499             struct_size.bits(),
2500             struct_align.bits() as u32,
2501             flags,
2502             None,
2503             empty_array,
2504             0,
2505             None,
2506             unique_type_id.as_ptr().cast(),
2507             unique_type_id.len(),
2508         )
2509     };
2510
2511     metadata_stub
2512 }
2513
2514 fn create_union_stub<'ll, 'tcx>(
2515     cx: &CodegenCx<'ll, 'tcx>,
2516     union_type: Ty<'tcx>,
2517     union_type_name: &str,
2518     unique_type_id: UniqueTypeId,
2519     containing_scope: &'ll DIScope,
2520 ) -> &'ll DICompositeType {
2521     let (union_size, union_align) = cx.size_and_align_of(union_type);
2522
2523     let type_map = debug_context(cx).type_map.borrow();
2524     let unique_type_id = type_map.get_unique_type_id_as_string(unique_type_id);
2525
2526     let metadata_stub = unsafe {
2527         // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null
2528         // pointer will lead to hard to trace and debug LLVM assertions
2529         // later on in `llvm/lib/IR/Value.cpp`.
2530         let empty_array = create_DIArray(DIB(cx), &[]);
2531
2532         llvm::LLVMRustDIBuilderCreateUnionType(
2533             DIB(cx),
2534             Some(containing_scope),
2535             union_type_name.as_ptr().cast(),
2536             union_type_name.len(),
2537             unknown_file_metadata(cx),
2538             UNKNOWN_LINE_NUMBER,
2539             union_size.bits(),
2540             union_align.bits() as u32,
2541             DIFlags::FlagZero,
2542             Some(empty_array),
2543             0, // RuntimeLang
2544             unique_type_id.as_ptr().cast(),
2545             unique_type_id.len(),
2546         )
2547     };
2548
2549     metadata_stub
2550 }
2551
2552 /// Creates debug information for the given global variable.
2553 ///
2554 /// Adds the created metadata nodes directly to the crate's IR.
2555 pub fn create_global_var_metadata<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) {
2556     if cx.dbg_cx.is_none() {
2557         return;
2558     }
2559
2560     // Only create type information if full debuginfo is enabled
2561     if cx.sess().opts.debuginfo != DebugInfo::Full {
2562         return;
2563     }
2564
2565     let tcx = cx.tcx;
2566
2567     // We may want to remove the namespace scope if we're in an extern block (see
2568     // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952).
2569     let var_scope = get_namespace_for_item(cx, def_id);
2570     let span = tcx.def_span(def_id);
2571
2572     let (file_metadata, line_number) = if !span.is_dummy() {
2573         let loc = cx.lookup_debug_loc(span.lo());
2574         (file_metadata(cx, &loc.file), loc.line)
2575     } else {
2576         (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)
2577     };
2578
2579     let is_local_to_unit = is_node_local_to_unit(cx, def_id);
2580     let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
2581     let type_metadata = type_metadata(cx, variable_type, span);
2582     let var_name = tcx.item_name(def_id).as_str();
2583     let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
2584     // When empty, linkage_name field is omitted,
2585     // which is what we want for no_mangle statics
2586     let linkage_name = if var_name == linkage_name { "" } else { linkage_name };
2587
2588     let global_align = cx.align_of(variable_type);
2589
2590     unsafe {
2591         llvm::LLVMRustDIBuilderCreateStaticVariable(
2592             DIB(cx),
2593             Some(var_scope),
2594             var_name.as_ptr().cast(),
2595             var_name.len(),
2596             linkage_name.as_ptr().cast(),
2597             linkage_name.len(),
2598             file_metadata,
2599             line_number,
2600             type_metadata,
2601             is_local_to_unit,
2602             global,
2603             None,
2604             global_align.bytes() as u32,
2605         );
2606     }
2607 }
2608
2609 /// Generates LLVM debuginfo for a vtable.
2610 fn vtable_type_metadata<'ll, 'tcx>(
2611     cx: &CodegenCx<'ll, 'tcx>,
2612     ty: Ty<'tcx>,
2613     poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2614 ) -> &'ll DIType {
2615     let tcx = cx.tcx;
2616
2617     let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
2618         let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
2619         let trait_ref = tcx.erase_regions(trait_ref);
2620
2621         tcx.vtable_entries(trait_ref)
2622     } else {
2623         COMMON_VTABLE_ENTRIES
2624     };
2625
2626     // FIXME: We describe the vtable as an array of *const () pointers. The length of the array is
2627     //        correct - but we could create a more accurate description, e.g. by describing it
2628     //        as a struct where each field has a name that corresponds to the name of the method
2629     //        it points to.
2630     //        However, this is not entirely straightforward because there might be multiple
2631     //        methods with the same name if the vtable is for multiple traits. So for now we keep
2632     //        things simple instead of adding some ad-hoc disambiguation scheme.
2633     let vtable_type = tcx.mk_array(tcx.mk_imm_ptr(tcx.types.unit), vtable_entries.len() as u64);
2634
2635     type_metadata(cx, vtable_type, rustc_span::DUMMY_SP)
2636 }
2637
2638 /// Creates debug information for the given vtable, which is for the
2639 /// given type.
2640 ///
2641 /// Adds the created metadata nodes directly to the crate's IR.
2642 pub fn create_vtable_metadata<'ll, 'tcx>(
2643     cx: &CodegenCx<'ll, 'tcx>,
2644     ty: Ty<'tcx>,
2645     poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2646     vtable: &'ll Value,
2647 ) {
2648     if cx.dbg_cx.is_none() {
2649         return;
2650     }
2651
2652     // Only create type information if full debuginfo is enabled
2653     if cx.sess().opts.debuginfo != DebugInfo::Full {
2654         return;
2655     }
2656
2657     let vtable_name = compute_debuginfo_vtable_name(cx.tcx, ty, poly_trait_ref);
2658     let vtable_type = vtable_type_metadata(cx, ty, poly_trait_ref);
2659
2660     unsafe {
2661         let linkage_name = "";
2662         llvm::LLVMRustDIBuilderCreateStaticVariable(
2663             DIB(cx),
2664             NO_SCOPE_METADATA,
2665             vtable_name.as_ptr().cast(),
2666             vtable_name.len(),
2667             linkage_name.as_ptr().cast(),
2668             linkage_name.len(),
2669             unknown_file_metadata(cx),
2670             UNKNOWN_LINE_NUMBER,
2671             vtable_type,
2672             true,
2673             vtable,
2674             None,
2675             0,
2676         );
2677     }
2678 }
2679
2680 /// Creates an "extension" of an existing `DIScope` into another file.
2681 pub fn extend_scope_to_file<'ll>(
2682     cx: &CodegenCx<'ll, '_>,
2683     scope_metadata: &'ll DIScope,
2684     file: &SourceFile,
2685 ) -> &'ll DILexicalBlock {
2686     let file_metadata = file_metadata(cx, file);
2687     unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) }
2688 }