1 //! Defines `Module` and related types.
2 
3 // TODO: Should `ir::Function` really have a `name`?
4 
5 // TODO: Factor out `ir::Function`'s `ext_funcs` and `global_values` into a struct
6 // shared with `DataDescription`?
7 
8 use super::HashMap;
9 use crate::data_context::DataDescription;
10 use core::fmt::Display;
11 use cranelift_codegen::binemit::{CodeOffset, Reloc};
12 use cranelift_codegen::entity::{entity_impl, PrimaryMap};
13 use cranelift_codegen::ir::function::{Function, VersionMarker};
14 use cranelift_codegen::ir::ExternalName;
15 use cranelift_codegen::settings::SetError;
16 use cranelift_codegen::{
17     ir, isa, CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget,
18 };
19 use cranelift_control::ControlPlane;
20 use std::borrow::{Cow, ToOwned};
21 use std::string::String;
22 
23 /// A module relocation.
24 #[derive(Clone)]
25 pub struct ModuleReloc {
26     /// The offset at which the relocation applies, *relative to the
27     /// containing section*.
28     pub offset: CodeOffset,
29     /// The kind of relocation.
30     pub kind: Reloc,
31     /// The external symbol / name to which this relocation refers.
32     pub name: ModuleRelocTarget,
33     /// The addend to add to the symbol value.
34     pub addend: i64,
35 }
36 
37 impl ModuleReloc {
38     /// Converts a `FinalizedMachReloc` produced from a `Function` into a `ModuleReloc`.
39     pub fn from_mach_reloc(
40         mach_reloc: &FinalizedMachReloc,
41         func: &Function,
42         func_id: FuncId,
43     ) -> Self {
44         let name = match mach_reloc.target {
45             FinalizedRelocTarget::ExternalName(ExternalName::User(reff)) => {
46                 let name = &func.params.user_named_funcs()[reff];
47                 ModuleRelocTarget::user(name.namespace, name.index)
48             }
49             FinalizedRelocTarget::ExternalName(ExternalName::TestCase(_)) => unimplemented!(),
50             FinalizedRelocTarget::ExternalName(ExternalName::LibCall(libcall)) => {
51                 ModuleRelocTarget::LibCall(libcall)
52             }
53             FinalizedRelocTarget::ExternalName(ExternalName::KnownSymbol(ks)) => {
54                 ModuleRelocTarget::KnownSymbol(ks)
55             }
56             FinalizedRelocTarget::Func(offset) => {
57                 ModuleRelocTarget::FunctionOffset(func_id, offset)
58             }
59         };
60         Self {
61             offset: mach_reloc.offset,
62             kind: mach_reloc.kind,
63             name,
64             addend: mach_reloc.addend,
65         }
66     }
67 }
68 
69 /// A function identifier for use in the `Module` interface.
70 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
71 #[cfg_attr(
72     feature = "enable-serde",
73     derive(serde_derive::Serialize, serde_derive::Deserialize)
74 )]
75 pub struct FuncId(u32);
76 entity_impl!(FuncId, "funcid");
77 
78 /// Function identifiers are namespace 0 in `ir::ExternalName`
79 impl From<FuncId> for ModuleRelocTarget {
80     fn from(id: FuncId) -> Self {
81         Self::User {
82             namespace: 0,
83             index: id.0,
84         }
85     }
86 }
87 
88 impl FuncId {
89     /// Get the `FuncId` for the function named by `name`.
90     pub fn from_name(name: &ModuleRelocTarget) -> FuncId {
91         if let ModuleRelocTarget::User { namespace, index } = name {
92             debug_assert_eq!(*namespace, 0);
93             FuncId::from_u32(*index)
94         } else {
95             panic!("unexpected name in DataId::from_name")
96         }
97     }
98 }
99 
100 /// A data object identifier for use in the `Module` interface.
101 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102 #[cfg_attr(
103     feature = "enable-serde",
104     derive(serde_derive::Serialize, serde_derive::Deserialize)
105 )]
106 pub struct DataId(u32);
107 entity_impl!(DataId, "dataid");
108 
109 /// Data identifiers are namespace 1 in `ir::ExternalName`
110 impl From<DataId> for ModuleRelocTarget {
111     fn from(id: DataId) -> Self {
112         Self::User {
113             namespace: 1,
114             index: id.0,
115         }
116     }
117 }
118 
119 impl DataId {
120     /// Get the `DataId` for the data object named by `name`.
121     pub fn from_name(name: &ModuleRelocTarget) -> DataId {
122         if let ModuleRelocTarget::User { namespace, index } = name {
123             debug_assert_eq!(*namespace, 1);
124             DataId::from_u32(*index)
125         } else {
126             panic!("unexpected name in DataId::from_name")
127         }
128     }
129 }
130 
131 /// Linkage refers to where an entity is defined and who can see it.
132 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
133 #[cfg_attr(
134     feature = "enable-serde",
135     derive(serde_derive::Serialize, serde_derive::Deserialize)
136 )]
137 pub enum Linkage {
138     /// Defined outside of a module.
139     Import,
140     /// Defined inside the module, but not visible outside it.
141     Local,
142     /// Defined inside the module, visible outside it, and may be preempted.
143     Preemptible,
144     /// Defined inside the module, visible inside the current static linkage unit, but not outside.
145     ///
146     /// A static linkage unit is the combination of all object files passed to a linker to create
147     /// an executable or dynamic library.
148     Hidden,
149     /// Defined inside the module, and visible outside it.
150     Export,
151 }
152 
153 impl Linkage {
154     fn merge(a: Self, b: Self) -> Self {
155         match a {
156             Self::Export => Self::Export,
157             Self::Hidden => match b {
158                 Self::Export => Self::Export,
159                 Self::Preemptible => Self::Preemptible,
160                 _ => Self::Hidden,
161             },
162             Self::Preemptible => match b {
163                 Self::Export => Self::Export,
164                 _ => Self::Preemptible,
165             },
166             Self::Local => match b {
167                 Self::Export => Self::Export,
168                 Self::Hidden => Self::Hidden,
169                 Self::Preemptible => Self::Preemptible,
170                 Self::Local | Self::Import => Self::Local,
171             },
172             Self::Import => b,
173         }
174     }
175 
176     /// Test whether this linkage can have a definition.
177     pub fn is_definable(self) -> bool {
178         match self {
179             Self::Import => false,
180             Self::Local | Self::Preemptible | Self::Hidden | Self::Export => true,
181         }
182     }
183 
184     /// Test whether this linkage will have a definition that cannot be preempted.
185     pub fn is_final(self) -> bool {
186         match self {
187             Self::Import | Self::Preemptible => false,
188             Self::Local | Self::Hidden | Self::Export => true,
189         }
190     }
191 }
192 
193 /// A declared name may refer to either a function or data declaration
194 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
195 #[cfg_attr(
196     feature = "enable-serde",
197     derive(serde_derive::Serialize, serde_derive::Deserialize)
198 )]
199 pub enum FuncOrDataId {
200     /// When it's a FuncId
201     Func(FuncId),
202     /// When it's a DataId
203     Data(DataId),
204 }
205 
206 /// Mapping to `ModuleExtName` is trivial based on the `FuncId` and `DataId` mapping.
207 impl From<FuncOrDataId> for ModuleRelocTarget {
208     fn from(id: FuncOrDataId) -> Self {
209         match id {
210             FuncOrDataId::Func(funcid) => Self::from(funcid),
211             FuncOrDataId::Data(dataid) => Self::from(dataid),
212         }
213     }
214 }
215 
216 /// Information about a function which can be called.
217 #[derive(Debug)]
218 #[cfg_attr(
219     feature = "enable-serde",
220     derive(serde_derive::Serialize, serde_derive::Deserialize)
221 )]
222 pub struct FunctionDeclaration {
223     #[allow(missing_docs)]
224     pub name: Option<String>,
225     #[allow(missing_docs)]
226     pub linkage: Linkage,
227     #[allow(missing_docs)]
228     pub signature: ir::Signature,
229 }
230 
231 impl FunctionDeclaration {
232     /// The linkage name of the function.
233     ///
234     /// Synthesized from the given function id if it is an anonymous function.
235     pub fn linkage_name(&self, id: FuncId) -> Cow<'_, str> {
236         match &self.name {
237             Some(name) => Cow::Borrowed(name),
238             // Symbols starting with .L are completely omitted from the symbol table after linking.
239             // Using hexadecimal instead of decimal for slightly smaller symbol names and often
240             // slightly faster linking.
241             None => Cow::Owned(format!(".Lfn{:x}", id.as_u32())),
242         }
243     }
244 
245     fn merge(
246         &mut self,
247         id: FuncId,
248         linkage: Linkage,
249         sig: &ir::Signature,
250     ) -> Result<(), ModuleError> {
251         self.linkage = Linkage::merge(self.linkage, linkage);
252         if &self.signature != sig {
253             return Err(ModuleError::IncompatibleSignature(
254                 self.linkage_name(id).into_owned(),
255                 self.signature.clone(),
256                 sig.clone(),
257             ));
258         }
259         Ok(())
260     }
261 }
262 
263 /// Error messages for all `Module` methods
264 #[derive(Debug)]
265 pub enum ModuleError {
266     /// Indicates an identifier was used before it was declared
267     Undeclared(String),
268 
269     /// Indicates an identifier was used as data/function first, but then used as the other
270     IncompatibleDeclaration(String),
271 
272     /// Indicates a function identifier was declared with a
273     /// different signature than declared previously
274     IncompatibleSignature(String, ir::Signature, ir::Signature),
275 
276     /// Indicates an identifier was defined more than once
277     DuplicateDefinition(String),
278 
279     /// Indicates an identifier was defined, but was declared as an import
280     InvalidImportDefinition(String),
281 
282     /// Wraps a `cranelift-codegen` error
283     Compilation(CodegenError),
284 
285     /// Memory allocation failure from a backend
286     Allocation {
287         /// Tell where the allocation came from
288         message: &'static str,
289         /// Io error the allocation failed with
290         err: std::io::Error,
291     },
292 
293     /// Wraps a generic error from a backend
294     Backend(anyhow::Error),
295 
296     /// Wraps an error from a flag definition.
297     Flag(SetError),
298 }
299 
300 impl<'a> From<CompileError<'a>> for ModuleError {
301     fn from(err: CompileError<'a>) -> Self {
302         Self::Compilation(err.inner)
303     }
304 }
305 
306 // This is manually implementing Error and Display instead of using thiserror to reduce the amount
307 // of dependencies used by Cranelift.
308 impl std::error::Error for ModuleError {
309     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
310         match self {
311             Self::Undeclared { .. }
312             | Self::IncompatibleDeclaration { .. }
313             | Self::IncompatibleSignature { .. }
314             | Self::DuplicateDefinition { .. }
315             | Self::InvalidImportDefinition { .. } => None,
316             Self::Compilation(source) => Some(source),
317             Self::Allocation { err: source, .. } => Some(source),
318             Self::Backend(source) => Some(&**source),
319             Self::Flag(source) => Some(source),
320         }
321     }
322 }
323 
324 impl std::fmt::Display for ModuleError {
325     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
326         match self {
327             Self::Undeclared(name) => {
328                 write!(f, "Undeclared identifier: {name}")
329             }
330             Self::IncompatibleDeclaration(name) => {
331                 write!(f, "Incompatible declaration of identifier: {name}",)
332             }
333             Self::IncompatibleSignature(name, prev_sig, new_sig) => {
334                 write!(
335                     f,
336                     "Function {name} signature {new_sig:?} is incompatible with previous declaration {prev_sig:?}",
337                 )
338             }
339             Self::DuplicateDefinition(name) => {
340                 write!(f, "Duplicate definition of identifier: {name}")
341             }
342             Self::InvalidImportDefinition(name) => {
343                 write!(
344                     f,
345                     "Invalid to define identifier declared as an import: {name}",
346                 )
347             }
348             Self::Compilation(err) => {
349                 write!(f, "Compilation error: {err}")
350             }
351             Self::Allocation { message, err } => {
352                 write!(f, "Allocation error: {message}: {err}")
353             }
354             Self::Backend(err) => write!(f, "Backend error: {err}"),
355             Self::Flag(err) => write!(f, "Flag error: {err}"),
356         }
357     }
358 }
359 
360 impl std::convert::From<CodegenError> for ModuleError {
361     fn from(source: CodegenError) -> Self {
362         Self::Compilation { 0: source }
363     }
364 }
365 
366 impl std::convert::From<SetError> for ModuleError {
367     fn from(source: SetError) -> Self {
368         Self::Flag { 0: source }
369     }
370 }
371 
372 /// A convenient alias for a `Result` that uses `ModuleError` as the error type.
373 pub type ModuleResult<T> = Result<T, ModuleError>;
374 
375 /// Information about a data object which can be accessed.
376 #[derive(Debug)]
377 #[cfg_attr(
378     feature = "enable-serde",
379     derive(serde_derive::Serialize, serde_derive::Deserialize)
380 )]
381 pub struct DataDeclaration {
382     #[allow(missing_docs)]
383     pub name: Option<String>,
384     #[allow(missing_docs)]
385     pub linkage: Linkage,
386     #[allow(missing_docs)]
387     pub writable: bool,
388     #[allow(missing_docs)]
389     pub tls: bool,
390 }
391 
392 impl DataDeclaration {
393     /// The linkage name of the data object.
394     ///
395     /// Synthesized from the given data id if it is an anonymous function.
396     pub fn linkage_name(&self, id: DataId) -> Cow<'_, str> {
397         match &self.name {
398             Some(name) => Cow::Borrowed(name),
399             // Symbols starting with .L are completely omitted from the symbol table after linking.
400             // Using hexadecimal instead of decimal for slightly smaller symbol names and often
401             // slightly faster linking.
402             None => Cow::Owned(format!(".Ldata{:x}", id.as_u32())),
403         }
404     }
405 
406     fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {
407         self.linkage = Linkage::merge(self.linkage, linkage);
408         self.writable = self.writable || writable;
409         assert_eq!(
410             self.tls, tls,
411             "Can't change TLS data object to normal or in the opposite way",
412         );
413     }
414 }
415 
416 /// A translated `ExternalName` into something global we can handle.
417 #[derive(Clone, Debug)]
418 #[cfg_attr(
419     feature = "enable-serde",
420     derive(serde_derive::Serialize, serde_derive::Deserialize)
421 )]
422 pub enum ModuleRelocTarget {
423     /// User defined function, converted from `ExternalName::User`.
424     User {
425         /// Arbitrary.
426         namespace: u32,
427         /// Arbitrary.
428         index: u32,
429     },
430     /// Call into a library function.
431     LibCall(ir::LibCall),
432     /// Symbols known to the linker.
433     KnownSymbol(ir::KnownSymbol),
434     /// A offset inside a function
435     FunctionOffset(FuncId, CodeOffset),
436 }
437 
438 impl ModuleRelocTarget {
439     /// Creates a user-defined external name.
440     pub fn user(namespace: u32, index: u32) -> Self {
441         Self::User { namespace, index }
442     }
443 }
444 
445 impl Display for ModuleRelocTarget {
446     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
447         match self {
448             Self::User { namespace, index } => write!(f, "u{namespace}:{index}"),
449             Self::LibCall(lc) => write!(f, "%{lc}"),
450             Self::KnownSymbol(ks) => write!(f, "{ks}"),
451             Self::FunctionOffset(fname, offset) => write!(f, "{fname}+{offset}"),
452         }
453     }
454 }
455 
456 /// This provides a view to the state of a module which allows `ir::ExternalName`s to be translated
457 /// into `FunctionDeclaration`s and `DataDeclaration`s.
458 #[derive(Debug, Default)]
459 pub struct ModuleDeclarations {
460     /// A version marker used to ensure that serialized clif ir is never deserialized with a
461     /// different version of Cranelift.
462     // Note: This must be the first field to ensure that Serde will deserialize it before
463     // attempting to deserialize other fields that are potentially changed between versions.
464     _version_marker: VersionMarker,
465 
466     names: HashMap<String, FuncOrDataId>,
467     functions: PrimaryMap<FuncId, FunctionDeclaration>,
468     data_objects: PrimaryMap<DataId, DataDeclaration>,
469 }
470 
471 #[cfg(feature = "enable-serde")]
472 mod serialize {
473     // This is manually implementing Serialize and Deserialize to avoid serializing the names field,
474     // which can be entirely reconstructed from the functions and data_objects fields, saving space.
475 
476     use super::*;
477 
478     use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Unexpected, Visitor};
479     use serde::ser::{Serialize, SerializeStruct, Serializer};
480     use std::fmt;
481 
482     fn get_names<E: Error>(
483         functions: &PrimaryMap<FuncId, FunctionDeclaration>,
484         data_objects: &PrimaryMap<DataId, DataDeclaration>,
485     ) -> Result<HashMap<String, FuncOrDataId>, E> {
486         let mut names = HashMap::new();
487         for (func_id, decl) in functions.iter() {
488             if let Some(name) = &decl.name {
489                 let old = names.insert(name.clone(), FuncOrDataId::Func(func_id));
490                 if old.is_some() {
491                     return Err(E::invalid_value(
492                         Unexpected::Other("duplicate name"),
493                         &"FunctionDeclaration's with no duplicate names",
494                     ));
495                 }
496             }
497         }
498         for (data_id, decl) in data_objects.iter() {
499             if let Some(name) = &decl.name {
500                 let old = names.insert(name.clone(), FuncOrDataId::Data(data_id));
501                 if old.is_some() {
502                     return Err(E::invalid_value(
503                         Unexpected::Other("duplicate name"),
504                         &"DataDeclaration's with no duplicate names",
505                     ));
506                 }
507             }
508         }
509         Ok(names)
510     }
511 
512     impl Serialize for ModuleDeclarations {
513         fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
514             let ModuleDeclarations {
515                 _version_marker,
516                 functions,
517                 data_objects,
518                 names: _,
519             } = self;
520 
521             let mut state = s.serialize_struct("ModuleDeclarations", 4)?;
522             state.serialize_field("_version_marker", _version_marker)?;
523             state.serialize_field("functions", functions)?;
524             state.serialize_field("data_objects", data_objects)?;
525             state.end()
526         }
527     }
528 
529     enum ModuleDeclarationsField {
530         VersionMarker,
531         Functions,
532         DataObjects,
533         Ignore,
534     }
535 
536     struct ModuleDeclarationsFieldVisitor;
537 
538     impl<'de> serde::de::Visitor<'de> for ModuleDeclarationsFieldVisitor {
539         type Value = ModuleDeclarationsField;
540 
541         fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
542             f.write_str("field identifier")
543         }
544 
545         fn visit_u64<E: Error>(self, val: u64) -> Result<Self::Value, E> {
546             match val {
547                 0u64 => Ok(ModuleDeclarationsField::VersionMarker),
548                 1u64 => Ok(ModuleDeclarationsField::Functions),
549                 2u64 => Ok(ModuleDeclarationsField::DataObjects),
550                 _ => Ok(ModuleDeclarationsField::Ignore),
551             }
552         }
553 
554         fn visit_str<E: Error>(self, val: &str) -> Result<Self::Value, E> {
555             match val {
556                 "_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
557                 "functions" => Ok(ModuleDeclarationsField::Functions),
558                 "data_objects" => Ok(ModuleDeclarationsField::DataObjects),
559                 _ => Ok(ModuleDeclarationsField::Ignore),
560             }
561         }
562 
563         fn visit_bytes<E: Error>(self, val: &[u8]) -> Result<Self::Value, E> {
564             match val {
565                 b"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
566                 b"functions" => Ok(ModuleDeclarationsField::Functions),
567                 b"data_objects" => Ok(ModuleDeclarationsField::DataObjects),
568                 _ => Ok(ModuleDeclarationsField::Ignore),
569             }
570         }
571     }
572 
573     impl<'de> Deserialize<'de> for ModuleDeclarationsField {
574         #[inline]
575         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
576             d.deserialize_identifier(ModuleDeclarationsFieldVisitor)
577         }
578     }
579 
580     struct ModuleDeclarationsVisitor;
581 
582     impl<'de> Visitor<'de> for ModuleDeclarationsVisitor {
583         type Value = ModuleDeclarations;
584 
585         fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
586             f.write_str("struct ModuleDeclarations")
587         }
588 
589         #[inline]
590         fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
591             let _version_marker = match seq.next_element()? {
592                 Some(val) => val,
593                 None => {
594                     return Err(Error::invalid_length(
595                         0usize,
596                         &"struct ModuleDeclarations with 4 elements",
597                     ));
598                 }
599             };
600             let functions = match seq.next_element()? {
601                 Some(val) => val,
602                 None => {
603                     return Err(Error::invalid_length(
604                         2usize,
605                         &"struct ModuleDeclarations with 4 elements",
606                     ));
607                 }
608             };
609             let data_objects = match seq.next_element()? {
610                 Some(val) => val,
611                 None => {
612                     return Err(Error::invalid_length(
613                         3usize,
614                         &"struct ModuleDeclarations with 4 elements",
615                     ));
616                 }
617             };
618             let names = get_names(&functions, &data_objects)?;
619             Ok(ModuleDeclarations {
620                 _version_marker,
621                 names,
622                 functions,
623                 data_objects,
624             })
625         }
626 
627         #[inline]
628         fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
629             let mut _version_marker: Option<VersionMarker> = None;
630             let mut functions: Option<PrimaryMap<FuncId, FunctionDeclaration>> = None;
631             let mut data_objects: Option<PrimaryMap<DataId, DataDeclaration>> = None;
632             while let Some(key) = map.next_key::<ModuleDeclarationsField>()? {
633                 match key {
634                     ModuleDeclarationsField::VersionMarker => {
635                         if _version_marker.is_some() {
636                             return Err(Error::duplicate_field("_version_marker"));
637                         }
638                         _version_marker = Some(map.next_value()?);
639                     }
640                     ModuleDeclarationsField::Functions => {
641                         if functions.is_some() {
642                             return Err(Error::duplicate_field("functions"));
643                         }
644                         functions = Some(map.next_value()?);
645                     }
646                     ModuleDeclarationsField::DataObjects => {
647                         if data_objects.is_some() {
648                             return Err(Error::duplicate_field("data_objects"));
649                         }
650                         data_objects = Some(map.next_value()?);
651                     }
652                     _ => {
653                         map.next_value::<serde::de::IgnoredAny>()?;
654                     }
655                 }
656             }
657             let _version_marker = match _version_marker {
658                 Some(_version_marker) => _version_marker,
659                 None => return Err(Error::missing_field("_version_marker")),
660             };
661             let functions = match functions {
662                 Some(functions) => functions,
663                 None => return Err(Error::missing_field("functions")),
664             };
665             let data_objects = match data_objects {
666                 Some(data_objects) => data_objects,
667                 None => return Err(Error::missing_field("data_objects")),
668             };
669             let names = get_names(&functions, &data_objects)?;
670             Ok(ModuleDeclarations {
671                 _version_marker,
672                 names,
673                 functions,
674                 data_objects,
675             })
676         }
677     }
678 
679     impl<'de> Deserialize<'de> for ModuleDeclarations {
680         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
681             d.deserialize_struct(
682                 "ModuleDeclarations",
683                 &["_version_marker", "functions", "data_objects"],
684                 ModuleDeclarationsVisitor,
685             )
686         }
687     }
688 }
689 
690 impl ModuleDeclarations {
691     /// Get the module identifier for a given name, if that name
692     /// has been declared.
693     pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
694         self.names.get(name).copied()
695     }
696 
697     /// Get an iterator of all function declarations
698     pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {
699         self.functions.iter()
700     }
701 
702     /// Return whether `name` names a function, rather than a data object.
703     pub fn is_function(name: &ModuleRelocTarget) -> bool {
704         match name {
705             ModuleRelocTarget::User { namespace, .. } => *namespace == 0,
706             ModuleRelocTarget::LibCall(_)
707             | ModuleRelocTarget::KnownSymbol(_)
708             | ModuleRelocTarget::FunctionOffset(..) => {
709                 panic!("unexpected module ext name")
710             }
711         }
712     }
713 
714     /// Get the `FunctionDeclaration` for the function named by `name`.
715     pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {
716         &self.functions[func_id]
717     }
718 
719     /// Get an iterator of all data declarations
720     pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {
721         self.data_objects.iter()
722     }
723 
724     /// Get the `DataDeclaration` for the data object named by `name`.
725     pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {
726         &self.data_objects[data_id]
727     }
728 
729     /// Declare a function in this module.
730     pub fn declare_function(
731         &mut self,
732         name: &str,
733         linkage: Linkage,
734         signature: &ir::Signature,
735     ) -> ModuleResult<(FuncId, Linkage)> {
736         // TODO: Can we avoid allocating names so often?
737         use super::hash_map::Entry::*;
738         match self.names.entry(name.to_owned()) {
739             Occupied(entry) => match *entry.get() {
740                 FuncOrDataId::Func(id) => {
741                     let existing = &mut self.functions[id];
742                     existing.merge(id, linkage, signature)?;
743                     Ok((id, existing.linkage))
744                 }
745                 FuncOrDataId::Data(..) => {
746                     Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
747                 }
748             },
749             Vacant(entry) => {
750                 let id = self.functions.push(FunctionDeclaration {
751                     name: Some(name.to_owned()),
752                     linkage,
753                     signature: signature.clone(),
754                 });
755                 entry.insert(FuncOrDataId::Func(id));
756                 Ok((id, self.functions[id].linkage))
757             }
758         }
759     }
760 
761     /// Declare an anonymous function in this module.
762     pub fn declare_anonymous_function(
763         &mut self,
764         signature: &ir::Signature,
765     ) -> ModuleResult<FuncId> {
766         let id = self.functions.push(FunctionDeclaration {
767             name: None,
768             linkage: Linkage::Local,
769             signature: signature.clone(),
770         });
771         Ok(id)
772     }
773 
774     /// Declare a data object in this module.
775     pub fn declare_data(
776         &mut self,
777         name: &str,
778         linkage: Linkage,
779         writable: bool,
780         tls: bool,
781     ) -> ModuleResult<(DataId, Linkage)> {
782         // TODO: Can we avoid allocating names so often?
783         use super::hash_map::Entry::*;
784         match self.names.entry(name.to_owned()) {
785             Occupied(entry) => match *entry.get() {
786                 FuncOrDataId::Data(id) => {
787                     let existing = &mut self.data_objects[id];
788                     existing.merge(linkage, writable, tls);
789                     Ok((id, existing.linkage))
790                 }
791 
792                 FuncOrDataId::Func(..) => {
793                     Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
794                 }
795             },
796             Vacant(entry) => {
797                 let id = self.data_objects.push(DataDeclaration {
798                     name: Some(name.to_owned()),
799                     linkage,
800                     writable,
801                     tls,
802                 });
803                 entry.insert(FuncOrDataId::Data(id));
804                 Ok((id, self.data_objects[id].linkage))
805             }
806         }
807     }
808 
809     /// Declare an anonymous data object in this module.
810     pub fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
811         let id = self.data_objects.push(DataDeclaration {
812             name: None,
813             linkage: Linkage::Local,
814             writable,
815             tls,
816         });
817         Ok(id)
818     }
819 }
820 
821 /// A `Module` is a utility for collecting functions and data objects, and linking them together.
822 pub trait Module {
823     /// Return the `TargetIsa` to compile for.
824     fn isa(&self) -> &dyn isa::TargetIsa;
825 
826     /// Get all declarations in this module.
827     fn declarations(&self) -> &ModuleDeclarations;
828 
829     /// Get the module identifier for a given name, if that name
830     /// has been declared.
831     fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
832         self.declarations().get_name(name)
833     }
834 
835     /// Return the target information needed by frontends to produce Cranelift IR
836     /// for the current target.
837     fn target_config(&self) -> isa::TargetFrontendConfig {
838         self.isa().frontend_config()
839     }
840 
841     /// Create a new `Context` initialized for use with this `Module`.
842     ///
843     /// This ensures that the `Context` is initialized with the default calling
844     /// convention for the `TargetIsa`.
845     fn make_context(&self) -> Context {
846         let mut ctx = Context::new();
847         ctx.func.signature.call_conv = self.isa().default_call_conv();
848         ctx
849     }
850 
851     /// Clear the given `Context` and reset it for use with a new function.
852     ///
853     /// This ensures that the `Context` is initialized with the default calling
854     /// convention for the `TargetIsa`.
855     fn clear_context(&self, ctx: &mut Context) {
856         ctx.clear();
857         ctx.func.signature.call_conv = self.isa().default_call_conv();
858     }
859 
860     /// Create a new empty `Signature` with the default calling convention for
861     /// the `TargetIsa`, to which parameter and return types can be added for
862     /// declaring a function to be called by this `Module`.
863     fn make_signature(&self) -> ir::Signature {
864         ir::Signature::new(self.isa().default_call_conv())
865     }
866 
867     /// Clear the given `Signature` and reset for use with a new function.
868     ///
869     /// This ensures that the `Signature` is initialized with the default
870     /// calling convention for the `TargetIsa`.
871     fn clear_signature(&self, sig: &mut ir::Signature) {
872         sig.clear(self.isa().default_call_conv());
873     }
874 
875     /// Declare a function in this module.
876     fn declare_function(
877         &mut self,
878         name: &str,
879         linkage: Linkage,
880         signature: &ir::Signature,
881     ) -> ModuleResult<FuncId>;
882 
883     /// Declare an anonymous function in this module.
884     fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId>;
885 
886     /// Declare a data object in this module.
887     fn declare_data(
888         &mut self,
889         name: &str,
890         linkage: Linkage,
891         writable: bool,
892         tls: bool,
893     ) -> ModuleResult<DataId>;
894 
895     /// Declare an anonymous data object in this module.
896     fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId>;
897 
898     /// Use this when you're building the IR of a function to reference a function.
899     ///
900     /// TODO: Coalesce redundant decls and signatures.
901     /// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.
902     fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {
903         let decl = &self.declarations().functions[func_id];
904         let signature = func.import_signature(decl.signature.clone());
905         let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
906             namespace: 0,
907             index: func_id.as_u32(),
908         });
909         let colocated = decl.linkage.is_final();
910         func.import_function(ir::ExtFuncData {
911             name: ir::ExternalName::user(user_name_ref),
912             signature,
913             colocated,
914         })
915     }
916 
917     /// Use this when you're building the IR of a function to reference a data object.
918     ///
919     /// TODO: Same as above.
920     fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
921         let decl = &self.declarations().data_objects[data];
922         let colocated = decl.linkage.is_final();
923         let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
924             namespace: 1,
925             index: data.as_u32(),
926         });
927         func.create_global_value(ir::GlobalValueData::Symbol {
928             name: ir::ExternalName::user(user_name_ref),
929             offset: ir::immediates::Imm64::new(0),
930             colocated,
931             tls: decl.tls,
932         })
933     }
934 
935     /// TODO: Same as above.
936     fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
937         data.import_function(ModuleRelocTarget::user(0, func_id.as_u32()))
938     }
939 
940     /// TODO: Same as above.
941     fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
942         data.import_global_value(ModuleRelocTarget::user(1, data_id.as_u32()))
943     }
944 
945     /// Define a function, producing the function body from the given `Context`.
946     ///
947     /// Returns the size of the function's code and constant data.
948     ///
949     /// Unlike [`define_function_with_control_plane`] this uses a default [`ControlPlane`] for
950     /// convenience.
951     ///
952     /// Note: After calling this function the given `Context` will contain the compiled function.
953     ///
954     /// [`define_function_with_control_plane`]: Self::define_function_with_control_plane
955     fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
956         self.define_function_with_control_plane(func, ctx, &mut ControlPlane::default())
957     }
958 
959     /// Define a function, producing the function body from the given `Context`.
960     ///
961     /// Returns the size of the function's code and constant data.
962     ///
963     /// Note: After calling this function the given `Context` will contain the compiled function.
964     fn define_function_with_control_plane(
965         &mut self,
966         func: FuncId,
967         ctx: &mut Context,
968         ctrl_plane: &mut ControlPlane,
969     ) -> ModuleResult<()>;
970 
971     /// Define a function, taking the function body from the given `bytes`.
972     ///
973     /// This function is generally only useful if you need to precisely specify
974     /// the emitted instructions for some reason; otherwise, you should use
975     /// `define_function`.
976     ///
977     /// Returns the size of the function's code.
978     fn define_function_bytes(
979         &mut self,
980         func_id: FuncId,
981         func: &ir::Function,
982         alignment: u64,
983         bytes: &[u8],
984         relocs: &[FinalizedMachReloc],
985     ) -> ModuleResult<()>;
986 
987     /// Define a data object, producing the data contents from the given `DataContext`.
988     fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()>;
989 }
990 
991 impl<M: Module> Module for &mut M {
992     fn isa(&self) -> &dyn isa::TargetIsa {
993         (**self).isa()
994     }
995 
996     fn declarations(&self) -> &ModuleDeclarations {
997         (**self).declarations()
998     }
999 
1000     fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
1001         (**self).get_name(name)
1002     }
1003 
1004     fn target_config(&self) -> isa::TargetFrontendConfig {
1005         (**self).target_config()
1006     }
1007 
1008     fn make_context(&self) -> Context {
1009         (**self).make_context()
1010     }
1011 
1012     fn clear_context(&self, ctx: &mut Context) {
1013         (**self).clear_context(ctx)
1014     }
1015 
1016     fn make_signature(&self) -> ir::Signature {
1017         (**self).make_signature()
1018     }
1019 
1020     fn clear_signature(&self, sig: &mut ir::Signature) {
1021         (**self).clear_signature(sig)
1022     }
1023 
1024     fn declare_function(
1025         &mut self,
1026         name: &str,
1027         linkage: Linkage,
1028         signature: &ir::Signature,
1029     ) -> ModuleResult<FuncId> {
1030         (**self).declare_function(name, linkage, signature)
1031     }
1032 
1033     fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {
1034         (**self).declare_anonymous_function(signature)
1035     }
1036 
1037     fn declare_data(
1038         &mut self,
1039         name: &str,
1040         linkage: Linkage,
1041         writable: bool,
1042         tls: bool,
1043     ) -> ModuleResult<DataId> {
1044         (**self).declare_data(name, linkage, writable, tls)
1045     }
1046 
1047     fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
1048         (**self).declare_anonymous_data(writable, tls)
1049     }
1050 
1051     fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
1052         (**self).declare_func_in_func(func, in_func)
1053     }
1054 
1055     fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
1056         (**self).declare_data_in_func(data, func)
1057     }
1058 
1059     fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
1060         (**self).declare_func_in_data(func_id, data)
1061     }
1062 
1063     fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
1064         (**self).declare_data_in_data(data_id, data)
1065     }
1066 
1067     fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
1068         (**self).define_function(func, ctx)
1069     }
1070 
1071     fn define_function_with_control_plane(
1072         &mut self,
1073         func: FuncId,
1074         ctx: &mut Context,
1075         ctrl_plane: &mut ControlPlane,
1076     ) -> ModuleResult<()> {
1077         (**self).define_function_with_control_plane(func, ctx, ctrl_plane)
1078     }
1079 
1080     fn define_function_bytes(
1081         &mut self,
1082         func_id: FuncId,
1083         func: &ir::Function,
1084         alignment: u64,
1085         bytes: &[u8],
1086         relocs: &[FinalizedMachReloc],
1087     ) -> ModuleResult<()> {
1088         (**self).define_function_bytes(func_id, func, alignment, bytes, relocs)
1089     }
1090 
1091     fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {
1092         (**self).define_data(data_id, data)
1093     }
1094 }
1095