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