1 //! In-memory representation of compiled machine code, with labels and fixups to
2 //! refer to those labels. Handles constant-pool island insertion and also
3 //! veneer insertion for out-of-range jumps.
4 //!
5 //! This code exists to solve three problems:
6 //!
7 //! - Branch targets for forward branches are not known until later, when we
8 //!   emit code in a single pass through the instruction structs.
9 //!
10 //! - On many architectures, address references or offsets have limited range.
11 //!   For example, on AArch64, conditional branches can only target code +/- 1MB
12 //!   from the branch itself.
13 //!
14 //! - The lowering of control flow from the CFG-with-edges produced by
15 //!   [BlockLoweringOrder](super::BlockLoweringOrder), combined with many empty
16 //!   edge blocks when the register allocator does not need to insert any
17 //!   spills/reloads/moves in edge blocks, results in many suboptimal branch
18 //!   patterns. The lowering also pays no attention to block order, and so
19 //!   two-target conditional forms (cond-br followed by uncond-br) can often by
20 //!   avoided because one of the targets is the fallthrough. There are several
21 //!   cases here where we can simplify to use fewer branches.
22 //!
23 //! This "buffer" implements a single-pass code emission strategy (with a later
24 //! "fixup" pass, but only through recorded fixups, not all instructions). The
25 //! basic idea is:
26 //!
27 //! - Emit branches as they are, including two-target (cond/uncond) compound
28 //!   forms, but with zero offsets and optimistically assuming the target will be
29 //!   in range. Record the "fixup" for later. Targets are denoted instead by
30 //!   symbolic "labels" that are then bound to certain offsets in the buffer as
31 //!   we emit code. (Nominally, there is a label at the start of every basic
32 //!   block.)
33 //!
34 //! - As we do this, track the offset in the buffer at which the first label
35 //!   reference "goes out of range". We call this the "deadline". If we reach the
36 //!   deadline and we still have not bound the label to which an unresolved branch
37 //!   refers, we have a problem!
38 //!
39 //! - To solve this problem, we emit "islands" full of "veneers". An island is
40 //!   simply a chunk of code inserted in the middle of the code actually produced
41 //!   by the emitter (e.g., vcode iterating over instruction structs). The emitter
42 //!   has some awareness of this: it either asks for an island between blocks, so
43 //!   it is not accidentally executed, or else it emits a branch around the island
44 //!   when all other options fail (see `Inst::EmitIsland` meta-instruction).
45 //!
46 //! - A "veneer" is an instruction (or sequence of instructions) in an "island"
47 //!   that implements a longer-range reference to a label. The idea is that, for
48 //!   example, a branch with a limited range can branch to a "veneer" instead,
49 //!   which is simply a branch in a form that can use a longer-range reference. On
50 //!   AArch64, for example, conditionals have a +/- 1 MB range, but a conditional
51 //!   can branch to an unconditional branch which has a +/- 128 MB range. Hence, a
52 //!   conditional branch's label reference can be fixed up with a "veneer" to
53 //!   achieve a longer range.
54 //!
55 //! - To implement all of this, we require the backend to provide a `LabelUse`
56 //!   type that implements a trait. This is nominally an enum that records one of
57 //!   several kinds of references to an offset in code -- basically, a relocation
58 //!   type -- and will usually correspond to different instruction formats. The
59 //!   `LabelUse` implementation specifies the maximum range, how to patch in the
60 //!   actual label location when known, and how to generate a veneer to extend the
61 //!   range.
62 //!
63 //! That satisfies label references, but we still may have suboptimal branch
64 //! patterns. To clean up the branches, we do a simple "peephole"-style
65 //! optimization on the fly. To do so, the emitter (e.g., `Inst::emit()`)
66 //! informs the buffer of branches in the code and, in the case of conditionals,
67 //! the code that would have been emitted to invert this branch's condition. We
68 //! track the "latest branches": these are branches that are contiguous up to
69 //! the current offset. (If any code is emitted after a branch, that branch or
70 //! run of contiguous branches is no longer "latest".) The latest branches are
71 //! those that we can edit by simply truncating the buffer and doing something
72 //! else instead.
73 //!
74 //! To optimize branches, we implement several simple rules, and try to apply
75 //! them to the "latest branches" when possible:
76 //!
77 //! - A branch with a label target, when that label is bound to the ending
78 //!   offset of the branch (the fallthrough location), can be removed altogether,
79 //!   because the branch would have no effect).
80 //!
81 //! - An unconditional branch that starts at a label location, and branches to
82 //!   another label, results in a "label alias": all references to the label bound
83 //!   *to* this branch instruction are instead resolved to the *target* of the
84 //!   branch instruction. This effectively removes empty blocks that just
85 //!   unconditionally branch to the next block. We call this "branch threading".
86 //!
87 //! - A conditional followed by an unconditional, when the conditional branches
88 //!   to the unconditional's fallthrough, results in (i) the truncation of the
89 //!   unconditional, (ii) the inversion of the condition's condition, and (iii)
90 //!   replacement of the conditional's target (using the original target of the
91 //!   unconditional). This is a fancy way of saying "we can flip a two-target
92 //!   conditional branch's taken/not-taken targets if it works better with our
93 //!   fallthrough". To make this work, the emitter actually gives the buffer
94 //!   *both* forms of every conditional branch: the true form is emitted into the
95 //!   buffer, and the "inverted" machine-code bytes are provided as part of the
96 //!   branch-fixup metadata.
97 //!
98 //! - An unconditional B preceded by another unconditional P, when B's label(s) have
99 //!   been redirected to target(B), can be removed entirely. This is an extension
100 //!   of the branch-threading optimization, and is valid because if we know there
101 //!   will be no fallthrough into this branch instruction (the prior instruction
102 //!   is an unconditional jump), and if we know we have successfully redirected
103 //!   all labels, then this branch instruction is unreachable. Note that this
104 //!   works because the redirection happens before the label is ever resolved
105 //!   (fixups happen at island emission time, at which point latest-branches are
106 //!   cleared, or at the end of emission), so we are sure to catch and redirect
107 //!   all possible paths to this instruction.
108 //!
109 //! # Branch-optimization Correctness
110 //!
111 //! The branch-optimization mechanism depends on a few data structures with
112 //! invariants, which are always held outside the scope of top-level public
113 //! methods:
114 //!
115 //! - The latest-branches list. Each entry describes a span of the buffer
116 //!   (start/end offsets), the label target, the corresponding fixup-list entry
117 //!   index, and the bytes (must be the same length) for the inverted form, if
118 //!   conditional. The list of labels that are bound to the start-offset of this
119 //!   branch is *complete* (if any label has a resolved offset equal to `start`
120 //!   and is not an alias, it must appear in this list) and *precise* (no label
121 //!   in this list can be bound to another offset). No label in this list should
122 //!   be an alias.  No two branch ranges can overlap, and branches are in
123 //!   ascending-offset order.
124 //!
125 //! - The labels-at-tail list. This contains all MachLabels that have been bound
126 //!   to (whose resolved offsets are equal to) the tail offset of the buffer.
127 //!   No label in this list should be an alias.
128 //!
129 //! - The label_offsets array, containing the bound offset of a label or
130 //!   UNKNOWN. No label can be bound at an offset greater than the current
131 //!   buffer tail.
132 //!
133 //! - The label_aliases array, containing another label to which a label is
134 //!   bound or UNKNOWN. A label's resolved offset is the resolved offset
135 //!   of the label it is aliased to, if this is set.
136 //!
137 //! We argue below, at each method, how the invariants in these data structures
138 //! are maintained (grep for "Post-invariant").
139 //!
140 //! Given these invariants, we argue why each optimization preserves execution
141 //! semantics below (grep for "Preserves execution semantics").
142 //!
143 //! # Avoiding Quadratic Behavior
144 //!
145 //! There are two cases where we've had to take some care to avoid
146 //! quadratic worst-case behavior:
147 //!
148 //! - The "labels at this branch" list can grow unboundedly if the
149 //!   code generator binds many labels at one location. If the count
150 //!   gets too high (defined by the `LABEL_LIST_THRESHOLD` constant), we
151 //!   simply abort an optimization early in a way that is always correct
152 //!   but is conservative.
153 //!
154 //! - The fixup list can interact with island emission to create
155 //!   "quadratic island behavior". In a little more detail, one can hit
156 //!   this behavior by having some pending fixups (forward label
157 //!   references) with long-range label-use kinds, and some others
158 //!   with shorter-range references that nonetheless still are pending
159 //!   long enough to trigger island generation. In such a case, we
160 //!   process the fixup list, generate veneers to extend some forward
161 //!   references' ranges, but leave the other (longer-range) ones
162 //!   alone. The way this was implemented put them back on a list and
163 //!   resulted in quadratic behavior.
164 //!
165 //!   To avoid this fixups are split into two lists: one "pending" list and one
166 //!   final list. The pending list is kept around for handling fixups related to
167 //!   branches so it can be edited/truncated. When an island is reached, which
168 //!   starts processing fixups, all pending fixups are flushed into the final
169 //!   list. The final list is a `BinaryHeap` which enables fixup processing to
170 //!   only process those which are required during island emission, deferring
171 //!   all longer-range fixups to later.
172 
173 use crate::binemit::{Addend, CodeOffset, Reloc};
174 use crate::ir::function::FunctionParameters;
175 use crate::ir::{ExternalName, RelSourceLoc, SourceLoc, TrapCode};
176 use crate::isa::unwind::UnwindInst;
177 use crate::machinst::{
178     BlockIndex, MachInstLabelUse, TextSectionBuilder, VCodeConstant, VCodeConstants, VCodeInst,
179 };
180 use crate::trace;
181 use crate::{ir, MachInstEmitState};
182 use crate::{timing, VCodeConstantData};
183 use cranelift_control::ControlPlane;
184 use cranelift_entity::packed_option::PackedOption;
185 use cranelift_entity::{entity_impl, PrimaryMap};
186 use smallvec::SmallVec;
187 use std::cmp::Ordering;
188 use std::collections::BinaryHeap;
189 use std::mem;
190 use std::string::String;
191 use std::vec::Vec;
192 
193 #[cfg(feature = "enable-serde")]
194 use serde::{Deserialize, Serialize};
195 
196 #[cfg(feature = "enable-serde")]
197 pub trait CompilePhase {
198     type MachSrcLocType: for<'a> Deserialize<'a> + Serialize + core::fmt::Debug + PartialEq + Clone;
199     type SourceLocType: for<'a> Deserialize<'a> + Serialize + core::fmt::Debug + PartialEq + Clone;
200 }
201 
202 #[cfg(not(feature = "enable-serde"))]
203 pub trait CompilePhase {
204     type MachSrcLocType: core::fmt::Debug + PartialEq + Clone;
205     type SourceLocType: core::fmt::Debug + PartialEq + Clone;
206 }
207 
208 /// Status of a compiled artifact that needs patching before being used.
209 #[derive(Clone, Debug, PartialEq)]
210 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
211 pub struct Stencil;
212 
213 /// Status of a compiled artifact ready to use.
214 #[derive(Clone, Debug, PartialEq)]
215 pub struct Final;
216 
217 impl CompilePhase for Stencil {
218     type MachSrcLocType = MachSrcLoc<Stencil>;
219     type SourceLocType = RelSourceLoc;
220 }
221 
222 impl CompilePhase for Final {
223     type MachSrcLocType = MachSrcLoc<Final>;
224     type SourceLocType = SourceLoc;
225 }
226 
227 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
228 enum ForceVeneers {
229     Yes,
230     No,
231 }
232 
233 /// A buffer of output to be produced, fixed up, and then emitted to a CodeSink
234 /// in bulk.
235 ///
236 /// This struct uses `SmallVec`s to support small-ish function bodies without
237 /// any heap allocation. As such, it will be several kilobytes large. This is
238 /// likely fine as long as it is stack-allocated for function emission then
239 /// thrown away; but beware if many buffer objects are retained persistently.
240 pub struct MachBuffer<I: VCodeInst> {
241     /// The buffer contents, as raw bytes.
242     data: SmallVec<[u8; 1024]>,
243     /// The required alignment of this buffer.
244     min_alignment: u32,
245     /// Any relocations referring to this code. Note that only *external*
246     /// relocations are tracked here; references to labels within the buffer are
247     /// resolved before emission.
248     relocs: SmallVec<[MachReloc; 16]>,
249     /// Any trap records referring to this code.
250     traps: SmallVec<[MachTrap; 16]>,
251     /// Any call site records referring to this code.
252     call_sites: SmallVec<[MachCallSite; 16]>,
253     /// Any source location mappings referring to this code.
254     srclocs: SmallVec<[MachSrcLoc<Stencil>; 64]>,
255     /// Any user stack maps for this code.
256     ///
257     /// Each entry is an `(offset, span, stack_map)` triple. Entries are sorted
258     /// by code offset, and each stack map covers `span` bytes on the stack.
259     user_stack_maps: SmallVec<[(CodeOffset, u32, ir::UserStackMap); 8]>,
260     /// Any unwind info at a given location.
261     unwind_info: SmallVec<[(CodeOffset, UnwindInst); 8]>,
262     /// Any exception handler targets at a given location.
263     exception_handlers: SmallVec<[(CodeOffset, PackedOption<ir::ExceptionTag>, MachLabel); 8]>,
264     /// The current source location in progress (after `start_srcloc()` and
265     /// before `end_srcloc()`).  This is a (start_offset, src_loc) tuple.
266     cur_srcloc: Option<(CodeOffset, RelSourceLoc)>,
267     /// Known label offsets; `UNKNOWN_LABEL_OFFSET` if unknown.
268     label_offsets: SmallVec<[CodeOffset; 16]>,
269     /// Label aliases: when one label points to an unconditional jump, and that
270     /// jump points to another label, we can redirect references to the first
271     /// label immediately to the second.
272     ///
273     /// Invariant: we don't have label-alias cycles. We ensure this by,
274     /// before setting label A to alias label B, resolving B's alias
275     /// target (iteratively until a non-aliased label); if B is already
276     /// aliased to A, then we cannot alias A back to B.
277     label_aliases: SmallVec<[MachLabel; 16]>,
278     /// Constants that must be emitted at some point.
279     pending_constants: SmallVec<[VCodeConstant; 16]>,
280     /// Byte size of all constants in `pending_constants`.
281     pending_constants_size: CodeOffset,
282     /// Traps that must be emitted at some point.
283     pending_traps: SmallVec<[MachLabelTrap; 16]>,
284     /// Fixups that haven't yet been flushed into `fixup_records` below and may
285     /// be related to branches that are chomped. These all get added to
286     /// `fixup_records` during island emission.
287     pending_fixup_records: SmallVec<[MachLabelFixup<I>; 16]>,
288     /// The nearest upcoming deadline for entries in `pending_fixup_records`.
289     pending_fixup_deadline: CodeOffset,
290     /// Fixups that must be performed after all code is emitted.
291     fixup_records: BinaryHeap<MachLabelFixup<I>>,
292     /// Latest branches, to facilitate in-place editing for better fallthrough
293     /// behavior and empty-block removal.
294     latest_branches: SmallVec<[MachBranch; 4]>,
295     /// All labels at the current offset (emission tail). This is lazily
296     /// cleared: it is actually accurate as long as the current offset is
297     /// `labels_at_tail_off`, but if `cur_offset()` has grown larger, it should
298     /// be considered as empty.
299     ///
300     /// For correctness, this *must* be complete (i.e., the vector must contain
301     /// all labels whose offsets are resolved to the current tail), because we
302     /// rely on it to update labels when we truncate branches.
303     labels_at_tail: SmallVec<[MachLabel; 4]>,
304     /// The last offset at which `labels_at_tail` is valid. It is conceptually
305     /// always describing the tail of the buffer, but we do not clear
306     /// `labels_at_tail` eagerly when the tail grows, rather we lazily clear it
307     /// when the offset has grown past this (`labels_at_tail_off`) point.
308     /// Always <= `cur_offset()`.
309     labels_at_tail_off: CodeOffset,
310     /// Metadata about all constants that this function has access to.
311     ///
312     /// This records the size/alignment of all constants (not the actual data)
313     /// along with the last available label generated for the constant. This map
314     /// is consulted when constants are referred to and the label assigned to a
315     /// constant may change over time as well.
316     constants: PrimaryMap<VCodeConstant, MachBufferConstant>,
317     /// All recorded usages of constants as pairs of the constant and where the
318     /// constant needs to be placed within `self.data`. Note that the same
319     /// constant may appear in this array multiple times if it was emitted
320     /// multiple times.
321     used_constants: SmallVec<[(VCodeConstant, CodeOffset); 4]>,
322     /// Indicates when a patchable region is currently open, to guard that it's
323     /// not possible to nest patchable regions.
324     open_patchable: bool,
325 }
326 
327 impl MachBufferFinalized<Stencil> {
328     /// Get a finalized machine buffer by applying the function's base source location.
329     pub fn apply_base_srcloc(self, base_srcloc: SourceLoc) -> MachBufferFinalized<Final> {
330         MachBufferFinalized {
331             data: self.data,
332             relocs: self.relocs,
333             traps: self.traps,
334             call_sites: self.call_sites,
335             srclocs: self
336                 .srclocs
337                 .into_iter()
338                 .map(|srcloc| srcloc.apply_base_srcloc(base_srcloc))
339                 .collect(),
340             user_stack_maps: self.user_stack_maps,
341             unwind_info: self.unwind_info,
342             exception_handlers: self.exception_handlers,
343             alignment: self.alignment,
344         }
345     }
346 }
347 
348 /// A `MachBuffer` once emission is completed: holds generated code and records,
349 /// without fixups. This allows the type to be independent of the backend.
350 #[derive(PartialEq, Debug, Clone)]
351 #[cfg_attr(
352     feature = "enable-serde",
353     derive(serde_derive::Serialize, serde_derive::Deserialize)
354 )]
355 pub struct MachBufferFinalized<T: CompilePhase> {
356     /// The buffer contents, as raw bytes.
357     pub(crate) data: SmallVec<[u8; 1024]>,
358     /// Any relocations referring to this code. Note that only *external*
359     /// relocations are tracked here; references to labels within the buffer are
360     /// resolved before emission.
361     pub(crate) relocs: SmallVec<[FinalizedMachReloc; 16]>,
362     /// Any trap records referring to this code.
363     pub(crate) traps: SmallVec<[MachTrap; 16]>,
364     /// Any call site records referring to this code.
365     pub(crate) call_sites: SmallVec<[MachCallSite; 16]>,
366     /// Any source location mappings referring to this code.
367     pub(crate) srclocs: SmallVec<[T::MachSrcLocType; 64]>,
368     /// Any user stack maps for this code.
369     ///
370     /// Each entry is an `(offset, span, stack_map)` triple. Entries are sorted
371     /// by code offset, and each stack map covers `span` bytes on the stack.
372     pub(crate) user_stack_maps: SmallVec<[(CodeOffset, u32, ir::UserStackMap); 8]>,
373     /// Any unwind info at a given location.
374     pub unwind_info: SmallVec<[(CodeOffset, UnwindInst); 8]>,
375     /// Any exception handler targets at a given location.
376     pub exception_handlers: SmallVec<[(CodeOffset, PackedOption<ir::ExceptionTag>, CodeOffset); 8]>,
377     /// The required alignment of this buffer.
378     pub alignment: u32,
379 }
380 
381 const UNKNOWN_LABEL_OFFSET: CodeOffset = 0xffff_ffff;
382 const UNKNOWN_LABEL: MachLabel = MachLabel(0xffff_ffff);
383 
384 /// Threshold on max length of `labels_at_this_branch` list to avoid
385 /// unbounded quadratic behavior (see comment below at use-site).
386 const LABEL_LIST_THRESHOLD: usize = 100;
387 
388 /// A label refers to some offset in a `MachBuffer`. It may not be resolved at
389 /// the point at which it is used by emitted code; the buffer records "fixups"
390 /// for references to the label, and will come back and patch the code
391 /// appropriately when the label's location is eventually known.
392 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
393 pub struct MachLabel(u32);
394 entity_impl!(MachLabel);
395 
396 impl MachLabel {
397     /// Get a label for a block. (The first N MachLabels are always reserved for
398     /// the N blocks in the vcode.)
399     pub fn from_block(bindex: BlockIndex) -> MachLabel {
400         MachLabel(bindex.index() as u32)
401     }
402 
403     /// Creates a string representing this label, for convenience.
404     pub fn to_string(&self) -> String {
405         format!("label{}", self.0)
406     }
407 }
408 
409 impl Default for MachLabel {
410     fn default() -> Self {
411         UNKNOWN_LABEL
412     }
413 }
414 
415 /// Represents the beginning of an editable region in the [`MachBuffer`], while code emission is
416 /// still occurring. An [`OpenPatchRegion`] is closed by [`MachBuffer::end_patchable`], consuming
417 /// the [`OpenPatchRegion`] token in the process.
418 pub struct OpenPatchRegion(usize);
419 
420 /// A region in the [`MachBuffer`] code buffer that can be edited prior to finalization. An example
421 /// of where you might want to use this is for patching instructions that mention constants that
422 /// won't be known until later: [`MachBuffer::start_patchable`] can be used to begin the patchable
423 /// region, instructions can be emitted with placeholder constants, and the [`PatchRegion`] token
424 /// can be produced by [`MachBuffer::end_patchable`]. Once the values of those constants are known,
425 /// the [`PatchRegion::patch`] function can be used to get a mutable buffer to the instruction
426 /// bytes, and the constants uses can be updated directly.
427 pub struct PatchRegion {
428     range: std::ops::Range<usize>,
429 }
430 
431 impl PatchRegion {
432     /// Consume the patch region to yield a mutable slice of the [`MachBuffer`] data buffer.
433     pub fn patch<I: VCodeInst>(self, buffer: &mut MachBuffer<I>) -> &mut [u8] {
434         &mut buffer.data[self.range]
435     }
436 }
437 
438 impl<I: VCodeInst> MachBuffer<I> {
439     /// Create a new section, known to start at `start_offset` and with a size limited to
440     /// `length_limit`.
441     pub fn new() -> MachBuffer<I> {
442         MachBuffer {
443             data: SmallVec::new(),
444             min_alignment: I::function_alignment().minimum,
445             relocs: SmallVec::new(),
446             traps: SmallVec::new(),
447             call_sites: SmallVec::new(),
448             srclocs: SmallVec::new(),
449             user_stack_maps: SmallVec::new(),
450             unwind_info: SmallVec::new(),
451             exception_handlers: SmallVec::new(),
452             cur_srcloc: None,
453             label_offsets: SmallVec::new(),
454             label_aliases: SmallVec::new(),
455             pending_constants: SmallVec::new(),
456             pending_constants_size: 0,
457             pending_traps: SmallVec::new(),
458             pending_fixup_records: SmallVec::new(),
459             pending_fixup_deadline: u32::MAX,
460             fixup_records: Default::default(),
461             latest_branches: SmallVec::new(),
462             labels_at_tail: SmallVec::new(),
463             labels_at_tail_off: 0,
464             constants: Default::default(),
465             used_constants: Default::default(),
466             open_patchable: false,
467         }
468     }
469 
470     /// Current offset from start of buffer.
471     pub fn cur_offset(&self) -> CodeOffset {
472         self.data.len() as CodeOffset
473     }
474 
475     /// Add a byte.
476     pub fn put1(&mut self, value: u8) {
477         self.data.push(value);
478 
479         // Post-invariant: conceptual-labels_at_tail contains a complete and
480         // precise list of labels bound at `cur_offset()`. We have advanced
481         // `cur_offset()`, hence if it had been equal to `labels_at_tail_off`
482         // before, it is not anymore (and it cannot become equal, because
483         // `labels_at_tail_off` is always <= `cur_offset()`). Thus the list is
484         // conceptually empty (even though it is only lazily cleared). No labels
485         // can be bound at this new offset (by invariant on `label_offsets`).
486         // Hence the invariant holds.
487     }
488 
489     /// Add 2 bytes.
490     pub fn put2(&mut self, value: u16) {
491         let bytes = value.to_le_bytes();
492         self.data.extend_from_slice(&bytes[..]);
493 
494         // Post-invariant: as for `put1()`.
495     }
496 
497     /// Add 4 bytes.
498     pub fn put4(&mut self, value: u32) {
499         let bytes = value.to_le_bytes();
500         self.data.extend_from_slice(&bytes[..]);
501 
502         // Post-invariant: as for `put1()`.
503     }
504 
505     /// Add 8 bytes.
506     pub fn put8(&mut self, value: u64) {
507         let bytes = value.to_le_bytes();
508         self.data.extend_from_slice(&bytes[..]);
509 
510         // Post-invariant: as for `put1()`.
511     }
512 
513     /// Add a slice of bytes.
514     pub fn put_data(&mut self, data: &[u8]) {
515         self.data.extend_from_slice(data);
516 
517         // Post-invariant: as for `put1()`.
518     }
519 
520     /// Reserve appended space and return a mutable slice referring to it.
521     pub fn get_appended_space(&mut self, len: usize) -> &mut [u8] {
522         let off = self.data.len();
523         let new_len = self.data.len() + len;
524         self.data.resize(new_len, 0);
525         &mut self.data[off..]
526 
527         // Post-invariant: as for `put1()`.
528     }
529 
530     /// Align up to the given alignment.
531     pub fn align_to(&mut self, align_to: CodeOffset) {
532         trace!("MachBuffer: align to {}", align_to);
533         assert!(
534             align_to.is_power_of_two(),
535             "{align_to} is not a power of two"
536         );
537         while self.cur_offset() & (align_to - 1) != 0 {
538             self.put1(0);
539         }
540 
541         // Post-invariant: as for `put1()`.
542     }
543 
544     /// Begin a region of patchable code. There is one requirement for the
545     /// code that is emitted: It must not introduce any instructions that
546     /// could be chomped (branches are an example of this). In other words,
547     /// you must not call [`MachBuffer::add_cond_branch`] or
548     /// [`MachBuffer::add_uncond_branch`] between calls to this method and
549     /// [`MachBuffer::end_patchable`].
550     pub fn start_patchable(&mut self) -> OpenPatchRegion {
551         assert!(!self.open_patchable, "Patchable regions may not be nested");
552         self.open_patchable = true;
553         OpenPatchRegion(usize::try_from(self.cur_offset()).unwrap())
554     }
555 
556     /// End a region of patchable code, yielding a [`PatchRegion`] value that
557     /// can be consumed later to produce a one-off mutable slice to the
558     /// associated region of the data buffer.
559     pub fn end_patchable(&mut self, open: OpenPatchRegion) -> PatchRegion {
560         // No need to assert the state of `open_patchable` here, as we take
561         // ownership of the only `OpenPatchable` value.
562         self.open_patchable = false;
563         let end = usize::try_from(self.cur_offset()).unwrap();
564         PatchRegion { range: open.0..end }
565     }
566 
567     /// Allocate a `Label` to refer to some offset. May not be bound to a fixed
568     /// offset yet.
569     pub fn get_label(&mut self) -> MachLabel {
570         let l = self.label_offsets.len() as u32;
571         self.label_offsets.push(UNKNOWN_LABEL_OFFSET);
572         self.label_aliases.push(UNKNOWN_LABEL);
573         trace!("MachBuffer: new label -> {:?}", MachLabel(l));
574         MachLabel(l)
575 
576         // Post-invariant: the only mutation is to add a new label; it has no
577         // bound offset yet, so it trivially satisfies all invariants.
578     }
579 
580     /// Reserve the first N MachLabels for blocks.
581     pub fn reserve_labels_for_blocks(&mut self, blocks: usize) {
582         trace!("MachBuffer: first {} labels are for blocks", blocks);
583         debug_assert!(self.label_offsets.is_empty());
584         self.label_offsets.resize(blocks, UNKNOWN_LABEL_OFFSET);
585         self.label_aliases.resize(blocks, UNKNOWN_LABEL);
586 
587         // Post-invariant: as for `get_label()`.
588     }
589 
590     /// Registers metadata in this `MachBuffer` about the `constants` provided.
591     ///
592     /// This will record the size/alignment of all constants which will prepare
593     /// them for emission later on.
594     pub fn register_constants(&mut self, constants: &VCodeConstants) {
595         for (c, val) in constants.iter() {
596             self.register_constant(&c, val);
597         }
598     }
599 
600     /// Similar to [`MachBuffer::register_constants`] but registers a
601     /// single constant metadata. This function is useful in
602     /// situations where not all constants are known at the time of
603     /// emission.
604     pub fn register_constant(&mut self, constant: &VCodeConstant, data: &VCodeConstantData) {
605         let c2 = self.constants.push(MachBufferConstant {
606             upcoming_label: None,
607             align: data.alignment(),
608             size: data.as_slice().len(),
609         });
610         assert_eq!(*constant, c2);
611     }
612 
613     /// Completes constant emission by iterating over `self.used_constants` and
614     /// filling in the "holes" with the constant values provided by `constants`.
615     ///
616     /// Returns the alignment required for this entire buffer. Alignment starts
617     /// at the ISA's minimum function alignment and can be increased due to
618     /// constant requirements.
619     fn finish_constants(&mut self, constants: &VCodeConstants) -> u32 {
620         let mut alignment = self.min_alignment;
621         for (constant, offset) in mem::take(&mut self.used_constants) {
622             let constant = constants.get(constant);
623             let data = constant.as_slice();
624             self.data[offset as usize..][..data.len()].copy_from_slice(data);
625             alignment = constant.alignment().max(alignment);
626         }
627         alignment
628     }
629 
630     /// Returns a label that can be used to refer to the `constant` provided.
631     ///
632     /// This will automatically defer a new constant to be emitted for
633     /// `constant` if it has not been previously emitted. Note that this
634     /// function may return a different label for the same constant at
635     /// different points in time. The label is valid to use only from the
636     /// current location; the MachBuffer takes care to emit the same constant
637     /// multiple times if needed so the constant is always in range.
638     pub fn get_label_for_constant(&mut self, constant: VCodeConstant) -> MachLabel {
639         let MachBufferConstant {
640             align,
641             size,
642             upcoming_label,
643         } = self.constants[constant];
644         if let Some(label) = upcoming_label {
645             return label;
646         }
647 
648         let label = self.get_label();
649         trace!(
650             "defer constant: eventually emit {size} bytes aligned \
651              to {align} at label {label:?}",
652         );
653         self.pending_constants.push(constant);
654         self.pending_constants_size += size as u32;
655         self.constants[constant].upcoming_label = Some(label);
656         label
657     }
658 
659     /// Bind a label to the current offset. A label can only be bound once.
660     pub fn bind_label(&mut self, label: MachLabel, ctrl_plane: &mut ControlPlane) {
661         trace!(
662             "MachBuffer: bind label {:?} at offset {}",
663             label,
664             self.cur_offset()
665         );
666         debug_assert_eq!(self.label_offsets[label.0 as usize], UNKNOWN_LABEL_OFFSET);
667         debug_assert_eq!(self.label_aliases[label.0 as usize], UNKNOWN_LABEL);
668         let offset = self.cur_offset();
669         self.label_offsets[label.0 as usize] = offset;
670         self.lazily_clear_labels_at_tail();
671         self.labels_at_tail.push(label);
672 
673         // Invariants hold: bound offset of label is <= cur_offset (in fact it
674         // is equal). If the `labels_at_tail` list was complete and precise
675         // before, it is still, because we have bound this label to the current
676         // offset and added it to the list (which contains all labels at the
677         // current offset).
678 
679         self.optimize_branches(ctrl_plane);
680 
681         // Post-invariant: by `optimize_branches()` (see argument there).
682     }
683 
684     /// Lazily clear `labels_at_tail` if the tail offset has moved beyond the
685     /// offset that it applies to.
686     fn lazily_clear_labels_at_tail(&mut self) {
687         let offset = self.cur_offset();
688         if offset > self.labels_at_tail_off {
689             self.labels_at_tail_off = offset;
690             self.labels_at_tail.clear();
691         }
692 
693         // Post-invariant: either labels_at_tail_off was at cur_offset, and
694         // state is untouched, or was less than cur_offset, in which case the
695         // labels_at_tail list was conceptually empty, and is now actually
696         // empty.
697     }
698 
699     /// Resolve a label to an offset, if known. May return `UNKNOWN_LABEL_OFFSET`.
700     pub(crate) fn resolve_label_offset(&self, mut label: MachLabel) -> CodeOffset {
701         let mut iters = 0;
702         while self.label_aliases[label.0 as usize] != UNKNOWN_LABEL {
703             label = self.label_aliases[label.0 as usize];
704             // To protect against an infinite loop (despite our assurances to
705             // ourselves that the invariants make this impossible), assert out
706             // after 1M iterations. The number of basic blocks is limited
707             // in most contexts anyway so this should be impossible to hit with
708             // a legitimate input.
709             iters += 1;
710             assert!(iters < 1_000_000, "Unexpected cycle in label aliases");
711         }
712         self.label_offsets[label.0 as usize]
713 
714         // Post-invariant: no mutations.
715     }
716 
717     /// Emit a reference to the given label with the given reference type (i.e.,
718     /// branch-instruction format) at the current offset.  This is like a
719     /// relocation, but handled internally.
720     ///
721     /// This can be called before the branch is actually emitted; fixups will
722     /// not happen until an island is emitted or the buffer is finished.
723     pub fn use_label_at_offset(&mut self, offset: CodeOffset, label: MachLabel, kind: I::LabelUse) {
724         trace!(
725             "MachBuffer: use_label_at_offset: offset {} label {:?} kind {:?}",
726             offset,
727             label,
728             kind
729         );
730 
731         // Add the fixup, and update the worst-case island size based on a
732         // veneer for this label use.
733         let fixup = MachLabelFixup {
734             label,
735             offset,
736             kind,
737         };
738         self.pending_fixup_deadline = self.pending_fixup_deadline.min(fixup.deadline());
739         self.pending_fixup_records.push(fixup);
740 
741         // Post-invariant: no mutations to branches/labels data structures.
742     }
743 
744     /// Inform the buffer of an unconditional branch at the given offset,
745     /// targeting the given label. May be used to optimize branches.
746     /// The last added label-use must correspond to this branch.
747     /// This must be called when the current offset is equal to `start`; i.e.,
748     /// before actually emitting the branch. This implies that for a branch that
749     /// uses a label and is eligible for optimizations by the MachBuffer, the
750     /// proper sequence is:
751     ///
752     /// - Call `use_label_at_offset()` to emit the fixup record.
753     /// - Call `add_uncond_branch()` to make note of the branch.
754     /// - Emit the bytes for the branch's machine code.
755     ///
756     /// Additional requirement: no labels may be bound between `start` and `end`
757     /// (exclusive on both ends).
758     pub fn add_uncond_branch(&mut self, start: CodeOffset, end: CodeOffset, target: MachLabel) {
759         debug_assert!(
760             !self.open_patchable,
761             "Branch instruction inserted within a patchable region"
762         );
763         assert!(self.cur_offset() == start);
764         debug_assert!(end > start);
765         assert!(!self.pending_fixup_records.is_empty());
766         let fixup = self.pending_fixup_records.len() - 1;
767         self.lazily_clear_labels_at_tail();
768         self.latest_branches.push(MachBranch {
769             start,
770             end,
771             target,
772             fixup,
773             inverted: None,
774             labels_at_this_branch: self.labels_at_tail.clone(),
775         });
776 
777         // Post-invariant: we asserted branch start is current tail; the list of
778         // labels at branch is cloned from list of labels at current tail.
779     }
780 
781     /// Inform the buffer of a conditional branch at the given offset,
782     /// targeting the given label. May be used to optimize branches.
783     /// The last added label-use must correspond to this branch.
784     ///
785     /// Additional requirement: no labels may be bound between `start` and `end`
786     /// (exclusive on both ends).
787     pub fn add_cond_branch(
788         &mut self,
789         start: CodeOffset,
790         end: CodeOffset,
791         target: MachLabel,
792         inverted: &[u8],
793     ) {
794         debug_assert!(
795             !self.open_patchable,
796             "Branch instruction inserted within a patchable region"
797         );
798         assert!(self.cur_offset() == start);
799         debug_assert!(end > start);
800         assert!(!self.pending_fixup_records.is_empty());
801         debug_assert!(
802             inverted.len() == (end - start) as usize,
803             "branch length = {}, but inverted length = {}",
804             end - start,
805             inverted.len()
806         );
807         let fixup = self.pending_fixup_records.len() - 1;
808         let inverted = Some(SmallVec::from(inverted));
809         self.lazily_clear_labels_at_tail();
810         self.latest_branches.push(MachBranch {
811             start,
812             end,
813             target,
814             fixup,
815             inverted,
816             labels_at_this_branch: self.labels_at_tail.clone(),
817         });
818 
819         // Post-invariant: we asserted branch start is current tail; labels at
820         // branch list is cloned from list of labels at current tail.
821     }
822 
823     fn truncate_last_branch(&mut self) {
824         debug_assert!(
825             !self.open_patchable,
826             "Branch instruction truncated within a patchable region"
827         );
828 
829         self.lazily_clear_labels_at_tail();
830         // Invariants hold at this point.
831 
832         let b = self.latest_branches.pop().unwrap();
833         assert!(b.end == self.cur_offset());
834 
835         // State:
836         //    [PRE CODE]
837         //  Offset b.start, b.labels_at_this_branch:
838         //    [BRANCH CODE]
839         //  cur_off, self.labels_at_tail -->
840         //    (end of buffer)
841         self.data.truncate(b.start as usize);
842         self.pending_fixup_records.truncate(b.fixup);
843         while let Some(last_srcloc) = self.srclocs.last_mut() {
844             if last_srcloc.end <= b.start {
845                 break;
846             }
847             if last_srcloc.start < b.start {
848                 last_srcloc.end = b.start;
849                 break;
850             }
851             self.srclocs.pop();
852         }
853         // State:
854         //    [PRE CODE]
855         //  cur_off, Offset b.start, b.labels_at_this_branch:
856         //    (end of buffer)
857         //
858         //  self.labels_at_tail -->  (past end of buffer)
859         let cur_off = self.cur_offset();
860         self.labels_at_tail_off = cur_off;
861         // State:
862         //    [PRE CODE]
863         //  cur_off, Offset b.start, b.labels_at_this_branch,
864         //  self.labels_at_tail:
865         //    (end of buffer)
866         //
867         // resolve_label_offset(l) for l in labels_at_tail:
868         //    (past end of buffer)
869 
870         trace!(
871             "truncate_last_branch: truncated {:?}; off now {}",
872             b,
873             cur_off
874         );
875 
876         // Fix up resolved label offsets for labels at tail.
877         for &l in &self.labels_at_tail {
878             self.label_offsets[l.0 as usize] = cur_off;
879         }
880         // Old labels_at_this_branch are now at cur_off.
881         self.labels_at_tail
882             .extend(b.labels_at_this_branch.into_iter());
883 
884         // Post-invariant: this operation is defined to truncate the buffer,
885         // which moves cur_off backward, and to move labels at the end of the
886         // buffer back to the start-of-branch offset.
887         //
888         // latest_branches satisfies all invariants:
889         // - it has no branches past the end of the buffer (branches are in
890         //   order, we removed the last one, and we truncated the buffer to just
891         //   before the start of that branch)
892         // - no labels were moved to lower offsets than the (new) cur_off, so
893         //   the labels_at_this_branch list for any other branch need not change.
894         //
895         // labels_at_tail satisfies all invariants:
896         // - all labels that were at the tail after the truncated branch are
897         //   moved backward to just before the branch, which becomes the new tail;
898         //   thus every element in the list should remain (ensured by `.extend()`
899         //   above).
900         // - all labels that refer to the new tail, which is the start-offset of
901         //   the truncated branch, must be present. The `labels_at_this_branch`
902         //   list in the truncated branch's record is a complete and precise list
903         //   of exactly these labels; we append these to labels_at_tail.
904         // - labels_at_tail_off is at cur_off after truncation occurs, so the
905         //   list is valid (not to be lazily cleared).
906         //
907         // The stated operation was performed:
908         // - For each label at the end of the buffer prior to this method, it
909         //   now resolves to the new (truncated) end of the buffer: it must have
910         //   been in `labels_at_tail` (this list is precise and complete, and
911         //   the tail was at the end of the truncated branch on entry), and we
912         //   iterate over this list and set `label_offsets` to the new tail.
913         //   None of these labels could have been an alias (by invariant), so
914         //   `label_offsets` is authoritative for each.
915         // - No other labels will be past the end of the buffer, because of the
916         //   requirement that no labels be bound to the middle of branch ranges
917         //   (see comments to `add_{cond,uncond}_branch()`).
918         // - The buffer is truncated to just before the last branch, and the
919         //   fixup record referring to that last branch is removed.
920     }
921 
922     /// Performs various optimizations on branches pointing at the current label.
923     pub fn optimize_branches(&mut self, ctrl_plane: &mut ControlPlane) {
924         if ctrl_plane.get_decision() {
925             return;
926         }
927 
928         self.lazily_clear_labels_at_tail();
929         // Invariants valid at this point.
930 
931         trace!(
932             "enter optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}",
933             self.latest_branches,
934             self.labels_at_tail,
935             self.pending_fixup_records
936         );
937 
938         // We continue to munch on branches at the tail of the buffer until no
939         // more rules apply. Note that the loop only continues if a branch is
940         // actually truncated (or if labels are redirected away from a branch),
941         // so this always makes progress.
942         while let Some(b) = self.latest_branches.last() {
943             let cur_off = self.cur_offset();
944             trace!("optimize_branches: last branch {:?} at off {}", b, cur_off);
945             // If there has been any code emission since the end of the last branch or
946             // label definition, then there's nothing we can edit (because we
947             // don't move code once placed, only back up and overwrite), so
948             // clear the records and finish.
949             if b.end < cur_off {
950                 break;
951             }
952 
953             // If the "labels at this branch" list on this branch is
954             // longer than a threshold, don't do any simplification,
955             // and let the branch remain to separate those labels from
956             // the current tail. This avoids quadratic behavior (see
957             // #3468): otherwise, if a long string of "goto next;
958             // next:" patterns are emitted, all of the labels will
959             // coalesce into a long list of aliases for the current
960             // buffer tail. We must track all aliases of the current
961             // tail for correctness, but we are also allowed to skip
962             // optimization (removal) of any branch, so we take the
963             // escape hatch here and let it stand. In effect this
964             // "spreads" the many thousands of labels in the
965             // pathological case among an actual (harmless but
966             // suboptimal) instruction once per N labels.
967             if b.labels_at_this_branch.len() > LABEL_LIST_THRESHOLD {
968                 break;
969             }
970 
971             // Invariant: we are looking at a branch that ends at the tail of
972             // the buffer.
973 
974             // For any branch, conditional or unconditional:
975             // - If the target is a label at the current offset, then remove
976             //   the conditional branch, and reset all labels that targeted
977             //   the current offset (end of branch) to the truncated
978             //   end-of-code.
979             //
980             // Preserves execution semantics: a branch to its own fallthrough
981             // address is equivalent to a no-op; in both cases, nextPC is the
982             // fallthrough.
983             if self.resolve_label_offset(b.target) == cur_off {
984                 trace!("branch with target == cur off; truncating");
985                 self.truncate_last_branch();
986                 continue;
987             }
988 
989             // If latest is an unconditional branch:
990             //
991             // - If the branch's target is not its own start address, then for
992             //   each label at the start of branch, make the label an alias of the
993             //   branch target, and remove the label from the "labels at this
994             //   branch" list.
995             //
996             //   - Preserves execution semantics: an unconditional branch's
997             //     only effect is to set PC to a new PC; this change simply
998             //     collapses one step in the step-semantics.
999             //
1000             //   - Post-invariant: the labels that were bound to the start of
1001             //     this branch become aliases, so they must not be present in any
1002             //     labels-at-this-branch list or the labels-at-tail list. The
1003             //     labels are removed form the latest-branch record's
1004             //     labels-at-this-branch list, and are never placed in the
1005             //     labels-at-tail list. Furthermore, it is correct that they are
1006             //     not in either list, because they are now aliases, and labels
1007             //     that are aliases remain aliases forever.
1008             //
1009             // - If there is a prior unconditional branch that ends just before
1010             //   this one begins, and this branch has no labels bound to its
1011             //   start, then we can truncate this branch, because it is entirely
1012             //   unreachable (we have redirected all labels that make it
1013             //   reachable otherwise). Do so and continue around the loop.
1014             //
1015             //   - Preserves execution semantics: the branch is unreachable,
1016             //     because execution can only flow into an instruction from the
1017             //     prior instruction's fallthrough or from a branch bound to that
1018             //     instruction's start offset. Unconditional branches have no
1019             //     fallthrough, so if the prior instruction is an unconditional
1020             //     branch, no fallthrough entry can happen. The
1021             //     labels-at-this-branch list is complete (by invariant), so if it
1022             //     is empty, then the instruction is entirely unreachable. Thus,
1023             //     it can be removed.
1024             //
1025             //   - Post-invariant: ensured by truncate_last_branch().
1026             //
1027             // - If there is a prior conditional branch whose target label
1028             //   resolves to the current offset (branches around the
1029             //   unconditional branch), then remove the unconditional branch,
1030             //   and make the target of the unconditional the target of the
1031             //   conditional instead.
1032             //
1033             //   - Preserves execution semantics: previously we had:
1034             //
1035             //         L1:
1036             //            cond_br L2
1037             //            br L3
1038             //         L2:
1039             //            (end of buffer)
1040             //
1041             //     by removing the last branch, we have:
1042             //
1043             //         L1:
1044             //            cond_br L2
1045             //         L2:
1046             //            (end of buffer)
1047             //
1048             //     we then fix up the records for the conditional branch to
1049             //     have:
1050             //
1051             //         L1:
1052             //           cond_br.inverted L3
1053             //         L2:
1054             //
1055             //     In the original code, control flow reaches L2 when the
1056             //     conditional branch's predicate is true, and L3 otherwise. In
1057             //     the optimized code, the same is true.
1058             //
1059             //   - Post-invariant: all edits to latest_branches and
1060             //     labels_at_tail are performed by `truncate_last_branch()`,
1061             //     which maintains the invariants at each step.
1062 
1063             if b.is_uncond() {
1064                 // Set any label equal to current branch's start as an alias of
1065                 // the branch's target, if the target is not the branch itself
1066                 // (i.e., an infinite loop).
1067                 //
1068                 // We cannot perform this aliasing if the target of this branch
1069                 // ultimately aliases back here; if so, we need to keep this
1070                 // branch, so break out of this loop entirely (and clear the
1071                 // latest-branches list below).
1072                 //
1073                 // Note that this check is what prevents cycles from forming in
1074                 // `self.label_aliases`. To see why, consider an arbitrary start
1075                 // state:
1076                 //
1077                 // label_aliases[L1] = L2, label_aliases[L2] = L3, ..., up to
1078                 // Ln, which is not aliased.
1079                 //
1080                 // We would create a cycle if we assigned label_aliases[Ln]
1081                 // = L1.  Note that the below assignment is the only write
1082                 // to label_aliases.
1083                 //
1084                 // By our other invariants, we have that Ln (`l` below)
1085                 // resolves to the offset `b.start`, because it is in the
1086                 // set `b.labels_at_this_branch`.
1087                 //
1088                 // If L1 were already aliased, through some arbitrarily deep
1089                 // chain, to Ln, then it must also resolve to this offset
1090                 // `b.start`.
1091                 //
1092                 // By checking the resolution of `L1` against this offset,
1093                 // and aborting this branch-simplification if they are
1094                 // equal, we prevent the below assignment from ever creating
1095                 // a cycle.
1096                 if self.resolve_label_offset(b.target) != b.start {
1097                     let redirected = b.labels_at_this_branch.len();
1098                     for &l in &b.labels_at_this_branch {
1099                         trace!(
1100                             " -> label at start of branch {:?} redirected to target {:?}",
1101                             l,
1102                             b.target
1103                         );
1104                         self.label_aliases[l.0 as usize] = b.target;
1105                         // NOTE: we continue to ensure the invariant that labels
1106                         // pointing to tail of buffer are in `labels_at_tail`
1107                         // because we already ensured above that the last branch
1108                         // cannot have a target of `cur_off`; so we never have
1109                         // to put the label into `labels_at_tail` when moving it
1110                         // here.
1111                     }
1112                     // Maintain invariant: all branches have been redirected
1113                     // and are no longer pointing at the start of this branch.
1114                     let mut_b = self.latest_branches.last_mut().unwrap();
1115                     mut_b.labels_at_this_branch.clear();
1116 
1117                     if redirected > 0 {
1118                         trace!(" -> after label redirects, restarting loop");
1119                         continue;
1120                     }
1121                 } else {
1122                     break;
1123                 }
1124 
1125                 let b = self.latest_branches.last().unwrap();
1126 
1127                 // Examine any immediately preceding branch.
1128                 if self.latest_branches.len() > 1 {
1129                     let prev_b = &self.latest_branches[self.latest_branches.len() - 2];
1130                     trace!(" -> more than one branch; prev_b = {:?}", prev_b);
1131                     // This uncond is immediately after another uncond; we
1132                     // should have already redirected labels to this uncond away
1133                     // (but check to be sure); so we can truncate this uncond.
1134                     if prev_b.is_uncond()
1135                         && prev_b.end == b.start
1136                         && b.labels_at_this_branch.is_empty()
1137                     {
1138                         trace!(" -> uncond follows another uncond; truncating");
1139                         self.truncate_last_branch();
1140                         continue;
1141                     }
1142 
1143                     // This uncond is immediately after a conditional, and the
1144                     // conditional's target is the end of this uncond, and we've
1145                     // already redirected labels to this uncond away; so we can
1146                     // truncate this uncond, flip the sense of the conditional, and
1147                     // set the conditional's target (in `latest_branches` and in
1148                     // `fixup_records`) to the uncond's target.
1149                     if prev_b.is_cond()
1150                         && prev_b.end == b.start
1151                         && self.resolve_label_offset(prev_b.target) == cur_off
1152                     {
1153                         trace!(" -> uncond follows a conditional, and conditional's target resolves to current offset");
1154                         // Save the target of the uncond (this becomes the
1155                         // target of the cond), and truncate the uncond.
1156                         let target = b.target;
1157                         let data = prev_b.inverted.clone().unwrap();
1158                         self.truncate_last_branch();
1159 
1160                         // Mutate the code and cond branch.
1161                         let off_before_edit = self.cur_offset();
1162                         let prev_b = self.latest_branches.last_mut().unwrap();
1163                         let not_inverted = SmallVec::from(
1164                             &self.data[(prev_b.start as usize)..(prev_b.end as usize)],
1165                         );
1166 
1167                         // Low-level edit: replaces bytes of branch with
1168                         // inverted form. cur_off remains the same afterward, so
1169                         // we do not need to modify label data structures.
1170                         self.data.truncate(prev_b.start as usize);
1171                         self.data.extend_from_slice(&data[..]);
1172 
1173                         // Save the original code as the inversion of the
1174                         // inverted branch, in case we later edit this branch
1175                         // again.
1176                         prev_b.inverted = Some(not_inverted);
1177                         self.pending_fixup_records[prev_b.fixup].label = target;
1178                         trace!(" -> reassigning target of condbr to {:?}", target);
1179                         prev_b.target = target;
1180                         debug_assert_eq!(off_before_edit, self.cur_offset());
1181                         continue;
1182                     }
1183                 }
1184             }
1185 
1186             // If we couldn't do anything with the last branch, then break.
1187             break;
1188         }
1189 
1190         self.purge_latest_branches();
1191 
1192         trace!(
1193             "leave optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}",
1194             self.latest_branches,
1195             self.labels_at_tail,
1196             self.pending_fixup_records
1197         );
1198     }
1199 
1200     fn purge_latest_branches(&mut self) {
1201         // All of our branch simplification rules work only if a branch ends at
1202         // the tail of the buffer, with no following code; and branches are in
1203         // order in latest_branches; so if the last entry ends prior to
1204         // cur_offset, then clear all entries.
1205         let cur_off = self.cur_offset();
1206         if let Some(l) = self.latest_branches.last() {
1207             if l.end < cur_off {
1208                 trace!("purge_latest_branches: removing branch {:?}", l);
1209                 self.latest_branches.clear();
1210             }
1211         }
1212 
1213         // Post-invariant: no invariant requires any branch to appear in
1214         // `latest_branches`; it is always optional. The list-clear above thus
1215         // preserves all semantics.
1216     }
1217 
1218     /// Emit a trap at some point in the future with the specified code and
1219     /// stack map.
1220     ///
1221     /// This function returns a [`MachLabel`] which will be the future address
1222     /// of the trap. Jumps should refer to this label, likely by using the
1223     /// [`MachBuffer::use_label_at_offset`] method, to get a relocation
1224     /// patched in once the address of the trap is known.
1225     ///
1226     /// This will batch all traps into the end of the function.
1227     pub fn defer_trap(&mut self, code: TrapCode) -> MachLabel {
1228         let label = self.get_label();
1229         self.pending_traps.push(MachLabelTrap {
1230             label,
1231             code,
1232             loc: self.cur_srcloc.map(|(_start, loc)| loc),
1233         });
1234         label
1235     }
1236 
1237     /// Is an island needed within the next N bytes?
1238     pub fn island_needed(&self, distance: CodeOffset) -> bool {
1239         let deadline = match self.fixup_records.peek() {
1240             Some(fixup) => fixup.deadline().min(self.pending_fixup_deadline),
1241             None => self.pending_fixup_deadline,
1242         };
1243         deadline < u32::MAX && self.worst_case_end_of_island(distance) > deadline
1244     }
1245 
1246     /// Returns the maximal offset that islands can reach if `distance` more
1247     /// bytes are appended.
1248     ///
1249     /// This is used to determine if veneers need insertions since jumps that
1250     /// can't reach past this point must get a veneer of some form.
1251     fn worst_case_end_of_island(&self, distance: CodeOffset) -> CodeOffset {
1252         // Assume that all fixups will require veneers and that the veneers are
1253         // the worst-case size for each platform. This is an over-generalization
1254         // to avoid iterating over the `fixup_records` list or maintaining
1255         // information about it as we go along.
1256         let island_worst_case_size = ((self.fixup_records.len() + self.pending_fixup_records.len())
1257             as u32)
1258             * (I::LabelUse::worst_case_veneer_size())
1259             + self.pending_constants_size
1260             + (self.pending_traps.len() * I::TRAP_OPCODE.len()) as u32;
1261         self.cur_offset()
1262             .saturating_add(distance)
1263             .saturating_add(island_worst_case_size)
1264     }
1265 
1266     /// Emit all pending constants and required pending veneers.
1267     ///
1268     /// Should only be called if `island_needed()` returns true, i.e., if we
1269     /// actually reach a deadline. It's not necessarily a problem to do so
1270     /// otherwise but it may result in unnecessary work during emission.
1271     pub fn emit_island(&mut self, distance: CodeOffset, ctrl_plane: &mut ControlPlane) {
1272         self.emit_island_maybe_forced(ForceVeneers::No, distance, ctrl_plane);
1273     }
1274 
1275     /// Same as `emit_island`, but an internal API with a `force_veneers`
1276     /// argument to force all veneers to always get emitted for debugging.
1277     fn emit_island_maybe_forced(
1278         &mut self,
1279         force_veneers: ForceVeneers,
1280         distance: CodeOffset,
1281         ctrl_plane: &mut ControlPlane,
1282     ) {
1283         // We're going to purge fixups, so no latest-branch editing can happen
1284         // anymore.
1285         self.latest_branches.clear();
1286 
1287         // End the current location tracking since anything emitted during this
1288         // function shouldn't be attributed to whatever the current source
1289         // location is.
1290         //
1291         // Note that the current source location, if it's set right now, will be
1292         // restored at the end of this island emission.
1293         let cur_loc = self.cur_srcloc.map(|(_, loc)| loc);
1294         if cur_loc.is_some() {
1295             self.end_srcloc();
1296         }
1297 
1298         let forced_threshold = self.worst_case_end_of_island(distance);
1299 
1300         // First flush out all traps/constants so we have more labels in case
1301         // fixups are applied against these labels.
1302         //
1303         // Note that traps are placed first since this typically happens at the
1304         // end of the function and for disassemblers we try to keep all the code
1305         // contiguously together.
1306         for MachLabelTrap { label, code, loc } in mem::take(&mut self.pending_traps) {
1307             // If this trap has source information associated with it then
1308             // emit this information for the trap instruction going out now too.
1309             if let Some(loc) = loc {
1310                 self.start_srcloc(loc);
1311             }
1312             self.align_to(I::LabelUse::ALIGN);
1313             self.bind_label(label, ctrl_plane);
1314             self.add_trap(code);
1315             self.put_data(I::TRAP_OPCODE);
1316             if loc.is_some() {
1317                 self.end_srcloc();
1318             }
1319         }
1320 
1321         for constant in mem::take(&mut self.pending_constants) {
1322             let MachBufferConstant { align, size, .. } = self.constants[constant];
1323             let label = self.constants[constant].upcoming_label.take().unwrap();
1324             self.align_to(align);
1325             self.bind_label(label, ctrl_plane);
1326             self.used_constants.push((constant, self.cur_offset()));
1327             self.get_appended_space(size);
1328         }
1329 
1330         // Either handle all pending fixups because they're ready or move them
1331         // onto the `BinaryHeap` tracking all pending fixups if they aren't
1332         // ready.
1333         assert!(self.latest_branches.is_empty());
1334         for fixup in mem::take(&mut self.pending_fixup_records) {
1335             if self.should_apply_fixup(&fixup, forced_threshold) {
1336                 self.handle_fixup(fixup, force_veneers, forced_threshold);
1337             } else {
1338                 self.fixup_records.push(fixup);
1339             }
1340         }
1341         self.pending_fixup_deadline = u32::MAX;
1342         while let Some(fixup) = self.fixup_records.peek() {
1343             trace!("emit_island: fixup {:?}", fixup);
1344 
1345             // If this fixup shouldn't be applied, that means its label isn't
1346             // defined yet and there'll be remaining space to apply a veneer if
1347             // necessary in the future after this island. In that situation
1348             // because `fixup_records` is sorted by deadline this loop can
1349             // exit.
1350             if !self.should_apply_fixup(fixup, forced_threshold) {
1351                 break;
1352             }
1353 
1354             let fixup = self.fixup_records.pop().unwrap();
1355             self.handle_fixup(fixup, force_veneers, forced_threshold);
1356         }
1357 
1358         if let Some(loc) = cur_loc {
1359             self.start_srcloc(loc);
1360         }
1361     }
1362 
1363     fn should_apply_fixup(&self, fixup: &MachLabelFixup<I>, forced_threshold: CodeOffset) -> bool {
1364         let label_offset = self.resolve_label_offset(fixup.label);
1365         label_offset != UNKNOWN_LABEL_OFFSET || fixup.deadline() < forced_threshold
1366     }
1367 
1368     fn handle_fixup(
1369         &mut self,
1370         fixup: MachLabelFixup<I>,
1371         force_veneers: ForceVeneers,
1372         forced_threshold: CodeOffset,
1373     ) {
1374         let MachLabelFixup {
1375             label,
1376             offset,
1377             kind,
1378         } = fixup;
1379         let start = offset as usize;
1380         let end = (offset + kind.patch_size()) as usize;
1381         let label_offset = self.resolve_label_offset(label);
1382 
1383         if label_offset != UNKNOWN_LABEL_OFFSET {
1384             // If the offset of the label for this fixup is known then
1385             // we're going to do something here-and-now. We're either going
1386             // to patch the original offset because it's an in-bounds jump,
1387             // or we're going to generate a veneer, patch the fixup to jump
1388             // to the veneer, and then keep going.
1389             //
1390             // If the label comes after the original fixup, then we should
1391             // be guaranteed that the jump is in-bounds. Otherwise there's
1392             // a bug somewhere because this method wasn't called soon
1393             // enough. All forward-jumps are tracked and should get veneers
1394             // before their deadline comes and they're unable to jump
1395             // further.
1396             //
1397             // Otherwise if the label is before the fixup, then that's a
1398             // backwards jump. If it's past the maximum negative range
1399             // then we'll emit a veneer that to jump forward to which can
1400             // then jump backwards.
1401             let veneer_required = if label_offset >= offset {
1402                 assert!((label_offset - offset) <= kind.max_pos_range());
1403                 false
1404             } else {
1405                 (offset - label_offset) > kind.max_neg_range()
1406             };
1407             trace!(
1408                 " -> label_offset = {}, known, required = {} (pos {} neg {})",
1409                 label_offset,
1410                 veneer_required,
1411                 kind.max_pos_range(),
1412                 kind.max_neg_range()
1413             );
1414 
1415             if (force_veneers == ForceVeneers::Yes && kind.supports_veneer()) || veneer_required {
1416                 self.emit_veneer(label, offset, kind);
1417             } else {
1418                 let slice = &mut self.data[start..end];
1419                 trace!("patching in-range! slice = {slice:?}; offset = {offset:#x}; label_offset = {label_offset:#x}");
1420                 kind.patch(slice, offset, label_offset);
1421             }
1422         } else {
1423             // If the offset of this label is not known at this time then
1424             // that means that a veneer is required because after this
1425             // island the target can't be in range of the original target.
1426             assert!(forced_threshold - offset > kind.max_pos_range());
1427             self.emit_veneer(label, offset, kind);
1428         }
1429     }
1430 
1431     /// Emits a "veneer" the `kind` code at `offset` to jump to `label`.
1432     ///
1433     /// This will generate extra machine code, using `kind`, to get a
1434     /// larger-jump-kind than `kind` allows. The code at `offset` is then
1435     /// patched to jump to our new code, and then the new code is enqueued for
1436     /// a fixup to get processed at some later time.
1437     fn emit_veneer(&mut self, label: MachLabel, offset: CodeOffset, kind: I::LabelUse) {
1438         // If this `kind` doesn't support a veneer then that's a bug in the
1439         // backend because we need to implement support for such a veneer.
1440         assert!(
1441             kind.supports_veneer(),
1442             "jump beyond the range of {kind:?} but a veneer isn't supported",
1443         );
1444 
1445         // Allocate space for a veneer in the island.
1446         self.align_to(I::LabelUse::ALIGN);
1447         let veneer_offset = self.cur_offset();
1448         trace!("making a veneer at {}", veneer_offset);
1449         let start = offset as usize;
1450         let end = (offset + kind.patch_size()) as usize;
1451         let slice = &mut self.data[start..end];
1452         // Patch the original label use to refer to the veneer.
1453         trace!(
1454             "patching original at offset {} to veneer offset {}",
1455             offset,
1456             veneer_offset
1457         );
1458         kind.patch(slice, offset, veneer_offset);
1459         // Generate the veneer.
1460         let veneer_slice = self.get_appended_space(kind.veneer_size() as usize);
1461         let (veneer_fixup_off, veneer_label_use) =
1462             kind.generate_veneer(veneer_slice, veneer_offset);
1463         trace!(
1464             "generated veneer; fixup offset {}, label_use {:?}",
1465             veneer_fixup_off,
1466             veneer_label_use
1467         );
1468         // Register a new use of `label` with our new veneer fixup and
1469         // offset. This'll recalculate deadlines accordingly and
1470         // enqueue this fixup to get processed at some later
1471         // time.
1472         self.use_label_at_offset(veneer_fixup_off, label, veneer_label_use);
1473     }
1474 
1475     fn finish_emission_maybe_forcing_veneers(
1476         &mut self,
1477         force_veneers: ForceVeneers,
1478         ctrl_plane: &mut ControlPlane,
1479     ) {
1480         while !self.pending_constants.is_empty()
1481             || !self.pending_traps.is_empty()
1482             || !self.fixup_records.is_empty()
1483             || !self.pending_fixup_records.is_empty()
1484         {
1485             // `emit_island()` will emit any pending veneers and constants, and
1486             // as a side-effect, will also take care of any fixups with resolved
1487             // labels eagerly.
1488             self.emit_island_maybe_forced(force_veneers, u32::MAX, ctrl_plane);
1489         }
1490 
1491         // Ensure that all labels have been fixed up after the last island is emitted. This is a
1492         // full (release-mode) assert because an unresolved label means the emitted code is
1493         // incorrect.
1494         assert!(self.fixup_records.is_empty());
1495         assert!(self.pending_fixup_records.is_empty());
1496     }
1497 
1498     /// Finish any deferred emissions and/or fixups.
1499     pub fn finish(
1500         mut self,
1501         constants: &VCodeConstants,
1502         ctrl_plane: &mut ControlPlane,
1503     ) -> MachBufferFinalized<Stencil> {
1504         let _tt = timing::vcode_emit_finish();
1505 
1506         self.finish_emission_maybe_forcing_veneers(ForceVeneers::No, ctrl_plane);
1507 
1508         let alignment = self.finish_constants(constants);
1509 
1510         // Resolve all labels to their offsets.
1511         let finalized_relocs = self
1512             .relocs
1513             .iter()
1514             .map(|reloc| FinalizedMachReloc {
1515                 offset: reloc.offset,
1516                 kind: reloc.kind,
1517                 addend: reloc.addend,
1518                 target: match &reloc.target {
1519                     RelocTarget::ExternalName(name) => {
1520                         FinalizedRelocTarget::ExternalName(name.clone())
1521                     }
1522                     RelocTarget::Label(label) => {
1523                         FinalizedRelocTarget::Func(self.resolve_label_offset(*label))
1524                     }
1525                 },
1526             })
1527             .collect();
1528 
1529         let exception_handlers = self
1530             .exception_handlers
1531             .iter()
1532             .map(|&(off, tag, target)| (off, tag, self.resolve_label_offset(target)))
1533             .collect();
1534 
1535         let mut srclocs = self.srclocs;
1536         srclocs.sort_by_key(|entry| entry.start);
1537 
1538         MachBufferFinalized {
1539             data: self.data,
1540             relocs: finalized_relocs,
1541             traps: self.traps,
1542             call_sites: self.call_sites,
1543             srclocs,
1544             user_stack_maps: self.user_stack_maps,
1545             unwind_info: self.unwind_info,
1546             exception_handlers,
1547             alignment,
1548         }
1549     }
1550 
1551     /// Add an external relocation at the given offset.
1552     pub fn add_reloc_at_offset<T: Into<RelocTarget> + Clone>(
1553         &mut self,
1554         offset: CodeOffset,
1555         kind: Reloc,
1556         target: &T,
1557         addend: Addend,
1558     ) {
1559         let target: RelocTarget = target.clone().into();
1560         // FIXME(#3277): This should use `I::LabelUse::from_reloc` to optionally
1561         // generate a label-use statement to track whether an island is possibly
1562         // needed to escape this function to actually get to the external name.
1563         // This is most likely to come up on AArch64 where calls between
1564         // functions use a 26-bit signed offset which gives +/- 64MB. This means
1565         // that if a function is 128MB in size and there's a call in the middle
1566         // it's impossible to reach the actual target. Also, while it's
1567         // technically possible to jump to the start of a function and then jump
1568         // further, island insertion below always inserts islands after
1569         // previously appended code so for Cranelift's own implementation this
1570         // is also a problem for 64MB functions on AArch64 which start with a
1571         // call instruction, those won't be able to escape.
1572         //
1573         // Ideally what needs to happen here is that a `LabelUse` is
1574         // transparently generated (or call-sites of this function are audited
1575         // to generate a `LabelUse` instead) and tracked internally. The actual
1576         // relocation would then change over time if and when a veneer is
1577         // inserted, where the relocation here would be patched by this
1578         // `MachBuffer` to jump to the veneer. The problem, though, is that all
1579         // this still needs to end up, in the case of a singular function,
1580         // generating a final relocation pointing either to this particular
1581         // relocation or to the veneer inserted. Additionally
1582         // `MachBuffer` needs the concept of a label which will never be
1583         // resolved, so `emit_island` doesn't trip over not actually ever
1584         // knowning what some labels are. Currently the loop in
1585         // `finish_emission_maybe_forcing_veneers` would otherwise infinitely
1586         // loop.
1587         //
1588         // For now this means that because relocs aren't tracked at all that
1589         // AArch64 functions have a rough size limits of 64MB. For now that's
1590         // somewhat reasonable and the failure mode is a panic in `MachBuffer`
1591         // when a relocation can't otherwise be resolved later, so it shouldn't
1592         // actually result in any memory unsafety or anything like that.
1593         self.relocs.push(MachReloc {
1594             offset,
1595             kind,
1596             target,
1597             addend,
1598         });
1599     }
1600 
1601     /// Add an external relocation at the current offset.
1602     pub fn add_reloc<T: Into<RelocTarget> + Clone>(
1603         &mut self,
1604         kind: Reloc,
1605         target: &T,
1606         addend: Addend,
1607     ) {
1608         self.add_reloc_at_offset(self.data.len() as CodeOffset, kind, target, addend);
1609     }
1610 
1611     /// Add a trap record at the current offset.
1612     pub fn add_trap(&mut self, code: TrapCode) {
1613         self.traps.push(MachTrap {
1614             offset: self.data.len() as CodeOffset,
1615             code,
1616         });
1617     }
1618 
1619     /// Add a call-site record at the current offset.
1620     pub fn add_call_site(&mut self) {
1621         self.call_sites.push(MachCallSite {
1622             ret_addr: self.data.len() as CodeOffset,
1623         });
1624     }
1625 
1626     /// Add an unwind record at the current offset.
1627     pub fn add_unwind(&mut self, unwind: UnwindInst) {
1628         self.unwind_info.push((self.cur_offset(), unwind));
1629     }
1630 
1631     /// Add an exception handler record at the current offset.
1632     pub fn add_exception_handler(
1633         &mut self,
1634         tag: PackedOption<ir::ExceptionTag>,
1635         target: MachLabel,
1636     ) {
1637         self.exception_handlers
1638             .push((self.cur_offset(), tag, target));
1639     }
1640 
1641     /// Set the `SourceLoc` for code from this offset until the offset at the
1642     /// next call to `end_srcloc()`.
1643     /// Returns the current [CodeOffset] and [RelSourceLoc].
1644     pub fn start_srcloc(&mut self, loc: RelSourceLoc) -> (CodeOffset, RelSourceLoc) {
1645         let cur = (self.cur_offset(), loc);
1646         self.cur_srcloc = Some(cur);
1647         cur
1648     }
1649 
1650     /// Mark the end of the `SourceLoc` segment started at the last
1651     /// `start_srcloc()` call.
1652     pub fn end_srcloc(&mut self) {
1653         let (start, loc) = self
1654             .cur_srcloc
1655             .take()
1656             .expect("end_srcloc() called without start_srcloc()");
1657         let end = self.cur_offset();
1658         // Skip zero-length extends.
1659         debug_assert!(end >= start);
1660         if end > start {
1661             self.srclocs.push(MachSrcLoc { start, end, loc });
1662         }
1663     }
1664 
1665     /// Push a user stack map onto this buffer.
1666     ///
1667     /// The stack map is associated with the given `return_addr` code
1668     /// offset. This must be the PC for the instruction just *after* this stack
1669     /// map's associated instruction. For example in the sequence `call $foo;
1670     /// add r8, rax`, the `return_addr` must be the offset of the start of the
1671     /// `add` instruction.
1672     ///
1673     /// Stack maps must be pushed in sorted `return_addr` order.
1674     pub fn push_user_stack_map(
1675         &mut self,
1676         emit_state: &I::State,
1677         return_addr: CodeOffset,
1678         mut stack_map: ir::UserStackMap,
1679     ) {
1680         let span = emit_state.frame_layout().active_size();
1681         trace!("Adding user stack map @ {return_addr:#x} spanning {span} bytes: {stack_map:?}");
1682 
1683         debug_assert!(
1684             self.user_stack_maps
1685                 .last()
1686                 .map_or(true, |(prev_addr, _, _)| *prev_addr < return_addr),
1687             "pushed stack maps out of order: {} is not less than {}",
1688             self.user_stack_maps.last().unwrap().0,
1689             return_addr,
1690         );
1691 
1692         stack_map.finalize(emit_state.frame_layout().sp_to_sized_stack_slots());
1693         self.user_stack_maps.push((return_addr, span, stack_map));
1694     }
1695 
1696     /// Increase the alignment of the buffer to the given alignment if bigger
1697     /// than the current alignment.
1698     pub fn set_log2_min_function_alignment(&mut self, align_to: u8) {
1699         self.min_alignment = self.min_alignment.max(
1700             1u32.checked_shl(u32::from(align_to))
1701                 .expect("log2_min_function_alignment too large"),
1702         );
1703     }
1704 }
1705 
1706 impl<I: VCodeInst> Extend<u8> for MachBuffer<I> {
1707     fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
1708         for b in iter {
1709             self.put1(b);
1710         }
1711     }
1712 }
1713 
1714 impl<T: CompilePhase> MachBufferFinalized<T> {
1715     /// Get a list of source location mapping tuples in sorted-by-start-offset order.
1716     pub fn get_srclocs_sorted(&self) -> &[T::MachSrcLocType] {
1717         &self.srclocs[..]
1718     }
1719 
1720     /// Get the total required size for the code.
1721     pub fn total_size(&self) -> CodeOffset {
1722         self.data.len() as CodeOffset
1723     }
1724 
1725     /// Return the code in this mach buffer as a hex string for testing purposes.
1726     pub fn stringify_code_bytes(&self) -> String {
1727         // This is pretty lame, but whatever ..
1728         use std::fmt::Write;
1729         let mut s = String::with_capacity(self.data.len() * 2);
1730         for b in &self.data {
1731             write!(&mut s, "{b:02X}").unwrap();
1732         }
1733         s
1734     }
1735 
1736     /// Get the code bytes.
1737     pub fn data(&self) -> &[u8] {
1738         // N.B.: we emit every section into the .text section as far as
1739         // the `CodeSink` is concerned; we do not bother to segregate
1740         // the contents into the actual program text, the jumptable and the
1741         // rodata (constant pool). This allows us to generate code assuming
1742         // that these will not be relocated relative to each other, and avoids
1743         // having to designate each section as belonging in one of the three
1744         // fixed categories defined by `CodeSink`. If this becomes a problem
1745         // later (e.g. because of memory permissions or similar), we can
1746         // add this designation and segregate the output; take care, however,
1747         // to add the appropriate relocations in this case.
1748 
1749         &self.data[..]
1750     }
1751 
1752     /// Get the list of external relocations for this code.
1753     pub fn relocs(&self) -> &[FinalizedMachReloc] {
1754         &self.relocs[..]
1755     }
1756 
1757     /// Get the list of trap records for this code.
1758     pub fn traps(&self) -> &[MachTrap] {
1759         &self.traps[..]
1760     }
1761 
1762     /// Get the user stack map metadata for this code.
1763     pub fn user_stack_maps(&self) -> &[(CodeOffset, u32, ir::UserStackMap)] {
1764         &self.user_stack_maps
1765     }
1766 
1767     /// Take this buffer's user strack map metadata.
1768     pub fn take_user_stack_maps(&mut self) -> SmallVec<[(CodeOffset, u32, ir::UserStackMap); 8]> {
1769         mem::take(&mut self.user_stack_maps)
1770     }
1771 
1772     /// Get the list of call sites for this code.
1773     pub fn call_sites(&self) -> &[MachCallSite] {
1774         &self.call_sites[..]
1775     }
1776 }
1777 
1778 /// Metadata about a constant.
1779 struct MachBufferConstant {
1780     /// A label which has not yet been bound which can be used for this
1781     /// constant.
1782     ///
1783     /// This is lazily created when a label is requested for a constant and is
1784     /// cleared when a constant is emitted.
1785     upcoming_label: Option<MachLabel>,
1786     /// Required alignment.
1787     align: CodeOffset,
1788     /// The byte size of this constant.
1789     size: usize,
1790 }
1791 
1792 /// A trap that is deferred to the next time an island is emitted for either
1793 /// traps, constants, or fixups.
1794 struct MachLabelTrap {
1795     /// This label will refer to the trap's offset.
1796     label: MachLabel,
1797     /// The code associated with this trap.
1798     code: TrapCode,
1799     /// An optional source location to assign for this trap.
1800     loc: Option<RelSourceLoc>,
1801 }
1802 
1803 /// A fixup to perform on the buffer once code is emitted. Fixups always refer
1804 /// to labels and patch the code based on label offsets. Hence, they are like
1805 /// relocations, but internal to one buffer.
1806 #[derive(Debug)]
1807 struct MachLabelFixup<I: VCodeInst> {
1808     /// The label whose offset controls this fixup.
1809     label: MachLabel,
1810     /// The offset to fix up / patch to refer to this label.
1811     offset: CodeOffset,
1812     /// The kind of fixup. This is architecture-specific; each architecture may have,
1813     /// e.g., several types of branch instructions, each with differently-sized
1814     /// offset fields and different places within the instruction to place the
1815     /// bits.
1816     kind: I::LabelUse,
1817 }
1818 
1819 impl<I: VCodeInst> MachLabelFixup<I> {
1820     fn deadline(&self) -> CodeOffset {
1821         self.offset.saturating_add(self.kind.max_pos_range())
1822     }
1823 }
1824 
1825 impl<I: VCodeInst> PartialEq for MachLabelFixup<I> {
1826     fn eq(&self, other: &Self) -> bool {
1827         self.deadline() == other.deadline()
1828     }
1829 }
1830 
1831 impl<I: VCodeInst> Eq for MachLabelFixup<I> {}
1832 
1833 impl<I: VCodeInst> PartialOrd for MachLabelFixup<I> {
1834     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1835         Some(self.cmp(other))
1836     }
1837 }
1838 
1839 impl<I: VCodeInst> Ord for MachLabelFixup<I> {
1840     fn cmp(&self, other: &Self) -> Ordering {
1841         other.deadline().cmp(&self.deadline())
1842     }
1843 }
1844 
1845 /// A relocation resulting from a compilation.
1846 #[derive(Clone, Debug, PartialEq)]
1847 #[cfg_attr(
1848     feature = "enable-serde",
1849     derive(serde_derive::Serialize, serde_derive::Deserialize)
1850 )]
1851 pub struct MachRelocBase<T> {
1852     /// The offset at which the relocation applies, *relative to the
1853     /// containing section*.
1854     pub offset: CodeOffset,
1855     /// The kind of relocation.
1856     pub kind: Reloc,
1857     /// The external symbol / name to which this relocation refers.
1858     pub target: T,
1859     /// The addend to add to the symbol value.
1860     pub addend: i64,
1861 }
1862 
1863 type MachReloc = MachRelocBase<RelocTarget>;
1864 
1865 /// A relocation resulting from a compilation.
1866 pub type FinalizedMachReloc = MachRelocBase<FinalizedRelocTarget>;
1867 
1868 /// A Relocation target
1869 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1870 pub enum RelocTarget {
1871     /// Points to an [ExternalName] outside the current function.
1872     ExternalName(ExternalName),
1873     /// Points to a [MachLabel] inside this function.
1874     /// This is different from [MachLabelFixup] in that both the relocation and the
1875     /// label will be emitted and are only resolved at link time.
1876     ///
1877     /// There is no reason to prefer this over [MachLabelFixup] unless the ABI requires it.
1878     Label(MachLabel),
1879 }
1880 
1881 impl From<ExternalName> for RelocTarget {
1882     fn from(name: ExternalName) -> Self {
1883         Self::ExternalName(name)
1884     }
1885 }
1886 
1887 impl From<MachLabel> for RelocTarget {
1888     fn from(label: MachLabel) -> Self {
1889         Self::Label(label)
1890     }
1891 }
1892 
1893 /// A Relocation target
1894 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1895 #[cfg_attr(
1896     feature = "enable-serde",
1897     derive(serde_derive::Serialize, serde_derive::Deserialize)
1898 )]
1899 pub enum FinalizedRelocTarget {
1900     /// Points to an [ExternalName] outside the current function.
1901     ExternalName(ExternalName),
1902     /// Points to a [CodeOffset] from the start of the current function.
1903     Func(CodeOffset),
1904 }
1905 
1906 impl FinalizedRelocTarget {
1907     /// Returns a display for the current [FinalizedRelocTarget], with extra context to prettify the
1908     /// output.
1909     pub fn display<'a>(&'a self, params: Option<&'a FunctionParameters>) -> String {
1910         match self {
1911             FinalizedRelocTarget::ExternalName(name) => format!("{}", name.display(params)),
1912             FinalizedRelocTarget::Func(offset) => format!("func+{offset}"),
1913         }
1914     }
1915 }
1916 
1917 /// A trap record resulting from a compilation.
1918 #[derive(Clone, Debug, PartialEq)]
1919 #[cfg_attr(
1920     feature = "enable-serde",
1921     derive(serde_derive::Serialize, serde_derive::Deserialize)
1922 )]
1923 pub struct MachTrap {
1924     /// The offset at which the trap instruction occurs, *relative to the
1925     /// containing section*.
1926     pub offset: CodeOffset,
1927     /// The trap code.
1928     pub code: TrapCode,
1929 }
1930 
1931 /// A call site record resulting from a compilation.
1932 #[derive(Clone, Debug, PartialEq)]
1933 #[cfg_attr(
1934     feature = "enable-serde",
1935     derive(serde_derive::Serialize, serde_derive::Deserialize)
1936 )]
1937 pub struct MachCallSite {
1938     /// The offset of the call's return address, *relative to the containing section*.
1939     pub ret_addr: CodeOffset,
1940 }
1941 
1942 /// A source-location mapping resulting from a compilation.
1943 #[derive(PartialEq, Debug, Clone)]
1944 #[cfg_attr(
1945     feature = "enable-serde",
1946     derive(serde_derive::Serialize, serde_derive::Deserialize)
1947 )]
1948 pub struct MachSrcLoc<T: CompilePhase> {
1949     /// The start of the region of code corresponding to a source location.
1950     /// This is relative to the start of the function, not to the start of the
1951     /// section.
1952     pub start: CodeOffset,
1953     /// The end of the region of code corresponding to a source location.
1954     /// This is relative to the start of the section, not to the start of the
1955     /// section.
1956     pub end: CodeOffset,
1957     /// The source location.
1958     pub loc: T::SourceLocType,
1959 }
1960 
1961 impl MachSrcLoc<Stencil> {
1962     fn apply_base_srcloc(self, base_srcloc: SourceLoc) -> MachSrcLoc<Final> {
1963         MachSrcLoc {
1964             start: self.start,
1965             end: self.end,
1966             loc: self.loc.expand(base_srcloc),
1967         }
1968     }
1969 }
1970 
1971 /// Record of branch instruction in the buffer, to facilitate editing.
1972 #[derive(Clone, Debug)]
1973 struct MachBranch {
1974     start: CodeOffset,
1975     end: CodeOffset,
1976     target: MachLabel,
1977     fixup: usize,
1978     inverted: Option<SmallVec<[u8; 8]>>,
1979     /// All labels pointing to the start of this branch. For correctness, this
1980     /// *must* be complete (i.e., must contain all labels whose resolved offsets
1981     /// are at the start of this branch): we rely on being able to redirect all
1982     /// labels that could jump to this branch before removing it, if it is
1983     /// otherwise unreachable.
1984     labels_at_this_branch: SmallVec<[MachLabel; 4]>,
1985 }
1986 
1987 impl MachBranch {
1988     fn is_cond(&self) -> bool {
1989         self.inverted.is_some()
1990     }
1991     fn is_uncond(&self) -> bool {
1992         self.inverted.is_none()
1993     }
1994 }
1995 
1996 /// Implementation of the `TextSectionBuilder` trait backed by `MachBuffer`.
1997 ///
1998 /// Note that `MachBuffer` was primarily written for intra-function references
1999 /// of jumps between basic blocks, but it's also quite usable for entire text
2000 /// sections and resolving references between functions themselves. This
2001 /// builder interprets "blocks" as labeled functions for the purposes of
2002 /// resolving labels internally in the buffer.
2003 pub struct MachTextSectionBuilder<I: VCodeInst> {
2004     buf: MachBuffer<I>,
2005     next_func: usize,
2006     force_veneers: ForceVeneers,
2007 }
2008 
2009 impl<I: VCodeInst> MachTextSectionBuilder<I> {
2010     /// Creates a new text section builder which will have `num_funcs` functions
2011     /// pushed into it.
2012     pub fn new(num_funcs: usize) -> MachTextSectionBuilder<I> {
2013         let mut buf = MachBuffer::new();
2014         buf.reserve_labels_for_blocks(num_funcs);
2015         MachTextSectionBuilder {
2016             buf,
2017             next_func: 0,
2018             force_veneers: ForceVeneers::No,
2019         }
2020     }
2021 }
2022 
2023 impl<I: VCodeInst> TextSectionBuilder for MachTextSectionBuilder<I> {
2024     fn append(
2025         &mut self,
2026         labeled: bool,
2027         func: &[u8],
2028         align: u32,
2029         ctrl_plane: &mut ControlPlane,
2030     ) -> u64 {
2031         // Conditionally emit an island if it's necessary to resolve jumps
2032         // between functions which are too far away.
2033         let size = func.len() as u32;
2034         if self.force_veneers == ForceVeneers::Yes || self.buf.island_needed(size) {
2035             self.buf
2036                 .emit_island_maybe_forced(self.force_veneers, size, ctrl_plane);
2037         }
2038 
2039         self.buf.align_to(align);
2040         let pos = self.buf.cur_offset();
2041         if labeled {
2042             self.buf.bind_label(
2043                 MachLabel::from_block(BlockIndex::new(self.next_func)),
2044                 ctrl_plane,
2045             );
2046             self.next_func += 1;
2047         }
2048         self.buf.put_data(func);
2049         u64::from(pos)
2050     }
2051 
2052     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool {
2053         crate::trace!(
2054             "Resolving relocation @ {offset:#x} + {addend:#x} to target {target} of kind {reloc:?}"
2055         );
2056         let label = MachLabel::from_block(BlockIndex::new(target));
2057         let offset = u32::try_from(offset).unwrap();
2058         match I::LabelUse::from_reloc(reloc, addend) {
2059             Some(label_use) => {
2060                 self.buf.use_label_at_offset(offset, label, label_use);
2061                 true
2062             }
2063             None => false,
2064         }
2065     }
2066 
2067     fn force_veneers(&mut self) {
2068         self.force_veneers = ForceVeneers::Yes;
2069     }
2070 
2071     fn write(&mut self, offset: u64, data: &[u8]) {
2072         self.buf.data[offset.try_into().unwrap()..][..data.len()].copy_from_slice(data);
2073     }
2074 
2075     fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8> {
2076         // Double-check all functions were pushed.
2077         assert_eq!(self.next_func, self.buf.label_offsets.len());
2078 
2079         // Finish up any veneers, if necessary.
2080         self.buf
2081             .finish_emission_maybe_forcing_veneers(self.force_veneers, ctrl_plane);
2082 
2083         // We don't need the data any more, so return it to the caller.
2084         mem::take(&mut self.buf.data).into_vec()
2085     }
2086 }
2087 
2088 // We use an actual instruction definition to do tests, so we depend on the `arm64` feature here.
2089 #[cfg(all(test, feature = "arm64"))]
2090 mod test {
2091     use cranelift_entity::EntityRef as _;
2092 
2093     use super::*;
2094     use crate::ir::UserExternalNameRef;
2095     use crate::isa::aarch64::inst::{xreg, OperandSize};
2096     use crate::isa::aarch64::inst::{BranchTarget, CondBrKind, EmitInfo, Inst};
2097     use crate::machinst::{MachInstEmit, MachInstEmitState};
2098     use crate::settings;
2099 
2100     fn label(n: u32) -> MachLabel {
2101         MachLabel::from_block(BlockIndex::new(n as usize))
2102     }
2103     fn target(n: u32) -> BranchTarget {
2104         BranchTarget::Label(label(n))
2105     }
2106 
2107     #[test]
2108     fn test_elide_jump_to_next() {
2109         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2110         let mut buf = MachBuffer::new();
2111         let mut state = <Inst as MachInstEmit>::State::default();
2112         let constants = Default::default();
2113 
2114         buf.reserve_labels_for_blocks(2);
2115         buf.bind_label(label(0), state.ctrl_plane_mut());
2116         let inst = Inst::Jump { dest: target(1) };
2117         inst.emit(&mut buf, &info, &mut state);
2118         buf.bind_label(label(1), state.ctrl_plane_mut());
2119         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2120         assert_eq!(0, buf.total_size());
2121     }
2122 
2123     #[test]
2124     fn test_elide_trivial_jump_blocks() {
2125         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2126         let mut buf = MachBuffer::new();
2127         let mut state = <Inst as MachInstEmit>::State::default();
2128         let constants = Default::default();
2129 
2130         buf.reserve_labels_for_blocks(4);
2131 
2132         buf.bind_label(label(0), state.ctrl_plane_mut());
2133         let inst = Inst::CondBr {
2134             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2135             taken: target(1),
2136             not_taken: target(2),
2137         };
2138         inst.emit(&mut buf, &info, &mut state);
2139 
2140         buf.bind_label(label(1), state.ctrl_plane_mut());
2141         let inst = Inst::Jump { dest: target(3) };
2142         inst.emit(&mut buf, &info, &mut state);
2143 
2144         buf.bind_label(label(2), state.ctrl_plane_mut());
2145         let inst = Inst::Jump { dest: target(3) };
2146         inst.emit(&mut buf, &info, &mut state);
2147 
2148         buf.bind_label(label(3), state.ctrl_plane_mut());
2149 
2150         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2151         assert_eq!(0, buf.total_size());
2152     }
2153 
2154     #[test]
2155     fn test_flip_cond() {
2156         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2157         let mut buf = MachBuffer::new();
2158         let mut state = <Inst as MachInstEmit>::State::default();
2159         let constants = Default::default();
2160 
2161         buf.reserve_labels_for_blocks(4);
2162 
2163         buf.bind_label(label(0), state.ctrl_plane_mut());
2164         let inst = Inst::CondBr {
2165             kind: CondBrKind::Zero(xreg(0), OperandSize::Size64),
2166             taken: target(1),
2167             not_taken: target(2),
2168         };
2169         inst.emit(&mut buf, &info, &mut state);
2170 
2171         buf.bind_label(label(1), state.ctrl_plane_mut());
2172         let inst = Inst::Nop4;
2173         inst.emit(&mut buf, &info, &mut state);
2174 
2175         buf.bind_label(label(2), state.ctrl_plane_mut());
2176         let inst = Inst::Udf {
2177             trap_code: TrapCode::STACK_OVERFLOW,
2178         };
2179         inst.emit(&mut buf, &info, &mut state);
2180 
2181         buf.bind_label(label(3), state.ctrl_plane_mut());
2182 
2183         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2184 
2185         let mut buf2 = MachBuffer::new();
2186         let mut state = Default::default();
2187         let inst = Inst::TrapIf {
2188             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2189             trap_code: TrapCode::STACK_OVERFLOW,
2190         };
2191         inst.emit(&mut buf2, &info, &mut state);
2192         let inst = Inst::Nop4;
2193         inst.emit(&mut buf2, &info, &mut state);
2194 
2195         let buf2 = buf2.finish(&constants, state.ctrl_plane_mut());
2196 
2197         assert_eq!(buf.data, buf2.data);
2198     }
2199 
2200     #[test]
2201     fn test_island() {
2202         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2203         let mut buf = MachBuffer::new();
2204         let mut state = <Inst as MachInstEmit>::State::default();
2205         let constants = Default::default();
2206 
2207         buf.reserve_labels_for_blocks(4);
2208 
2209         buf.bind_label(label(0), state.ctrl_plane_mut());
2210         let inst = Inst::CondBr {
2211             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2212             taken: target(2),
2213             not_taken: target(3),
2214         };
2215         inst.emit(&mut buf, &info, &mut state);
2216 
2217         buf.bind_label(label(1), state.ctrl_plane_mut());
2218         while buf.cur_offset() < 2000000 {
2219             if buf.island_needed(0) {
2220                 buf.emit_island(0, state.ctrl_plane_mut());
2221             }
2222             let inst = Inst::Nop4;
2223             inst.emit(&mut buf, &info, &mut state);
2224         }
2225 
2226         buf.bind_label(label(2), state.ctrl_plane_mut());
2227         let inst = Inst::Nop4;
2228         inst.emit(&mut buf, &info, &mut state);
2229 
2230         buf.bind_label(label(3), state.ctrl_plane_mut());
2231         let inst = Inst::Nop4;
2232         inst.emit(&mut buf, &info, &mut state);
2233 
2234         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2235 
2236         assert_eq!(2000000 + 8, buf.total_size());
2237 
2238         let mut buf2 = MachBuffer::new();
2239         let mut state = Default::default();
2240         let inst = Inst::CondBr {
2241             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2242 
2243             // This conditionally taken branch has a 19-bit constant, shifted
2244             // to the left by two, giving us a 21-bit range in total. Half of
2245             // this range positive so the we should be around 1 << 20 bytes
2246             // away for our jump target.
2247             //
2248             // There are two pending fixups by the time we reach this point,
2249             // one for this 19-bit jump and one for the unconditional 26-bit
2250             // jump below. A 19-bit veneer is 4 bytes large and the 26-bit
2251             // veneer is 20 bytes large, which means that pessimistically
2252             // assuming we'll need two veneers. Currently each veneer is
2253             // pessimistically assumed to be the maximal size which means we
2254             // need 40 bytes of extra space, meaning that the actual island
2255             // should come 40-bytes before the deadline.
2256             taken: BranchTarget::ResolvedOffset((1 << 20) - 20 - 20),
2257 
2258             // This branch is in-range so no veneers should be needed, it should
2259             // go directly to the target.
2260             not_taken: BranchTarget::ResolvedOffset(2000000 + 4 - 4),
2261         };
2262         inst.emit(&mut buf2, &info, &mut state);
2263 
2264         let buf2 = buf2.finish(&constants, state.ctrl_plane_mut());
2265 
2266         assert_eq!(&buf.data[0..8], &buf2.data[..]);
2267     }
2268 
2269     #[test]
2270     fn test_island_backward() {
2271         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2272         let mut buf = MachBuffer::new();
2273         let mut state = <Inst as MachInstEmit>::State::default();
2274         let constants = Default::default();
2275 
2276         buf.reserve_labels_for_blocks(4);
2277 
2278         buf.bind_label(label(0), state.ctrl_plane_mut());
2279         let inst = Inst::Nop4;
2280         inst.emit(&mut buf, &info, &mut state);
2281 
2282         buf.bind_label(label(1), state.ctrl_plane_mut());
2283         let inst = Inst::Nop4;
2284         inst.emit(&mut buf, &info, &mut state);
2285 
2286         buf.bind_label(label(2), state.ctrl_plane_mut());
2287         while buf.cur_offset() < 2000000 {
2288             let inst = Inst::Nop4;
2289             inst.emit(&mut buf, &info, &mut state);
2290         }
2291 
2292         buf.bind_label(label(3), state.ctrl_plane_mut());
2293         let inst = Inst::CondBr {
2294             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2295             taken: target(0),
2296             not_taken: target(1),
2297         };
2298         inst.emit(&mut buf, &info, &mut state);
2299 
2300         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2301 
2302         assert_eq!(2000000 + 12, buf.total_size());
2303 
2304         let mut buf2 = MachBuffer::new();
2305         let mut state = Default::default();
2306         let inst = Inst::CondBr {
2307             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2308             taken: BranchTarget::ResolvedOffset(8),
2309             not_taken: BranchTarget::ResolvedOffset(4 - (2000000 + 4)),
2310         };
2311         inst.emit(&mut buf2, &info, &mut state);
2312         let inst = Inst::Jump {
2313             dest: BranchTarget::ResolvedOffset(-(2000000 + 8)),
2314         };
2315         inst.emit(&mut buf2, &info, &mut state);
2316 
2317         let buf2 = buf2.finish(&constants, state.ctrl_plane_mut());
2318 
2319         assert_eq!(&buf.data[2000000..], &buf2.data[..]);
2320     }
2321 
2322     #[test]
2323     fn test_multiple_redirect() {
2324         // label0:
2325         //   cbz x0, label1
2326         //   b label2
2327         // label1:
2328         //   b label3
2329         // label2:
2330         //   nop
2331         //   nop
2332         //   b label0
2333         // label3:
2334         //   b label4
2335         // label4:
2336         //   b label5
2337         // label5:
2338         //   b label7
2339         // label6:
2340         //   nop
2341         // label7:
2342         //   ret
2343         //
2344         // -- should become:
2345         //
2346         // label0:
2347         //   cbz x0, label7
2348         // label2:
2349         //   nop
2350         //   nop
2351         //   b label0
2352         // label6:
2353         //   nop
2354         // label7:
2355         //   ret
2356 
2357         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2358         let mut buf = MachBuffer::new();
2359         let mut state = <Inst as MachInstEmit>::State::default();
2360         let constants = Default::default();
2361 
2362         buf.reserve_labels_for_blocks(8);
2363 
2364         buf.bind_label(label(0), state.ctrl_plane_mut());
2365         let inst = Inst::CondBr {
2366             kind: CondBrKind::Zero(xreg(0), OperandSize::Size64),
2367             taken: target(1),
2368             not_taken: target(2),
2369         };
2370         inst.emit(&mut buf, &info, &mut state);
2371 
2372         buf.bind_label(label(1), state.ctrl_plane_mut());
2373         let inst = Inst::Jump { dest: target(3) };
2374         inst.emit(&mut buf, &info, &mut state);
2375 
2376         buf.bind_label(label(2), state.ctrl_plane_mut());
2377         let inst = Inst::Nop4;
2378         inst.emit(&mut buf, &info, &mut state);
2379         inst.emit(&mut buf, &info, &mut state);
2380         let inst = Inst::Jump { dest: target(0) };
2381         inst.emit(&mut buf, &info, &mut state);
2382 
2383         buf.bind_label(label(3), state.ctrl_plane_mut());
2384         let inst = Inst::Jump { dest: target(4) };
2385         inst.emit(&mut buf, &info, &mut state);
2386 
2387         buf.bind_label(label(4), state.ctrl_plane_mut());
2388         let inst = Inst::Jump { dest: target(5) };
2389         inst.emit(&mut buf, &info, &mut state);
2390 
2391         buf.bind_label(label(5), state.ctrl_plane_mut());
2392         let inst = Inst::Jump { dest: target(7) };
2393         inst.emit(&mut buf, &info, &mut state);
2394 
2395         buf.bind_label(label(6), state.ctrl_plane_mut());
2396         let inst = Inst::Nop4;
2397         inst.emit(&mut buf, &info, &mut state);
2398 
2399         buf.bind_label(label(7), state.ctrl_plane_mut());
2400         let inst = Inst::Ret {};
2401         inst.emit(&mut buf, &info, &mut state);
2402 
2403         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2404 
2405         let golden_data = vec![
2406             0xa0, 0x00, 0x00, 0xb4, // cbz x0, 0x14
2407             0x1f, 0x20, 0x03, 0xd5, // nop
2408             0x1f, 0x20, 0x03, 0xd5, // nop
2409             0xfd, 0xff, 0xff, 0x17, // b 0
2410             0x1f, 0x20, 0x03, 0xd5, // nop
2411             0xc0, 0x03, 0x5f, 0xd6, // ret
2412         ];
2413 
2414         assert_eq!(&golden_data[..], &buf.data[..]);
2415     }
2416 
2417     #[test]
2418     fn test_handle_branch_cycle() {
2419         // label0:
2420         //   b label1
2421         // label1:
2422         //   b label2
2423         // label2:
2424         //   b label3
2425         // label3:
2426         //   b label4
2427         // label4:
2428         //   b label1  // note: not label0 (to make it interesting).
2429         //
2430         // -- should become:
2431         //
2432         // label0, label1, ..., label4:
2433         //   b label0
2434         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2435         let mut buf = MachBuffer::new();
2436         let mut state = <Inst as MachInstEmit>::State::default();
2437         let constants = Default::default();
2438 
2439         buf.reserve_labels_for_blocks(5);
2440 
2441         buf.bind_label(label(0), state.ctrl_plane_mut());
2442         let inst = Inst::Jump { dest: target(1) };
2443         inst.emit(&mut buf, &info, &mut state);
2444 
2445         buf.bind_label(label(1), state.ctrl_plane_mut());
2446         let inst = Inst::Jump { dest: target(2) };
2447         inst.emit(&mut buf, &info, &mut state);
2448 
2449         buf.bind_label(label(2), state.ctrl_plane_mut());
2450         let inst = Inst::Jump { dest: target(3) };
2451         inst.emit(&mut buf, &info, &mut state);
2452 
2453         buf.bind_label(label(3), state.ctrl_plane_mut());
2454         let inst = Inst::Jump { dest: target(4) };
2455         inst.emit(&mut buf, &info, &mut state);
2456 
2457         buf.bind_label(label(4), state.ctrl_plane_mut());
2458         let inst = Inst::Jump { dest: target(1) };
2459         inst.emit(&mut buf, &info, &mut state);
2460 
2461         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2462 
2463         let golden_data = vec![
2464             0x00, 0x00, 0x00, 0x14, // b 0
2465         ];
2466 
2467         assert_eq!(&golden_data[..], &buf.data[..]);
2468     }
2469 
2470     #[test]
2471     fn metadata_records() {
2472         let mut buf = MachBuffer::<Inst>::new();
2473         let ctrl_plane = &mut Default::default();
2474         let constants = Default::default();
2475 
2476         buf.reserve_labels_for_blocks(1);
2477 
2478         buf.bind_label(label(0), ctrl_plane);
2479         buf.put1(1);
2480         buf.add_trap(TrapCode::HEAP_OUT_OF_BOUNDS);
2481         buf.put1(2);
2482         buf.add_trap(TrapCode::INTEGER_OVERFLOW);
2483         buf.add_trap(TrapCode::INTEGER_DIVISION_BY_ZERO);
2484         buf.add_call_site();
2485         buf.add_reloc(
2486             Reloc::Abs4,
2487             &ExternalName::User(UserExternalNameRef::new(0)),
2488             0,
2489         );
2490         buf.put1(3);
2491         buf.add_reloc(
2492             Reloc::Abs8,
2493             &ExternalName::User(UserExternalNameRef::new(1)),
2494             1,
2495         );
2496         buf.put1(4);
2497 
2498         let buf = buf.finish(&constants, ctrl_plane);
2499 
2500         assert_eq!(buf.data(), &[1, 2, 3, 4]);
2501         assert_eq!(
2502             buf.traps()
2503                 .iter()
2504                 .map(|trap| (trap.offset, trap.code))
2505                 .collect::<Vec<_>>(),
2506             vec![
2507                 (1, TrapCode::HEAP_OUT_OF_BOUNDS),
2508                 (2, TrapCode::INTEGER_OVERFLOW),
2509                 (2, TrapCode::INTEGER_DIVISION_BY_ZERO)
2510             ]
2511         );
2512         assert_eq!(
2513             buf.call_sites()
2514                 .iter()
2515                 .map(|call_site| call_site.ret_addr)
2516                 .collect::<Vec<_>>(),
2517             vec![2]
2518         );
2519         assert_eq!(
2520             buf.relocs()
2521                 .iter()
2522                 .map(|reloc| (reloc.offset, reloc.kind))
2523                 .collect::<Vec<_>>(),
2524             vec![(2, Reloc::Abs4), (3, Reloc::Abs8)]
2525         );
2526     }
2527 }
2528