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