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