1use super::HashMap;
9use crate::data_context::DataDescription;
10use core::fmt::Display;
11use cranelift_codegen::binemit::{CodeOffset, Reloc};
12use cranelift_codegen::entity::{entity_impl, PrimaryMap};
13use cranelift_codegen::ir::function::{Function, VersionMarker};
14use cranelift_codegen::ir::ExternalName;
15use cranelift_codegen::settings::SetError;
16use cranelift_codegen::{
17 ir, isa, CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget,
18};
19use cranelift_control::ControlPlane;
20use std::borrow::{Cow, ToOwned};
21use std::string::String;
22
23#[derive(Clone)]
25pub struct ModuleReloc {
26 pub offset: CodeOffset,
29 pub kind: Reloc,
31 pub name: ModuleRelocTarget,
33 pub addend: i64,
35}
36
37impl ModuleReloc {
38 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#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
71#[cfg_attr(
72 feature = "enable-serde",
73 derive(serde_derive::Serialize, serde_derive::Deserialize)
74)]
75pub struct FuncId(u32);
76entity_impl!(FuncId, "funcid");
77
78impl From<FuncId> for ModuleRelocTarget {
80 fn from(id: FuncId) -> Self {
81 Self::User {
82 namespace: 0,
83 index: id.0,
84 }
85 }
86}
87
88impl FuncId {
89 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#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
102#[cfg_attr(
103 feature = "enable-serde",
104 derive(serde_derive::Serialize, serde_derive::Deserialize)
105)]
106pub struct DataId(u32);
107entity_impl!(DataId, "dataid");
108
109impl From<DataId> for ModuleRelocTarget {
111 fn from(id: DataId) -> Self {
112 Self::User {
113 namespace: 1,
114 index: id.0,
115 }
116 }
117}
118
119impl DataId {
120 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#[derive(Copy, Clone, Debug, PartialEq, Eq)]
133#[cfg_attr(
134 feature = "enable-serde",
135 derive(serde_derive::Serialize, serde_derive::Deserialize)
136)]
137pub enum Linkage {
138 Import,
140 Local,
142 Preemptible,
144 Hidden,
149 Export,
151}
152
153impl 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 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 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#[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)]
199pub enum FuncOrDataId {
200 Func(FuncId),
202 Data(DataId),
204}
205
206impl 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#[derive(Debug)]
218#[cfg_attr(
219 feature = "enable-serde",
220 derive(serde_derive::Serialize, serde_derive::Deserialize)
221)]
222pub 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
231impl FunctionDeclaration {
232 pub fn linkage_name(&self, id: FuncId) -> Cow<'_, str> {
236 match &self.name {
237 Some(name) => Cow::Borrowed(name),
238 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#[derive(Debug)]
265pub enum ModuleError {
266 Undeclared(String),
268
269 IncompatibleDeclaration(String),
271
272 IncompatibleSignature(String, ir::Signature, ir::Signature),
275
276 DuplicateDefinition(String),
278
279 InvalidImportDefinition(String),
281
282 Compilation(CodegenError),
284
285 Allocation {
287 message: &'static str,
289 err: std::io::Error,
291 },
292
293 Backend(anyhow::Error),
295
296 Flag(SetError),
298}
299
300impl<'a> From<CompileError<'a>> for ModuleError {
301 fn from(err: CompileError<'a>) -> Self {
302 Self::Compilation(err.inner)
303 }
304}
305
306impl 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
324impl 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 {} signature {:?} is incompatible with previous declaration {:?}",
337 name, new_sig, prev_sig,
338 )
339 }
340 Self::DuplicateDefinition(name) => {
341 write!(f, "Duplicate definition of identifier: {}", name)
342 }
343 Self::InvalidImportDefinition(name) => {
344 write!(
345 f,
346 "Invalid to define identifier declared as an import: {}",
347 name,
348 )
349 }
350 Self::Compilation(err) => {
351 write!(f, "Compilation error: {}", err)
352 }
353 Self::Allocation { message, err } => {
354 write!(f, "Allocation error: {}: {}", message, err)
355 }
356 Self::Backend(err) => write!(f, "Backend error: {}", err),
357 Self::Flag(err) => write!(f, "Flag error: {}", err),
358 }
359 }
360}
361
362impl std::convert::From<CodegenError> for ModuleError {
363 fn from(source: CodegenError) -> Self {
364 Self::Compilation { 0: source }
365 }
366}
367
368impl std::convert::From<SetError> for ModuleError {
369 fn from(source: SetError) -> Self {
370 Self::Flag { 0: source }
371 }
372}
373
374pub type ModuleResult<T> = Result<T, ModuleError>;
376
377#[derive(Debug)]
379#[cfg_attr(
380 feature = "enable-serde",
381 derive(serde_derive::Serialize, serde_derive::Deserialize)
382)]
383pub struct DataDeclaration {
384 #[allow(missing_docs)]
385 pub name: Option<String>,
386 #[allow(missing_docs)]
387 pub linkage: Linkage,
388 #[allow(missing_docs)]
389 pub writable: bool,
390 #[allow(missing_docs)]
391 pub tls: bool,
392}
393
394impl DataDeclaration {
395 pub fn linkage_name(&self, id: DataId) -> Cow<'_, str> {
399 match &self.name {
400 Some(name) => Cow::Borrowed(name),
401 None => Cow::Owned(format!(".Ldata{:x}", id.as_u32())),
405 }
406 }
407
408 fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {
409 self.linkage = Linkage::merge(self.linkage, linkage);
410 self.writable = self.writable || writable;
411 assert_eq!(
412 self.tls, tls,
413 "Can't change TLS data object to normal or in the opposite way",
414 );
415 }
416}
417
418#[derive(Clone, Debug)]
420#[cfg_attr(
421 feature = "enable-serde",
422 derive(serde_derive::Serialize, serde_derive::Deserialize)
423)]
424pub enum ModuleRelocTarget {
425 User {
427 namespace: u32,
429 index: u32,
431 },
432 LibCall(ir::LibCall),
434 KnownSymbol(ir::KnownSymbol),
436 FunctionOffset(FuncId, CodeOffset),
438}
439
440impl ModuleRelocTarget {
441 pub fn user(namespace: u32, index: u32) -> Self {
443 Self::User { namespace, index }
444 }
445}
446
447impl Display for ModuleRelocTarget {
448 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
449 match self {
450 Self::User { namespace, index } => write!(f, "u{}:{}", namespace, index),
451 Self::LibCall(lc) => write!(f, "%{}", lc),
452 Self::KnownSymbol(ks) => write!(f, "{}", ks),
453 Self::FunctionOffset(fname, offset) => write!(f, "{fname}+{offset}"),
454 }
455 }
456}
457
458#[derive(Debug, Default)]
461pub struct ModuleDeclarations {
462 _version_marker: VersionMarker,
467
468 names: HashMap<String, FuncOrDataId>,
469 functions: PrimaryMap<FuncId, FunctionDeclaration>,
470 data_objects: PrimaryMap<DataId, DataDeclaration>,
471}
472
473#[cfg(feature = "enable-serde")]
474mod serialize {
475 use super::*;
479
480 use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Unexpected, Visitor};
481 use serde::ser::{Serialize, SerializeStruct, Serializer};
482 use std::fmt;
483
484 fn get_names<E: Error>(
485 functions: &PrimaryMap<FuncId, FunctionDeclaration>,
486 data_objects: &PrimaryMap<DataId, DataDeclaration>,
487 ) -> Result<HashMap<String, FuncOrDataId>, E> {
488 let mut names = HashMap::new();
489 for (func_id, decl) in functions.iter() {
490 if let Some(name) = &decl.name {
491 let old = names.insert(name.clone(), FuncOrDataId::Func(func_id));
492 if old.is_some() {
493 return Err(E::invalid_value(
494 Unexpected::Other("duplicate name"),
495 &"FunctionDeclaration's with no duplicate names",
496 ));
497 }
498 }
499 }
500 for (data_id, decl) in data_objects.iter() {
501 if let Some(name) = &decl.name {
502 let old = names.insert(name.clone(), FuncOrDataId::Data(data_id));
503 if old.is_some() {
504 return Err(E::invalid_value(
505 Unexpected::Other("duplicate name"),
506 &"DataDeclaration's with no duplicate names",
507 ));
508 }
509 }
510 }
511 Ok(names)
512 }
513
514 impl Serialize for ModuleDeclarations {
515 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
516 let ModuleDeclarations {
517 _version_marker,
518 functions,
519 data_objects,
520 names: _,
521 } = self;
522
523 let mut state = s.serialize_struct("ModuleDeclarations", 4)?;
524 state.serialize_field("_version_marker", _version_marker)?;
525 state.serialize_field("functions", functions)?;
526 state.serialize_field("data_objects", data_objects)?;
527 state.end()
528 }
529 }
530
531 enum ModuleDeclarationsField {
532 VersionMarker,
533 Functions,
534 DataObjects,
535 Ignore,
536 }
537
538 struct ModuleDeclarationsFieldVisitor;
539
540 impl<'de> serde::de::Visitor<'de> for ModuleDeclarationsFieldVisitor {
541 type Value = ModuleDeclarationsField;
542
543 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
544 f.write_str("field identifier")
545 }
546
547 fn visit_u64<E: Error>(self, val: u64) -> Result<Self::Value, E> {
548 match val {
549 0u64 => Ok(ModuleDeclarationsField::VersionMarker),
550 1u64 => Ok(ModuleDeclarationsField::Functions),
551 2u64 => Ok(ModuleDeclarationsField::DataObjects),
552 _ => Ok(ModuleDeclarationsField::Ignore),
553 }
554 }
555
556 fn visit_str<E: Error>(self, val: &str) -> Result<Self::Value, E> {
557 match val {
558 "_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
559 "functions" => Ok(ModuleDeclarationsField::Functions),
560 "data_objects" => Ok(ModuleDeclarationsField::DataObjects),
561 _ => Ok(ModuleDeclarationsField::Ignore),
562 }
563 }
564
565 fn visit_bytes<E: Error>(self, val: &[u8]) -> Result<Self::Value, E> {
566 match val {
567 b"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),
568 b"functions" => Ok(ModuleDeclarationsField::Functions),
569 b"data_objects" => Ok(ModuleDeclarationsField::DataObjects),
570 _ => Ok(ModuleDeclarationsField::Ignore),
571 }
572 }
573 }
574
575 impl<'de> Deserialize<'de> for ModuleDeclarationsField {
576 #[inline]
577 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
578 d.deserialize_identifier(ModuleDeclarationsFieldVisitor)
579 }
580 }
581
582 struct ModuleDeclarationsVisitor;
583
584 impl<'de> Visitor<'de> for ModuleDeclarationsVisitor {
585 type Value = ModuleDeclarations;
586
587 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
588 f.write_str("struct ModuleDeclarations")
589 }
590
591 #[inline]
592 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
593 let _version_marker = match seq.next_element()? {
594 Some(val) => val,
595 None => {
596 return Err(Error::invalid_length(
597 0usize,
598 &"struct ModuleDeclarations with 4 elements",
599 ));
600 }
601 };
602 let functions = match seq.next_element()? {
603 Some(val) => val,
604 None => {
605 return Err(Error::invalid_length(
606 2usize,
607 &"struct ModuleDeclarations with 4 elements",
608 ));
609 }
610 };
611 let data_objects = match seq.next_element()? {
612 Some(val) => val,
613 None => {
614 return Err(Error::invalid_length(
615 3usize,
616 &"struct ModuleDeclarations with 4 elements",
617 ));
618 }
619 };
620 let names = get_names(&functions, &data_objects)?;
621 Ok(ModuleDeclarations {
622 _version_marker,
623 names,
624 functions,
625 data_objects,
626 })
627 }
628
629 #[inline]
630 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
631 let mut _version_marker: Option<VersionMarker> = None;
632 let mut functions: Option<PrimaryMap<FuncId, FunctionDeclaration>> = None;
633 let mut data_objects: Option<PrimaryMap<DataId, DataDeclaration>> = None;
634 while let Some(key) = map.next_key::<ModuleDeclarationsField>()? {
635 match key {
636 ModuleDeclarationsField::VersionMarker => {
637 if _version_marker.is_some() {
638 return Err(Error::duplicate_field("_version_marker"));
639 }
640 _version_marker = Some(map.next_value()?);
641 }
642 ModuleDeclarationsField::Functions => {
643 if functions.is_some() {
644 return Err(Error::duplicate_field("functions"));
645 }
646 functions = Some(map.next_value()?);
647 }
648 ModuleDeclarationsField::DataObjects => {
649 if data_objects.is_some() {
650 return Err(Error::duplicate_field("data_objects"));
651 }
652 data_objects = Some(map.next_value()?);
653 }
654 _ => {
655 map.next_value::<serde::de::IgnoredAny>()?;
656 }
657 }
658 }
659 let _version_marker = match _version_marker {
660 Some(_version_marker) => _version_marker,
661 None => return Err(Error::missing_field("_version_marker")),
662 };
663 let functions = match functions {
664 Some(functions) => functions,
665 None => return Err(Error::missing_field("functions")),
666 };
667 let data_objects = match data_objects {
668 Some(data_objects) => data_objects,
669 None => return Err(Error::missing_field("data_objects")),
670 };
671 let names = get_names(&functions, &data_objects)?;
672 Ok(ModuleDeclarations {
673 _version_marker,
674 names,
675 functions,
676 data_objects,
677 })
678 }
679 }
680
681 impl<'de> Deserialize<'de> for ModuleDeclarations {
682 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
683 d.deserialize_struct(
684 "ModuleDeclarations",
685 &["_version_marker", "functions", "data_objects"],
686 ModuleDeclarationsVisitor,
687 )
688 }
689 }
690}
691
692impl ModuleDeclarations {
693 pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
696 self.names.get(name).copied()
697 }
698
699 pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {
701 self.functions.iter()
702 }
703
704 pub fn is_function(name: &ModuleRelocTarget) -> bool {
706 match name {
707 ModuleRelocTarget::User { namespace, .. } => *namespace == 0,
708 ModuleRelocTarget::LibCall(_)
709 | ModuleRelocTarget::KnownSymbol(_)
710 | ModuleRelocTarget::FunctionOffset(..) => {
711 panic!("unexpected module ext name")
712 }
713 }
714 }
715
716 pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {
718 &self.functions[func_id]
719 }
720
721 pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {
723 self.data_objects.iter()
724 }
725
726 pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {
728 &self.data_objects[data_id]
729 }
730
731 pub fn declare_function(
733 &mut self,
734 name: &str,
735 linkage: Linkage,
736 signature: &ir::Signature,
737 ) -> ModuleResult<(FuncId, Linkage)> {
738 use super::hash_map::Entry::*;
740 match self.names.entry(name.to_owned()) {
741 Occupied(entry) => match *entry.get() {
742 FuncOrDataId::Func(id) => {
743 let existing = &mut self.functions[id];
744 existing.merge(id, linkage, signature)?;
745 Ok((id, existing.linkage))
746 }
747 FuncOrDataId::Data(..) => {
748 Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
749 }
750 },
751 Vacant(entry) => {
752 let id = self.functions.push(FunctionDeclaration {
753 name: Some(name.to_owned()),
754 linkage,
755 signature: signature.clone(),
756 });
757 entry.insert(FuncOrDataId::Func(id));
758 Ok((id, self.functions[id].linkage))
759 }
760 }
761 }
762
763 pub fn declare_anonymous_function(
765 &mut self,
766 signature: &ir::Signature,
767 ) -> ModuleResult<FuncId> {
768 let id = self.functions.push(FunctionDeclaration {
769 name: None,
770 linkage: Linkage::Local,
771 signature: signature.clone(),
772 });
773 Ok(id)
774 }
775
776 pub fn declare_data(
778 &mut self,
779 name: &str,
780 linkage: Linkage,
781 writable: bool,
782 tls: bool,
783 ) -> ModuleResult<(DataId, Linkage)> {
784 use super::hash_map::Entry::*;
786 match self.names.entry(name.to_owned()) {
787 Occupied(entry) => match *entry.get() {
788 FuncOrDataId::Data(id) => {
789 let existing = &mut self.data_objects[id];
790 existing.merge(linkage, writable, tls);
791 Ok((id, existing.linkage))
792 }
793
794 FuncOrDataId::Func(..) => {
795 Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
796 }
797 },
798 Vacant(entry) => {
799 let id = self.data_objects.push(DataDeclaration {
800 name: Some(name.to_owned()),
801 linkage,
802 writable,
803 tls,
804 });
805 entry.insert(FuncOrDataId::Data(id));
806 Ok((id, self.data_objects[id].linkage))
807 }
808 }
809 }
810
811 pub fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
813 let id = self.data_objects.push(DataDeclaration {
814 name: None,
815 linkage: Linkage::Local,
816 writable,
817 tls,
818 });
819 Ok(id)
820 }
821}
822
823pub trait Module {
825 fn isa(&self) -> &dyn isa::TargetIsa;
827
828 fn declarations(&self) -> &ModuleDeclarations;
830
831 fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
834 self.declarations().get_name(name)
835 }
836
837 fn target_config(&self) -> isa::TargetFrontendConfig {
840 self.isa().frontend_config()
841 }
842
843 fn make_context(&self) -> Context {
848 let mut ctx = Context::new();
849 ctx.func.signature.call_conv = self.isa().default_call_conv();
850 ctx
851 }
852
853 fn clear_context(&self, ctx: &mut Context) {
858 ctx.clear();
859 ctx.func.signature.call_conv = self.isa().default_call_conv();
860 }
861
862 fn make_signature(&self) -> ir::Signature {
866 ir::Signature::new(self.isa().default_call_conv())
867 }
868
869 fn clear_signature(&self, sig: &mut ir::Signature) {
874 sig.clear(self.isa().default_call_conv());
875 }
876
877 fn declare_function(
879 &mut self,
880 name: &str,
881 linkage: Linkage,
882 signature: &ir::Signature,
883 ) -> ModuleResult<FuncId>;
884
885 fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId>;
887
888 fn declare_data(
890 &mut self,
891 name: &str,
892 linkage: Linkage,
893 writable: bool,
894 tls: bool,
895 ) -> ModuleResult<DataId>;
896
897 fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId>;
899
900 fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {
905 let decl = &self.declarations().functions[func_id];
906 let signature = func.import_signature(decl.signature.clone());
907 let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
908 namespace: 0,
909 index: func_id.as_u32(),
910 });
911 let colocated = decl.linkage.is_final();
912 func.import_function(ir::ExtFuncData {
913 name: ir::ExternalName::user(user_name_ref),
914 signature,
915 colocated,
916 })
917 }
918
919 fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
923 let decl = &self.declarations().data_objects[data];
924 let colocated = decl.linkage.is_final();
925 let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
926 namespace: 1,
927 index: data.as_u32(),
928 });
929 func.create_global_value(ir::GlobalValueData::Symbol {
930 name: ir::ExternalName::user(user_name_ref),
931 offset: ir::immediates::Imm64::new(0),
932 colocated,
933 tls: decl.tls,
934 })
935 }
936
937 fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
939 data.import_function(ModuleRelocTarget::user(0, func_id.as_u32()))
940 }
941
942 fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
944 data.import_global_value(ModuleRelocTarget::user(1, data_id.as_u32()))
945 }
946
947 fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
958 self.define_function_with_control_plane(func, ctx, &mut ControlPlane::default())
959 }
960
961 fn define_function_with_control_plane(
967 &mut self,
968 func: FuncId,
969 ctx: &mut Context,
970 ctrl_plane: &mut ControlPlane,
971 ) -> ModuleResult<()>;
972
973 fn define_function_bytes(
981 &mut self,
982 func_id: FuncId,
983 func: &ir::Function,
984 alignment: u64,
985 bytes: &[u8],
986 relocs: &[FinalizedMachReloc],
987 ) -> ModuleResult<()>;
988
989 fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()>;
991}
992
993impl<M: Module> Module for &mut M {
994 fn isa(&self) -> &dyn isa::TargetIsa {
995 (**self).isa()
996 }
997
998 fn declarations(&self) -> &ModuleDeclarations {
999 (**self).declarations()
1000 }
1001
1002 fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
1003 (**self).get_name(name)
1004 }
1005
1006 fn target_config(&self) -> isa::TargetFrontendConfig {
1007 (**self).target_config()
1008 }
1009
1010 fn make_context(&self) -> Context {
1011 (**self).make_context()
1012 }
1013
1014 fn clear_context(&self, ctx: &mut Context) {
1015 (**self).clear_context(ctx)
1016 }
1017
1018 fn make_signature(&self) -> ir::Signature {
1019 (**self).make_signature()
1020 }
1021
1022 fn clear_signature(&self, sig: &mut ir::Signature) {
1023 (**self).clear_signature(sig)
1024 }
1025
1026 fn declare_function(
1027 &mut self,
1028 name: &str,
1029 linkage: Linkage,
1030 signature: &ir::Signature,
1031 ) -> ModuleResult<FuncId> {
1032 (**self).declare_function(name, linkage, signature)
1033 }
1034
1035 fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {
1036 (**self).declare_anonymous_function(signature)
1037 }
1038
1039 fn declare_data(
1040 &mut self,
1041 name: &str,
1042 linkage: Linkage,
1043 writable: bool,
1044 tls: bool,
1045 ) -> ModuleResult<DataId> {
1046 (**self).declare_data(name, linkage, writable, tls)
1047 }
1048
1049 fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
1050 (**self).declare_anonymous_data(writable, tls)
1051 }
1052
1053 fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
1054 (**self).declare_func_in_func(func, in_func)
1055 }
1056
1057 fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
1058 (**self).declare_data_in_func(data, func)
1059 }
1060
1061 fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {
1062 (**self).declare_func_in_data(func_id, data)
1063 }
1064
1065 fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {
1066 (**self).declare_data_in_data(data_id, data)
1067 }
1068
1069 fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
1070 (**self).define_function(func, ctx)
1071 }
1072
1073 fn define_function_with_control_plane(
1074 &mut self,
1075 func: FuncId,
1076 ctx: &mut Context,
1077 ctrl_plane: &mut ControlPlane,
1078 ) -> ModuleResult<()> {
1079 (**self).define_function_with_control_plane(func, ctx, ctrl_plane)
1080 }
1081
1082 fn define_function_bytes(
1083 &mut self,
1084 func_id: FuncId,
1085 func: &ir::Function,
1086 alignment: u64,
1087 bytes: &[u8],
1088 relocs: &[FinalizedMachReloc],
1089 ) -> ModuleResult<()> {
1090 (**self).define_function_bytes(func_id, func, alignment, bytes, relocs)
1091 }
1092
1093 fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {
1094 (**self).define_data(data_id, data)
1095 }
1096}