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