cranelift_codegen/isa/aarch64/
mod.rs

1//! ARM 64-bit Instruction Set Architecture.
2
3use crate::dominator_tree::DominatorTree;
4use crate::ir::{self, Function, Type};
5use crate::isa::aarch64::settings as aarch64_settings;
6#[cfg(feature = "unwind")]
7use crate::isa::unwind::systemv;
8use crate::isa::{Builder as IsaBuilder, FunctionAlignment, TargetIsa};
9use crate::machinst::{
10    CompiledCode, CompiledCodeStencil, MachInst, MachTextSectionBuilder, Reg, SigSet,
11    TextSectionBuilder, VCode, compile,
12};
13use crate::result::CodegenResult;
14use crate::settings as shared_settings;
15use alloc::{boxed::Box, vec::Vec};
16use core::fmt;
17use cranelift_control::ControlPlane;
18use std::string::String;
19use target_lexicon::{Aarch64Architecture, Architecture, OperatingSystem, Triple};
20
21// New backend:
22mod abi;
23pub mod inst;
24mod lower;
25mod pcc;
26pub mod settings;
27
28use self::inst::EmitInfo;
29
30/// An AArch64 backend.
31pub struct AArch64Backend {
32    triple: Triple,
33    flags: shared_settings::Flags,
34    isa_flags: aarch64_settings::Flags,
35}
36
37impl AArch64Backend {
38    /// Create a new AArch64 backend with the given (shared) flags.
39    pub fn new_with_flags(
40        triple: Triple,
41        flags: shared_settings::Flags,
42        isa_flags: aarch64_settings::Flags,
43    ) -> AArch64Backend {
44        AArch64Backend {
45            triple,
46            flags,
47            isa_flags,
48        }
49    }
50
51    /// This performs lowering to VCode, register-allocates the code, computes block layout and
52    /// finalizes branches. The result is ready for binary emission.
53    fn compile_vcode(
54        &self,
55        func: &Function,
56        domtree: &DominatorTree,
57        ctrl_plane: &mut ControlPlane,
58    ) -> CodegenResult<(VCode<inst::Inst>, regalloc2::Output)> {
59        let emit_info = EmitInfo::new(self.flags.clone());
60        let sigs = SigSet::new::<abi::AArch64MachineDeps>(func, &self.flags)?;
61        let abi = abi::AArch64Callee::new(func, self, &self.isa_flags, &sigs)?;
62        compile::compile::<AArch64Backend>(func, domtree, self, abi, emit_info, sigs, ctrl_plane)
63    }
64}
65
66impl TargetIsa for AArch64Backend {
67    fn compile_function(
68        &self,
69        func: &Function,
70        domtree: &DominatorTree,
71        want_disasm: bool,
72        ctrl_plane: &mut ControlPlane,
73    ) -> CodegenResult<CompiledCodeStencil> {
74        let (vcode, regalloc_result) = self.compile_vcode(func, domtree, ctrl_plane)?;
75
76        let emit_result = vcode.emit(&regalloc_result, want_disasm, &self.flags, ctrl_plane);
77        let frame_size = emit_result.frame_size;
78        let value_labels_ranges = emit_result.value_labels_ranges;
79        let buffer = emit_result.buffer;
80        let sized_stackslot_offsets = emit_result.sized_stackslot_offsets;
81        let dynamic_stackslot_offsets = emit_result.dynamic_stackslot_offsets;
82
83        if let Some(disasm) = emit_result.disasm.as_ref() {
84            log::debug!("disassembly:\n{}", disasm);
85        }
86
87        Ok(CompiledCodeStencil {
88            buffer,
89            frame_size,
90            vcode: emit_result.disasm,
91            value_labels_ranges,
92            sized_stackslot_offsets,
93            dynamic_stackslot_offsets,
94            bb_starts: emit_result.bb_offsets,
95            bb_edges: emit_result.bb_edges,
96        })
97    }
98
99    fn name(&self) -> &'static str {
100        "aarch64"
101    }
102
103    fn triple(&self) -> &Triple {
104        &self.triple
105    }
106
107    fn flags(&self) -> &shared_settings::Flags {
108        &self.flags
109    }
110
111    fn isa_flags(&self) -> Vec<shared_settings::Value> {
112        self.isa_flags.iter().collect()
113    }
114
115    fn is_branch_protection_enabled(&self) -> bool {
116        self.isa_flags.use_bti()
117    }
118
119    fn dynamic_vector_bytes(&self, _dyn_ty: Type) -> u32 {
120        16
121    }
122
123    #[cfg(feature = "unwind")]
124    fn emit_unwind_info(
125        &self,
126        result: &CompiledCode,
127        kind: crate::isa::unwind::UnwindInfoKind,
128    ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
129        use crate::isa::unwind::UnwindInfo;
130        use crate::isa::unwind::UnwindInfoKind;
131        Ok(match kind {
132            UnwindInfoKind::SystemV => {
133                let mapper = self::inst::unwind::systemv::RegisterMapper;
134                Some(UnwindInfo::SystemV(
135                    crate::isa::unwind::systemv::create_unwind_info_from_insts(
136                        &result.buffer.unwind_info[..],
137                        result.buffer.data().len(),
138                        &mapper,
139                    )?,
140                ))
141            }
142            UnwindInfoKind::Windows => Some(UnwindInfo::WindowsArm64(
143                crate::isa::unwind::winarm64::create_unwind_info_from_insts(
144                    &result.buffer.unwind_info[..],
145                )?,
146            )),
147            _ => None,
148        })
149    }
150
151    #[cfg(feature = "unwind")]
152    fn create_systemv_cie(&self) -> Option<gimli::write::CommonInformationEntry> {
153        let is_apple_os = match self.triple.operating_system {
154            OperatingSystem::Darwin(_)
155            | OperatingSystem::IOS(_)
156            | OperatingSystem::MacOSX { .. }
157            | OperatingSystem::TvOS(_) => true,
158            _ => false,
159        };
160
161        if self.isa_flags.sign_return_address()
162            && self.isa_flags.sign_return_address_with_bkey()
163            && !is_apple_os
164        {
165            unimplemented!(
166                "Specifying that the B key is used with pointer authentication instructions in the CIE is not implemented."
167            );
168        }
169
170        Some(inst::unwind::systemv::create_cie())
171    }
172
173    fn text_section_builder(&self, num_funcs: usize) -> Box<dyn TextSectionBuilder> {
174        Box::new(MachTextSectionBuilder::<inst::Inst>::new(num_funcs))
175    }
176
177    #[cfg(feature = "unwind")]
178    fn map_regalloc_reg_to_dwarf(&self, reg: Reg) -> Result<u16, systemv::RegisterMappingError> {
179        inst::unwind::systemv::map_reg(reg).map(|reg| reg.0)
180    }
181
182    fn function_alignment(&self) -> FunctionAlignment {
183        inst::Inst::function_alignment()
184    }
185
186    fn page_size_align_log2(&self) -> u8 {
187        use target_lexicon::*;
188        match self.triple().operating_system {
189            OperatingSystem::MacOSX { .. }
190            | OperatingSystem::Darwin(_)
191            | OperatingSystem::IOS(_)
192            | OperatingSystem::TvOS(_) => {
193                debug_assert_eq!(1 << 14, 0x4000);
194                14
195            }
196            _ => {
197                debug_assert_eq!(1 << 16, 0x10000);
198                16
199            }
200        }
201    }
202
203    #[cfg(feature = "disas")]
204    fn to_capstone(&self) -> Result<capstone::Capstone, capstone::Error> {
205        use capstone::prelude::*;
206        let mut cs = Capstone::new()
207            .arm64()
208            .mode(arch::arm64::ArchMode::Arm)
209            .detail(true)
210            .build()?;
211        // AArch64 uses inline constants rather than a separate constant pool right now.
212        // Without this option, Capstone will stop disassembling as soon as it sees
213        // an inline constant that is not also a valid instruction. With this option,
214        // Capstone will print a `.byte` directive with the bytes of the inline constant
215        // and continue to the next instruction.
216        cs.set_skipdata(true)?;
217        Ok(cs)
218    }
219
220    fn pretty_print_reg(&self, reg: Reg, _size: u8) -> String {
221        inst::regs::pretty_print_reg(reg)
222    }
223
224    fn has_native_fma(&self) -> bool {
225        true
226    }
227
228    fn has_round(&self) -> bool {
229        true
230    }
231
232    fn has_x86_blendv_lowering(&self, _: Type) -> bool {
233        false
234    }
235
236    fn has_x86_pshufb_lowering(&self) -> bool {
237        false
238    }
239
240    fn has_x86_pmulhrsw_lowering(&self) -> bool {
241        false
242    }
243
244    fn has_x86_pmaddubsw_lowering(&self) -> bool {
245        false
246    }
247
248    fn default_argument_extension(&self) -> ir::ArgumentExtension {
249        // This is copied/carried over from a historical piece of code in
250        // Wasmtime:
251        //
252        // https://github.com/bytecodealliance/wasmtime/blob/a018a5a9addb77d5998021a0150192aa955c71bf/crates/cranelift/src/lib.rs#L366-L374
253        //
254        // Whether or not it is still applicable here is unsure, but it's left
255        // the same as-is for now to reduce the likelihood of problems arising.
256        ir::ArgumentExtension::Uext
257    }
258}
259
260impl fmt::Display for AArch64Backend {
261    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
262        f.debug_struct("MachBackend")
263            .field("name", &self.name())
264            .field("triple", &self.triple())
265            .field("flags", &format!("{}", self.flags()))
266            .finish()
267    }
268}
269
270/// Create a new `isa::Builder`.
271pub fn isa_builder(triple: Triple) -> IsaBuilder {
272    assert!(triple.architecture == Architecture::Aarch64(Aarch64Architecture::Aarch64));
273    IsaBuilder {
274        triple,
275        setup: aarch64_settings::builder(),
276        constructor: |triple, shared_flags, builder| {
277            let isa_flags = aarch64_settings::Flags::new(&shared_flags, builder);
278            let backend = AArch64Backend::new_with_flags(triple, shared_flags, isa_flags);
279            Ok(backend.wrapped())
280        },
281    }
282}