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