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 use crate::binemit::{Addend, CodeOffset, Reloc, StackMap};
144 use crate::ir::function::FunctionParameters;
145 use crate::ir::{ExternalName, Opcode, RelSourceLoc, SourceLoc, TrapCode};
146 use crate::isa::unwind::UnwindInst;
147 use crate::machinst::{
148     BlockIndex, MachInstLabelUse, TextSectionBuilder, VCodeConstant, VCodeConstants, VCodeInst,
149 };
150 use crate::timing;
151 use crate::trace;
152 use cranelift_entity::{entity_impl, SecondaryMap};
153 use smallvec::SmallVec;
154 use std::convert::TryFrom;
155 use std::mem;
156 use std::string::String;
157 use std::vec::Vec;
158 
159 #[cfg(feature = "enable-serde")]
160 use serde::{Deserialize, Serialize};
161 
162 #[cfg(feature = "enable-serde")]
163 pub trait CompilePhase {
164     type MachSrcLocType: for<'a> Deserialize<'a> + Serialize + core::fmt::Debug + PartialEq + Clone;
165     type SourceLocType: for<'a> Deserialize<'a> + Serialize + core::fmt::Debug + PartialEq + Clone;
166 }
167 
168 #[cfg(not(feature = "enable-serde"))]
169 pub trait CompilePhase {
170     type MachSrcLocType: core::fmt::Debug + PartialEq + Clone;
171     type SourceLocType: core::fmt::Debug + PartialEq + Clone;
172 }
173 
174 /// Status of a compiled artifact that needs patching before being used.
175 ///
176 /// Only used internally.
177 #[derive(Clone, Debug, PartialEq)]
178 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
179 pub struct Stencil;
180 
181 /// Status of a compiled artifact ready to use.
182 #[derive(Clone, Debug, PartialEq)]
183 pub struct Final;
184 
185 impl CompilePhase for Stencil {
186     type MachSrcLocType = MachSrcLoc<Stencil>;
187     type SourceLocType = RelSourceLoc;
188 }
189 
190 impl CompilePhase for Final {
191     type MachSrcLocType = MachSrcLoc<Final>;
192     type SourceLocType = SourceLoc;
193 }
194 
195 /// A buffer of output to be produced, fixed up, and then emitted to a CodeSink
196 /// in bulk.
197 ///
198 /// This struct uses `SmallVec`s to support small-ish function bodies without
199 /// any heap allocation. As such, it will be several kilobytes large. This is
200 /// likely fine as long as it is stack-allocated for function emission then
201 /// thrown away; but beware if many buffer objects are retained persistently.
202 pub struct MachBuffer<I: VCodeInst> {
203     /// The buffer contents, as raw bytes.
204     data: SmallVec<[u8; 1024]>,
205     /// Any relocations referring to this code. Note that only *external*
206     /// relocations are tracked here; references to labels within the buffer are
207     /// resolved before emission.
208     relocs: SmallVec<[MachReloc; 16]>,
209     /// Any trap records referring to this code.
210     traps: SmallVec<[MachTrap; 16]>,
211     /// Any call site records referring to this code.
212     call_sites: SmallVec<[MachCallSite; 16]>,
213     /// Any source location mappings referring to this code.
214     srclocs: SmallVec<[MachSrcLoc<Stencil>; 64]>,
215     /// Any stack maps referring to this code.
216     stack_maps: SmallVec<[MachStackMap; 8]>,
217     /// Any unwind info at a given location.
218     unwind_info: SmallVec<[(CodeOffset, UnwindInst); 8]>,
219     /// The current source location in progress (after `start_srcloc()` and
220     /// before `end_srcloc()`).  This is a (start_offset, src_loc) tuple.
221     cur_srcloc: Option<(CodeOffset, RelSourceLoc)>,
222     /// Known label offsets; `UNKNOWN_LABEL_OFFSET` if unknown.
223     label_offsets: SmallVec<[CodeOffset; 16]>,
224     /// Label aliases: when one label points to an unconditional jump, and that
225     /// jump points to another label, we can redirect references to the first
226     /// label immediately to the second.
227     ///
228     /// Invariant: we don't have label-alias cycles. We ensure this by,
229     /// before setting label A to alias label B, resolving B's alias
230     /// target (iteratively until a non-aliased label); if B is already
231     /// aliased to A, then we cannot alias A back to B.
232     label_aliases: SmallVec<[MachLabel; 16]>,
233     /// Constants that must be emitted at some point.
234     pending_constants: SmallVec<[MachLabelConstant; 16]>,
235     /// Fixups that must be performed after all code is emitted.
236     fixup_records: SmallVec<[MachLabelFixup<I>; 16]>,
237     /// Current deadline at which all constants are flushed and all code labels
238     /// are extended by emitting long-range jumps in an island. This flush
239     /// should be rare (e.g., on AArch64, the shortest-range PC-rel references
240     /// are +/- 1MB for conditional jumps and load-literal instructions), so
241     /// it's acceptable to track a minimum and flush-all rather than doing more
242     /// detailed "current minimum" / sort-by-deadline trickery.
243     island_deadline: CodeOffset,
244     /// How many bytes are needed in the worst case for an island, given all
245     /// pending constants and fixups.
246     island_worst_case_size: CodeOffset,
247     /// Latest branches, to facilitate in-place editing for better fallthrough
248     /// behavior and empty-block removal.
249     latest_branches: SmallVec<[MachBranch; 4]>,
250     /// All labels at the current offset (emission tail). This is lazily
251     /// cleared: it is actually accurate as long as the current offset is
252     /// `labels_at_tail_off`, but if `cur_offset()` has grown larger, it should
253     /// be considered as empty.
254     ///
255     /// For correctness, this *must* be complete (i.e., the vector must contain
256     /// all labels whose offsets are resolved to the current tail), because we
257     /// rely on it to update labels when we truncate branches.
258     labels_at_tail: SmallVec<[MachLabel; 4]>,
259     /// The last offset at which `labels_at_tail` is valid. It is conceptually
260     /// always describing the tail of the buffer, but we do not clear
261     /// `labels_at_tail` eagerly when the tail grows, rather we lazily clear it
262     /// when the offset has grown past this (`labels_at_tail_off`) point.
263     /// Always <= `cur_offset()`.
264     labels_at_tail_off: CodeOffset,
265     /// Map used constants to their [MachLabel].
266     constant_labels: SecondaryMap<VCodeConstant, MachLabel>,
267 }
268 
269 impl MachBufferFinalized<Stencil> {
270     pub(crate) fn apply_params(self, params: &FunctionParameters) -> MachBufferFinalized<Final> {
271         MachBufferFinalized {
272             data: self.data,
273             relocs: self.relocs,
274             traps: self.traps,
275             call_sites: self.call_sites,
276             srclocs: self
277                 .srclocs
278                 .into_iter()
279                 .map(|srcloc| srcloc.apply_params(params))
280                 .collect(),
281             stack_maps: self.stack_maps,
282             unwind_info: self.unwind_info,
283         }
284     }
285 }
286 
287 /// A `MachBuffer` once emission is completed: holds generated code and records,
288 /// without fixups. This allows the type to be independent of the backend.
289 #[derive(PartialEq, Debug, Clone)]
290 #[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
291 pub struct MachBufferFinalized<T: CompilePhase> {
292     /// The buffer contents, as raw bytes.
293     pub(crate) data: SmallVec<[u8; 1024]>,
294     /// Any relocations referring to this code. Note that only *external*
295     /// relocations are tracked here; references to labels within the buffer are
296     /// resolved before emission.
297     pub(crate) relocs: SmallVec<[MachReloc; 16]>,
298     /// Any trap records referring to this code.
299     pub(crate) traps: SmallVec<[MachTrap; 16]>,
300     /// Any call site records referring to this code.
301     pub(crate) call_sites: SmallVec<[MachCallSite; 16]>,
302     /// Any source location mappings referring to this code.
303     pub(crate) srclocs: SmallVec<[T::MachSrcLocType; 64]>,
304     /// Any stack maps referring to this code.
305     pub(crate) stack_maps: SmallVec<[MachStackMap; 8]>,
306     /// Any unwind info at a given location.
307     pub unwind_info: SmallVec<[(CodeOffset, UnwindInst); 8]>,
308 }
309 
310 const UNKNOWN_LABEL_OFFSET: CodeOffset = 0xffff_ffff;
311 const UNKNOWN_LABEL: MachLabel = MachLabel(0xffff_ffff);
312 
313 /// Threshold on max length of `labels_at_this_branch` list to avoid
314 /// unbounded quadratic behavior (see comment below at use-site).
315 const LABEL_LIST_THRESHOLD: usize = 100;
316 
317 /// A label refers to some offset in a `MachBuffer`. It may not be resolved at
318 /// the point at which it is used by emitted code; the buffer records "fixups"
319 /// for references to the label, and will come back and patch the code
320 /// appropriately when the label's location is eventually known.
321 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
322 pub struct MachLabel(u32);
323 entity_impl!(MachLabel);
324 
325 impl MachLabel {
326     /// Get a label for a block. (The first N MachLabels are always reseved for
327     /// the N blocks in the vcode.)
328     pub fn from_block(bindex: BlockIndex) -> MachLabel {
329         MachLabel(bindex.index() as u32)
330     }
331 
332     /// Get the numeric label index.
333     pub fn get(self) -> u32 {
334         self.0
335     }
336 
337     /// Creates a string representing this label, for convenience.
338     pub fn to_string(&self) -> String {
339         format!("label{}", self.0)
340     }
341 }
342 
343 impl Default for MachLabel {
344     fn default() -> Self {
345         UNKNOWN_LABEL
346     }
347 }
348 
349 /// A stack map extent, when creating a stack map.
350 pub enum StackMapExtent {
351     /// The stack map starts at this instruction, and ends after the number of upcoming bytes
352     /// (note: this is a code offset diff).
353     UpcomingBytes(CodeOffset),
354 
355     /// The stack map started at the given offset and ends at the current one. This helps
356     /// architectures where the instruction size has not a fixed length.
357     StartedAtOffset(CodeOffset),
358 }
359 
360 impl<I: VCodeInst> MachBuffer<I> {
361     /// Create a new section, known to start at `start_offset` and with a size limited to
362     /// `length_limit`.
363     pub fn new() -> MachBuffer<I> {
364         MachBuffer {
365             data: SmallVec::new(),
366             relocs: SmallVec::new(),
367             traps: SmallVec::new(),
368             call_sites: SmallVec::new(),
369             srclocs: SmallVec::new(),
370             stack_maps: SmallVec::new(),
371             unwind_info: SmallVec::new(),
372             cur_srcloc: None,
373             label_offsets: SmallVec::new(),
374             label_aliases: SmallVec::new(),
375             pending_constants: SmallVec::new(),
376             fixup_records: SmallVec::new(),
377             island_deadline: UNKNOWN_LABEL_OFFSET,
378             island_worst_case_size: 0,
379             latest_branches: SmallVec::new(),
380             labels_at_tail: SmallVec::new(),
381             labels_at_tail_off: 0,
382             constant_labels: SecondaryMap::new(),
383         }
384     }
385 
386     /// Current offset from start of buffer.
387     pub fn cur_offset(&self) -> CodeOffset {
388         self.data.len() as CodeOffset
389     }
390 
391     /// Add a byte.
392     pub fn put1(&mut self, value: u8) {
393         trace!("MachBuffer: put byte @ {}: {:x}", self.cur_offset(), value);
394         self.data.push(value);
395 
396         // Post-invariant: conceptual-labels_at_tail contains a complete and
397         // precise list of labels bound at `cur_offset()`. We have advanced
398         // `cur_offset()`, hence if it had been equal to `labels_at_tail_off`
399         // before, it is not anymore (and it cannot become equal, because
400         // `labels_at_tail_off` is always <= `cur_offset()`). Thus the list is
401         // conceptually empty (even though it is only lazily cleared). No labels
402         // can be bound at this new offset (by invariant on `label_offsets`).
403         // Hence the invariant holds.
404     }
405 
406     /// Add 2 bytes.
407     pub fn put2(&mut self, value: u16) {
408         trace!(
409             "MachBuffer: put 16-bit word @ {}: {:x}",
410             self.cur_offset(),
411             value
412         );
413         let bytes = value.to_le_bytes();
414         self.data.extend_from_slice(&bytes[..]);
415 
416         // Post-invariant: as for `put1()`.
417     }
418 
419     /// Add 4 bytes.
420     pub fn put4(&mut self, value: u32) {
421         trace!(
422             "MachBuffer: put 32-bit word @ {}: {:x}",
423             self.cur_offset(),
424             value
425         );
426         let bytes = value.to_le_bytes();
427         self.data.extend_from_slice(&bytes[..]);
428 
429         // Post-invariant: as for `put1()`.
430     }
431 
432     /// Add 8 bytes.
433     pub fn put8(&mut self, value: u64) {
434         trace!(
435             "MachBuffer: put 64-bit word @ {}: {:x}",
436             self.cur_offset(),
437             value
438         );
439         let bytes = value.to_le_bytes();
440         self.data.extend_from_slice(&bytes[..]);
441 
442         // Post-invariant: as for `put1()`.
443     }
444 
445     /// Add a slice of bytes.
446     pub fn put_data(&mut self, data: &[u8]) {
447         trace!(
448             "MachBuffer: put data @ {}: len {}",
449             self.cur_offset(),
450             data.len()
451         );
452         self.data.extend_from_slice(data);
453 
454         // Post-invariant: as for `put1()`.
455     }
456 
457     /// Reserve appended space and return a mutable slice referring to it.
458     pub fn get_appended_space(&mut self, len: usize) -> &mut [u8] {
459         trace!("MachBuffer: put data @ {}: len {}", self.cur_offset(), len);
460         let off = self.data.len();
461         let new_len = self.data.len() + len;
462         self.data.resize(new_len, 0);
463         &mut self.data[off..]
464 
465         // Post-invariant: as for `put1()`.
466     }
467 
468     /// Align up to the given alignment.
469     pub fn align_to(&mut self, align_to: CodeOffset) {
470         trace!("MachBuffer: align to {}", align_to);
471         assert!(align_to.is_power_of_two());
472         while self.cur_offset() & (align_to - 1) != 0 {
473             self.put1(0);
474         }
475 
476         // Post-invariant: as for `put1()`.
477     }
478 
479     /// Allocate a `Label` to refer to some offset. May not be bound to a fixed
480     /// offset yet.
481     pub fn get_label(&mut self) -> MachLabel {
482         let l = self.label_offsets.len() as u32;
483         self.label_offsets.push(UNKNOWN_LABEL_OFFSET);
484         self.label_aliases.push(UNKNOWN_LABEL);
485         trace!("MachBuffer: new label -> {:?}", MachLabel(l));
486         MachLabel(l)
487 
488         // Post-invariant: the only mutation is to add a new label; it has no
489         // bound offset yet, so it trivially satisfies all invariants.
490     }
491 
492     /// Reserve the first N MachLabels for blocks.
493     pub fn reserve_labels_for_blocks(&mut self, blocks: usize) {
494         trace!("MachBuffer: first {} labels are for blocks", blocks);
495         debug_assert!(self.label_offsets.is_empty());
496         self.label_offsets.resize(blocks, UNKNOWN_LABEL_OFFSET);
497         self.label_aliases.resize(blocks, UNKNOWN_LABEL);
498 
499         // Post-invariant: as for `get_label()`.
500     }
501 
502     /// Reserve the next N MachLabels for constants.
503     pub fn reserve_labels_for_constants(&mut self, constants: &VCodeConstants) {
504         trace!(
505             "MachBuffer: next {} labels are for constants",
506             constants.len()
507         );
508         for c in constants.keys() {
509             self.constant_labels[c] = self.get_label();
510         }
511 
512         // Post-invariant: as for `get_label()`.
513     }
514 
515     /// Retrieve the reserved label for a constant.
516     pub fn get_label_for_constant(&self, constant: VCodeConstant) -> MachLabel {
517         self.constant_labels[constant]
518     }
519 
520     /// Bind a label to the current offset. A label can only be bound once.
521     pub fn bind_label(&mut self, label: MachLabel) {
522         trace!(
523             "MachBuffer: bind label {:?} at offset {}",
524             label,
525             self.cur_offset()
526         );
527         debug_assert_eq!(self.label_offsets[label.0 as usize], UNKNOWN_LABEL_OFFSET);
528         debug_assert_eq!(self.label_aliases[label.0 as usize], UNKNOWN_LABEL);
529         let offset = self.cur_offset();
530         self.label_offsets[label.0 as usize] = offset;
531         self.lazily_clear_labels_at_tail();
532         self.labels_at_tail.push(label);
533 
534         // Invariants hold: bound offset of label is <= cur_offset (in fact it
535         // is equal). If the `labels_at_tail` list was complete and precise
536         // before, it is still, because we have bound this label to the current
537         // offset and added it to the list (which contains all labels at the
538         // current offset).
539 
540         self.optimize_branches();
541 
542         // Post-invariant: by `optimize_branches()` (see argument there).
543     }
544 
545     /// Lazily clear `labels_at_tail` if the tail offset has moved beyond the
546     /// offset that it applies to.
547     fn lazily_clear_labels_at_tail(&mut self) {
548         let offset = self.cur_offset();
549         if offset > self.labels_at_tail_off {
550             self.labels_at_tail_off = offset;
551             self.labels_at_tail.clear();
552         }
553 
554         // Post-invariant: either labels_at_tail_off was at cur_offset, and
555         // state is untouched, or was less than cur_offset, in which case the
556         // labels_at_tail list was conceptually empty, and is now actually
557         // empty.
558     }
559 
560     /// Resolve a label to an offset, if known. May return `UNKNOWN_LABEL_OFFSET`.
561     pub(crate) fn resolve_label_offset(&self, mut label: MachLabel) -> CodeOffset {
562         let mut iters = 0;
563         while self.label_aliases[label.0 as usize] != UNKNOWN_LABEL {
564             label = self.label_aliases[label.0 as usize];
565             // To protect against an infinite loop (despite our assurances to
566             // ourselves that the invariants make this impossible), assert out
567             // after 1M iterations. The number of basic blocks is limited
568             // in most contexts anyway so this should be impossible to hit with
569             // a legitimate input.
570             iters += 1;
571             assert!(iters < 1_000_000, "Unexpected cycle in label aliases");
572         }
573         self.label_offsets[label.0 as usize]
574 
575         // Post-invariant: no mutations.
576     }
577 
578     /// Emit a reference to the given label with the given reference type (i.e.,
579     /// branch-instruction format) at the current offset.  This is like a
580     /// relocation, but handled internally.
581     ///
582     /// This can be called before the branch is actually emitted; fixups will
583     /// not happen until an island is emitted or the buffer is finished.
584     pub fn use_label_at_offset(&mut self, offset: CodeOffset, label: MachLabel, kind: I::LabelUse) {
585         trace!(
586             "MachBuffer: use_label_at_offset: offset {} label {:?} kind {:?}",
587             offset,
588             label,
589             kind
590         );
591 
592         // Add the fixup, and update the worst-case island size based on a
593         // veneer for this label use.
594         self.fixup_records.push(MachLabelFixup {
595             label,
596             offset,
597             kind,
598         });
599         if kind.supports_veneer() {
600             self.island_worst_case_size += kind.veneer_size();
601             self.island_worst_case_size &= !(I::LabelUse::ALIGN - 1);
602         }
603         let deadline = offset.saturating_add(kind.max_pos_range());
604         if deadline < self.island_deadline {
605             self.island_deadline = deadline;
606         }
607 
608         // Post-invariant: no mutations to branches/labels data structures.
609     }
610 
611     /// Inform the buffer of an unconditional branch at the given offset,
612     /// targetting the given label. May be used to optimize branches.
613     /// The last added label-use must correspond to this branch.
614     /// This must be called when the current offset is equal to `start`; i.e.,
615     /// before actually emitting the branch. This implies that for a branch that
616     /// uses a label and is eligible for optimizations by the MachBuffer, the
617     /// proper sequence is:
618     ///
619     /// - Call `use_label_at_offset()` to emit the fixup record.
620     /// - Call `add_uncond_branch()` to make note of the branch.
621     /// - Emit the bytes for the branch's machine code.
622     ///
623     /// Additional requirement: no labels may be bound between `start` and `end`
624     /// (exclusive on both ends).
625     pub fn add_uncond_branch(&mut self, start: CodeOffset, end: CodeOffset, target: MachLabel) {
626         assert!(self.cur_offset() == start);
627         debug_assert!(end > start);
628         assert!(!self.fixup_records.is_empty());
629         let fixup = self.fixup_records.len() - 1;
630         self.lazily_clear_labels_at_tail();
631         self.latest_branches.push(MachBranch {
632             start,
633             end,
634             target,
635             fixup,
636             inverted: None,
637             labels_at_this_branch: self.labels_at_tail.clone(),
638         });
639 
640         // Post-invariant: we asserted branch start is current tail; the list of
641         // labels at branch is cloned from list of labels at current tail.
642     }
643 
644     /// Inform the buffer of a conditional branch at the given offset,
645     /// targetting the given label. May be used to optimize branches.
646     /// The last added label-use must correspond to this branch.
647     ///
648     /// Additional requirement: no labels may be bound between `start` and `end`
649     /// (exclusive on both ends).
650     pub fn add_cond_branch(
651         &mut self,
652         start: CodeOffset,
653         end: CodeOffset,
654         target: MachLabel,
655         inverted: &[u8],
656     ) {
657         assert!(self.cur_offset() == start);
658         debug_assert!(end > start);
659         assert!(!self.fixup_records.is_empty());
660         debug_assert!(inverted.len() == (end - start) as usize);
661         let fixup = self.fixup_records.len() - 1;
662         let inverted = Some(SmallVec::from(inverted));
663         self.lazily_clear_labels_at_tail();
664         self.latest_branches.push(MachBranch {
665             start,
666             end,
667             target,
668             fixup,
669             inverted,
670             labels_at_this_branch: self.labels_at_tail.clone(),
671         });
672 
673         // Post-invariant: we asserted branch start is current tail; labels at
674         // branch list is cloned from list of labels at current tail.
675     }
676 
677     fn truncate_last_branch(&mut self) {
678         self.lazily_clear_labels_at_tail();
679         // Invariants hold at this point.
680 
681         let b = self.latest_branches.pop().unwrap();
682         assert!(b.end == self.cur_offset());
683 
684         // State:
685         //    [PRE CODE]
686         //  Offset b.start, b.labels_at_this_branch:
687         //    [BRANCH CODE]
688         //  cur_off, self.labels_at_tail -->
689         //    (end of buffer)
690         self.data.truncate(b.start as usize);
691         self.fixup_records.truncate(b.fixup);
692         while let Some(mut last_srcloc) = self.srclocs.last_mut() {
693             if last_srcloc.end <= b.start {
694                 break;
695             }
696             if last_srcloc.start < b.start {
697                 last_srcloc.end = b.start;
698                 break;
699             }
700             self.srclocs.pop();
701         }
702         // State:
703         //    [PRE CODE]
704         //  cur_off, Offset b.start, b.labels_at_this_branch:
705         //    (end of buffer)
706         //
707         //  self.labels_at_tail -->  (past end of buffer)
708         let cur_off = self.cur_offset();
709         self.labels_at_tail_off = cur_off;
710         // State:
711         //    [PRE CODE]
712         //  cur_off, Offset b.start, b.labels_at_this_branch,
713         //  self.labels_at_tail:
714         //    (end of buffer)
715         //
716         // resolve_label_offset(l) for l in labels_at_tail:
717         //    (past end of buffer)
718 
719         trace!(
720             "truncate_last_branch: truncated {:?}; off now {}",
721             b,
722             cur_off
723         );
724 
725         // Fix up resolved label offsets for labels at tail.
726         for &l in &self.labels_at_tail {
727             self.label_offsets[l.0 as usize] = cur_off;
728         }
729         // Old labels_at_this_branch are now at cur_off.
730         self.labels_at_tail
731             .extend(b.labels_at_this_branch.into_iter());
732 
733         // Post-invariant: this operation is defined to truncate the buffer,
734         // which moves cur_off backward, and to move labels at the end of the
735         // buffer back to the start-of-branch offset.
736         //
737         // latest_branches satisfies all invariants:
738         // - it has no branches past the end of the buffer (branches are in
739         //   order, we removed the last one, and we truncated the buffer to just
740         //   before the start of that branch)
741         // - no labels were moved to lower offsets than the (new) cur_off, so
742         //   the labels_at_this_branch list for any other branch need not change.
743         //
744         // labels_at_tail satisfies all invariants:
745         // - all labels that were at the tail after the truncated branch are
746         //   moved backward to just before the branch, which becomes the new tail;
747         //   thus every element in the list should remain (ensured by `.extend()`
748         //   above).
749         // - all labels that refer to the new tail, which is the start-offset of
750         //   the truncated branch, must be present. The `labels_at_this_branch`
751         //   list in the truncated branch's record is a complete and precise list
752         //   of exactly these labels; we append these to labels_at_tail.
753         // - labels_at_tail_off is at cur_off after truncation occurs, so the
754         //   list is valid (not to be lazily cleared).
755         //
756         // The stated operation was performed:
757         // - For each label at the end of the buffer prior to this method, it
758         //   now resolves to the new (truncated) end of the buffer: it must have
759         //   been in `labels_at_tail` (this list is precise and complete, and
760         //   the tail was at the end of the truncated branch on entry), and we
761         //   iterate over this list and set `label_offsets` to the new tail.
762         //   None of these labels could have been an alias (by invariant), so
763         //   `label_offsets` is authoritative for each.
764         // - No other labels will be past the end of the buffer, because of the
765         //   requirement that no labels be bound to the middle of branch ranges
766         //   (see comments to `add_{cond,uncond}_branch()`).
767         // - The buffer is truncated to just before the last branch, and the
768         //   fixup record referring to that last branch is removed.
769     }
770 
771     fn optimize_branches(&mut self) {
772         self.lazily_clear_labels_at_tail();
773         // Invariants valid at this point.
774 
775         trace!(
776             "enter optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}",
777             self.latest_branches,
778             self.labels_at_tail,
779             self.fixup_records
780         );
781 
782         // We continue to munch on branches at the tail of the buffer until no
783         // more rules apply. Note that the loop only continues if a branch is
784         // actually truncated (or if labels are redirected away from a branch),
785         // so this always makes progress.
786         while let Some(b) = self.latest_branches.last() {
787             let cur_off = self.cur_offset();
788             trace!("optimize_branches: last branch {:?} at off {}", b, cur_off);
789             // If there has been any code emission since the end of the last branch or
790             // label definition, then there's nothing we can edit (because we
791             // don't move code once placed, only back up and overwrite), so
792             // clear the records and finish.
793             if b.end < cur_off {
794                 break;
795             }
796 
797             // If the "labels at this branch" list on this branch is
798             // longer than a threshold, don't do any simplification,
799             // and let the branch remain to separate those labels from
800             // the current tail. This avoids quadratic behavior (see
801             // #3468): otherwise, if a long string of "goto next;
802             // next:" patterns are emitted, all of the labels will
803             // coalesce into a long list of aliases for the current
804             // buffer tail. We must track all aliases of the current
805             // tail for correctness, but we are also allowed to skip
806             // optimization (removal) of any branch, so we take the
807             // escape hatch here and let it stand. In effect this
808             // "spreads" the many thousands of labels in the
809             // pathological case among an actual (harmless but
810             // suboptimal) instruction once per N labels.
811             if b.labels_at_this_branch.len() > LABEL_LIST_THRESHOLD {
812                 break;
813             }
814 
815             // Invariant: we are looking at a branch that ends at the tail of
816             // the buffer.
817 
818             // For any branch, conditional or unconditional:
819             // - If the target is a label at the current offset, then remove
820             //   the conditional branch, and reset all labels that targetted
821             //   the current offset (end of branch) to the truncated
822             //   end-of-code.
823             //
824             // Preserves execution semantics: a branch to its own fallthrough
825             // address is equivalent to a no-op; in both cases, nextPC is the
826             // fallthrough.
827             if self.resolve_label_offset(b.target) == cur_off {
828                 trace!("branch with target == cur off; truncating");
829                 self.truncate_last_branch();
830                 continue;
831             }
832 
833             // If latest is an unconditional branch:
834             //
835             // - If the branch's target is not its own start address, then for
836             //   each label at the start of branch, make the label an alias of the
837             //   branch target, and remove the label from the "labels at this
838             //   branch" list.
839             //
840             //   - Preserves execution semantics: an unconditional branch's
841             //     only effect is to set PC to a new PC; this change simply
842             //     collapses one step in the step-semantics.
843             //
844             //   - Post-invariant: the labels that were bound to the start of
845             //     this branch become aliases, so they must not be present in any
846             //     labels-at-this-branch list or the labels-at-tail list. The
847             //     labels are removed form the latest-branch record's
848             //     labels-at-this-branch list, and are never placed in the
849             //     labels-at-tail list. Furthermore, it is correct that they are
850             //     not in either list, because they are now aliases, and labels
851             //     that are aliases remain aliases forever.
852             //
853             // - If there is a prior unconditional branch that ends just before
854             //   this one begins, and this branch has no labels bound to its
855             //   start, then we can truncate this branch, because it is entirely
856             //   unreachable (we have redirected all labels that make it
857             //   reachable otherwise). Do so and continue around the loop.
858             //
859             //   - Preserves execution semantics: the branch is unreachable,
860             //     because execution can only flow into an instruction from the
861             //     prior instruction's fallthrough or from a branch bound to that
862             //     instruction's start offset. Unconditional branches have no
863             //     fallthrough, so if the prior instruction is an unconditional
864             //     branch, no fallthrough entry can happen. The
865             //     labels-at-this-branch list is complete (by invariant), so if it
866             //     is empty, then the instruction is entirely unreachable. Thus,
867             //     it can be removed.
868             //
869             //   - Post-invariant: ensured by truncate_last_branch().
870             //
871             // - If there is a prior conditional branch whose target label
872             //   resolves to the current offset (branches around the
873             //   unconditional branch), then remove the unconditional branch,
874             //   and make the target of the unconditional the target of the
875             //   conditional instead.
876             //
877             //   - Preserves execution semantics: previously we had:
878             //
879             //         L1:
880             //            cond_br L2
881             //            br L3
882             //         L2:
883             //            (end of buffer)
884             //
885             //     by removing the last branch, we have:
886             //
887             //         L1:
888             //            cond_br L2
889             //         L2:
890             //            (end of buffer)
891             //
892             //     we then fix up the records for the conditional branch to
893             //     have:
894             //
895             //         L1:
896             //           cond_br.inverted L3
897             //         L2:
898             //
899             //     In the original code, control flow reaches L2 when the
900             //     conditional branch's predicate is true, and L3 otherwise. In
901             //     the optimized code, the same is true.
902             //
903             //   - Post-invariant: all edits to latest_branches and
904             //     labels_at_tail are performed by `truncate_last_branch()`,
905             //     which maintains the invariants at each step.
906 
907             if b.is_uncond() {
908                 // Set any label equal to current branch's start as an alias of
909                 // the branch's target, if the target is not the branch itself
910                 // (i.e., an infinite loop).
911                 //
912                 // We cannot perform this aliasing if the target of this branch
913                 // ultimately aliases back here; if so, we need to keep this
914                 // branch, so break out of this loop entirely (and clear the
915                 // latest-branches list below).
916                 //
917                 // Note that this check is what prevents cycles from forming in
918                 // `self.label_aliases`. To see why, consider an arbitrary start
919                 // state:
920                 //
921                 // label_aliases[L1] = L2, label_aliases[L2] = L3, ..., up to
922                 // Ln, which is not aliased.
923                 //
924                 // We would create a cycle if we assigned label_aliases[Ln]
925                 // = L1.  Note that the below assignment is the only write
926                 // to label_aliases.
927                 //
928                 // By our other invariants, we have that Ln (`l` below)
929                 // resolves to the offset `b.start`, because it is in the
930                 // set `b.labels_at_this_branch`.
931                 //
932                 // If L1 were already aliased, through some arbitrarily deep
933                 // chain, to Ln, then it must also resolve to this offset
934                 // `b.start`.
935                 //
936                 // By checking the resolution of `L1` against this offset,
937                 // and aborting this branch-simplification if they are
938                 // equal, we prevent the below assignment from ever creating
939                 // a cycle.
940                 if self.resolve_label_offset(b.target) != b.start {
941                     let redirected = b.labels_at_this_branch.len();
942                     for &l in &b.labels_at_this_branch {
943                         trace!(
944                             " -> label at start of branch {:?} redirected to target {:?}",
945                             l,
946                             b.target
947                         );
948                         self.label_aliases[l.0 as usize] = b.target;
949                         // NOTE: we continue to ensure the invariant that labels
950                         // pointing to tail of buffer are in `labels_at_tail`
951                         // because we already ensured above that the last branch
952                         // cannot have a target of `cur_off`; so we never have
953                         // to put the label into `labels_at_tail` when moving it
954                         // here.
955                     }
956                     // Maintain invariant: all branches have been redirected
957                     // and are no longer pointing at the start of this branch.
958                     let mut_b = self.latest_branches.last_mut().unwrap();
959                     mut_b.labels_at_this_branch.clear();
960 
961                     if redirected > 0 {
962                         trace!(" -> after label redirects, restarting loop");
963                         continue;
964                     }
965                 } else {
966                     break;
967                 }
968 
969                 let b = self.latest_branches.last().unwrap();
970 
971                 // Examine any immediately preceding branch.
972                 if self.latest_branches.len() > 1 {
973                     let prev_b = &self.latest_branches[self.latest_branches.len() - 2];
974                     trace!(" -> more than one branch; prev_b = {:?}", prev_b);
975                     // This uncond is immediately after another uncond; we
976                     // should have already redirected labels to this uncond away
977                     // (but check to be sure); so we can truncate this uncond.
978                     if prev_b.is_uncond()
979                         && prev_b.end == b.start
980                         && b.labels_at_this_branch.is_empty()
981                     {
982                         trace!(" -> uncond follows another uncond; truncating");
983                         self.truncate_last_branch();
984                         continue;
985                     }
986 
987                     // This uncond is immediately after a conditional, and the
988                     // conditional's target is the end of this uncond, and we've
989                     // already redirected labels to this uncond away; so we can
990                     // truncate this uncond, flip the sense of the conditional, and
991                     // set the conditional's target (in `latest_branches` and in
992                     // `fixup_records`) to the uncond's target.
993                     if prev_b.is_cond()
994                         && prev_b.end == b.start
995                         && self.resolve_label_offset(prev_b.target) == cur_off
996                     {
997                         trace!(" -> uncond follows a conditional, and conditional's target resolves to current offset");
998                         // Save the target of the uncond (this becomes the
999                         // target of the cond), and truncate the uncond.
1000                         let target = b.target;
1001                         let data = prev_b.inverted.clone().unwrap();
1002                         self.truncate_last_branch();
1003 
1004                         // Mutate the code and cond branch.
1005                         let off_before_edit = self.cur_offset();
1006                         let prev_b = self.latest_branches.last_mut().unwrap();
1007                         let not_inverted = SmallVec::from(
1008                             &self.data[(prev_b.start as usize)..(prev_b.end as usize)],
1009                         );
1010 
1011                         // Low-level edit: replaces bytes of branch with
1012                         // inverted form. cur_off remains the same afterward, so
1013                         // we do not need to modify label data structures.
1014                         self.data.truncate(prev_b.start as usize);
1015                         self.data.extend_from_slice(&data[..]);
1016 
1017                         // Save the original code as the inversion of the
1018                         // inverted branch, in case we later edit this branch
1019                         // again.
1020                         prev_b.inverted = Some(not_inverted);
1021                         self.fixup_records[prev_b.fixup].label = target;
1022                         trace!(" -> reassigning target of condbr to {:?}", target);
1023                         prev_b.target = target;
1024                         debug_assert_eq!(off_before_edit, self.cur_offset());
1025                         continue;
1026                     }
1027                 }
1028             }
1029 
1030             // If we couldn't do anything with the last branch, then break.
1031             break;
1032         }
1033 
1034         self.purge_latest_branches();
1035 
1036         trace!(
1037             "leave optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}",
1038             self.latest_branches,
1039             self.labels_at_tail,
1040             self.fixup_records
1041         );
1042     }
1043 
1044     fn purge_latest_branches(&mut self) {
1045         // All of our branch simplification rules work only if a branch ends at
1046         // the tail of the buffer, with no following code; and branches are in
1047         // order in latest_branches; so if the last entry ends prior to
1048         // cur_offset, then clear all entries.
1049         let cur_off = self.cur_offset();
1050         if let Some(l) = self.latest_branches.last() {
1051             if l.end < cur_off {
1052                 trace!("purge_latest_branches: removing branch {:?}", l);
1053                 self.latest_branches.clear();
1054             }
1055         }
1056 
1057         // Post-invariant: no invariant requires any branch to appear in
1058         // `latest_branches`; it is always optional. The list-clear above thus
1059         // preserves all semantics.
1060     }
1061 
1062     /// Emit a constant at some point in the future, binding the given label to
1063     /// its offset. The constant will be placed at most `max_distance` from the
1064     /// current offset.
1065     pub fn defer_constant(
1066         &mut self,
1067         label: MachLabel,
1068         align: CodeOffset,
1069         data: &[u8],
1070         max_distance: CodeOffset,
1071     ) {
1072         trace!(
1073             "defer_constant: eventually emit {} bytes aligned to {} at label {:?}",
1074             data.len(),
1075             align,
1076             label
1077         );
1078         let deadline = self.cur_offset().saturating_add(max_distance);
1079         self.island_worst_case_size += data.len() as CodeOffset;
1080         self.island_worst_case_size =
1081             (self.island_worst_case_size + I::LabelUse::ALIGN - 1) & !(I::LabelUse::ALIGN - 1);
1082         self.pending_constants.push(MachLabelConstant {
1083             label,
1084             align,
1085             data: SmallVec::from(data),
1086         });
1087         if deadline < self.island_deadline {
1088             self.island_deadline = deadline;
1089         }
1090     }
1091 
1092     /// Is an island needed within the next N bytes?
1093     pub fn island_needed(&self, distance: CodeOffset) -> bool {
1094         self.worst_case_end_of_island(distance) > self.island_deadline
1095     }
1096 
1097     /// Returns the maximal offset that islands can reach if `distance` more
1098     /// bytes are appended.
1099     ///
1100     /// This is used to determine if veneers need insertions since jumps that
1101     /// can't reach past this point must get a veneer of some form.
1102     fn worst_case_end_of_island(&self, distance: CodeOffset) -> CodeOffset {
1103         self.cur_offset()
1104             .saturating_add(distance)
1105             .saturating_add(self.island_worst_case_size)
1106     }
1107 
1108     /// Emit all pending constants and required pending veneers.
1109     ///
1110     /// Should only be called if `island_needed()` returns true, i.e., if we
1111     /// actually reach a deadline. It's not necessarily a problem to do so
1112     /// otherwise but it may result in unnecessary work during emission.
1113     pub fn emit_island(&mut self, distance: CodeOffset) {
1114         self.emit_island_maybe_forced(false, distance);
1115     }
1116 
1117     /// Same as `emit_island`, but an internal API with a `force_veneers`
1118     /// argument to force all veneers to always get emitted for debugging.
1119     fn emit_island_maybe_forced(&mut self, force_veneers: bool, distance: CodeOffset) {
1120         // We're going to purge fixups, so no latest-branch editing can happen
1121         // anymore.
1122         self.latest_branches.clear();
1123 
1124         // Reset internal calculations about islands since we're going to
1125         // change the calculus as we apply fixups. The `forced_threshold` is
1126         // used here to determine whether jumps to unknown labels will require
1127         // a veneer or not.
1128         let forced_threshold = self.worst_case_end_of_island(distance);
1129         self.island_deadline = UNKNOWN_LABEL_OFFSET;
1130         self.island_worst_case_size = 0;
1131 
1132         // First flush out all constants so we have more labels in case fixups
1133         // are applied against these labels.
1134         for MachLabelConstant { label, align, data } in mem::take(&mut self.pending_constants) {
1135             self.align_to(align);
1136             self.bind_label(label);
1137             self.put_data(&data[..]);
1138         }
1139 
1140         for fixup in mem::take(&mut self.fixup_records) {
1141             trace!("emit_island: fixup {:?}", fixup);
1142             let MachLabelFixup {
1143                 label,
1144                 offset,
1145                 kind,
1146             } = fixup;
1147             let label_offset = self.resolve_label_offset(label);
1148             let start = offset as usize;
1149             let end = (offset + kind.patch_size()) as usize;
1150 
1151             if label_offset != UNKNOWN_LABEL_OFFSET {
1152                 // If the offset of the label for this fixup is known then
1153                 // we're going to do something here-and-now. We're either going
1154                 // to patch the original offset because it's an in-bounds jump,
1155                 // or we're going to generate a veneer, patch the fixup to jump
1156                 // to the veneer, and then keep going.
1157                 //
1158                 // If the label comes after the original fixup, then we should
1159                 // be guaranteed that the jump is in-bounds. Otherwise there's
1160                 // a bug somewhere because this method wasn't called soon
1161                 // enough. All forward-jumps are tracked and should get veneers
1162                 // before their deadline comes and they're unable to jump
1163                 // further.
1164                 //
1165                 // Otherwise if the label is before the fixup, then that's a
1166                 // backwards jump. If it's past the maximum negative range
1167                 // then we'll emit a veneer that to jump forward to which can
1168                 // then jump backwards.
1169                 let veneer_required = if label_offset >= offset {
1170                     assert!((label_offset - offset) <= kind.max_pos_range());
1171                     false
1172                 } else {
1173                     (offset - label_offset) > kind.max_neg_range()
1174                 };
1175                 trace!(
1176                     " -> label_offset = {}, known, required = {} (pos {} neg {})",
1177                     label_offset,
1178                     veneer_required,
1179                     kind.max_pos_range(),
1180                     kind.max_neg_range()
1181                 );
1182 
1183                 if (force_veneers && kind.supports_veneer()) || veneer_required {
1184                     self.emit_veneer(label, offset, kind);
1185                 } else {
1186                     let slice = &mut self.data[start..end];
1187                     trace!("patching in-range!");
1188                     kind.patch(slice, offset, label_offset);
1189                 }
1190             } else {
1191                 // If the offset of this label is not known at this time then
1192                 // there's one of two possibilities:
1193                 //
1194                 // * First we may be about to exceed the maximum jump range of
1195                 //   this fixup. In that case a veneer is inserted to buy some
1196                 //   more budget for the forward-jump. It's guaranteed that the
1197                 //   label will eventually come after where we're at, so we know
1198                 //   that the forward jump is necessary.
1199                 //
1200                 // * Otherwise we're still within range of the forward jump but
1201                 //   the precise target isn't known yet. In that case we
1202                 //   enqueue the fixup to get processed later.
1203                 if forced_threshold - offset > kind.max_pos_range() {
1204                     self.emit_veneer(label, offset, kind);
1205                 } else {
1206                     self.use_label_at_offset(offset, label, kind);
1207                 }
1208             }
1209         }
1210     }
1211 
1212     /// Emits a "veneer" the `kind` code at `offset` to jump to `label`.
1213     ///
1214     /// This will generate extra machine code, using `kind`, to get a
1215     /// larger-jump-kind than `kind` allows. The code at `offset` is then
1216     /// patched to jump to our new code, and then the new code is enqueued for
1217     /// a fixup to get processed at some later time.
1218     fn emit_veneer(&mut self, label: MachLabel, offset: CodeOffset, kind: I::LabelUse) {
1219         // If this `kind` doesn't support a veneer then that's a bug in the
1220         // backend because we need to implement support for such a veneer.
1221         assert!(
1222             kind.supports_veneer(),
1223             "jump beyond the range of {:?} but a veneer isn't supported",
1224             kind,
1225         );
1226 
1227         // Allocate space for a veneer in the island.
1228         self.align_to(I::LabelUse::ALIGN);
1229         let veneer_offset = self.cur_offset();
1230         trace!("making a veneer at {}", veneer_offset);
1231         let start = offset as usize;
1232         let end = (offset + kind.patch_size()) as usize;
1233         let slice = &mut self.data[start..end];
1234         // Patch the original label use to refer to the veneer.
1235         trace!(
1236             "patching original at offset {} to veneer offset {}",
1237             offset,
1238             veneer_offset
1239         );
1240         kind.patch(slice, offset, veneer_offset);
1241         // Generate the veneer.
1242         let veneer_slice = self.get_appended_space(kind.veneer_size() as usize);
1243         let (veneer_fixup_off, veneer_label_use) =
1244             kind.generate_veneer(veneer_slice, veneer_offset);
1245         trace!(
1246             "generated veneer; fixup offset {}, label_use {:?}",
1247             veneer_fixup_off,
1248             veneer_label_use
1249         );
1250         // Register a new use of `label` with our new veneer fixup and offset.
1251         // This'll recalculate deadlines accordingly and enqueue this fixup to
1252         // get processed at some later time.
1253         self.use_label_at_offset(veneer_fixup_off, label, veneer_label_use);
1254     }
1255 
1256     fn finish_emission_maybe_forcing_veneers(&mut self, force_veneers: bool) {
1257         while !self.pending_constants.is_empty() || !self.fixup_records.is_empty() {
1258             // `emit_island()` will emit any pending veneers and constants, and
1259             // as a side-effect, will also take care of any fixups with resolved
1260             // labels eagerly.
1261             self.emit_island_maybe_forced(force_veneers, u32::MAX);
1262         }
1263 
1264         // Ensure that all labels have been fixed up after the last island is emitted. This is a
1265         // full (release-mode) assert because an unresolved label means the emitted code is
1266         // incorrect.
1267         assert!(self.fixup_records.is_empty());
1268     }
1269 
1270     /// Finish any deferred emissions and/or fixups.
1271     pub fn finish(mut self) -> MachBufferFinalized<Stencil> {
1272         let _tt = timing::vcode_emit_finish();
1273 
1274         // Do any optimizations on branches at tail of buffer, as if we
1275         // had bound one last label.
1276         self.optimize_branches();
1277 
1278         self.finish_emission_maybe_forcing_veneers(false);
1279 
1280         let mut srclocs = self.srclocs;
1281         srclocs.sort_by_key(|entry| entry.start);
1282 
1283         MachBufferFinalized {
1284             data: self.data,
1285             relocs: self.relocs,
1286             traps: self.traps,
1287             call_sites: self.call_sites,
1288             srclocs,
1289             stack_maps: self.stack_maps,
1290             unwind_info: self.unwind_info,
1291         }
1292     }
1293 
1294     /// Add an external relocation at the current offset.
1295     pub fn add_reloc(&mut self, kind: Reloc, name: &ExternalName, addend: Addend) {
1296         let name = name.clone();
1297         // FIXME(#3277): This should use `I::LabelUse::from_reloc` to optionally
1298         // generate a label-use statement to track whether an island is possibly
1299         // needed to escape this function to actually get to the external name.
1300         // This is most likely to come up on AArch64 where calls between
1301         // functions use a 26-bit signed offset which gives +/- 64MB. This means
1302         // that if a function is 128MB in size and there's a call in the middle
1303         // it's impossible to reach the actual target. Also, while it's
1304         // technically possible to jump to the start of a function and then jump
1305         // further, island insertion below always inserts islands after
1306         // previously appended code so for Cranelift's own implementation this
1307         // is also a problem for 64MB functions on AArch64 which start with a
1308         // call instruction, those won't be able to escape.
1309         //
1310         // Ideally what needs to happen here is that a `LabelUse` is
1311         // transparently generated (or call-sites of this function are audited
1312         // to generate a `LabelUse` instead) and tracked internally. The actual
1313         // relocation would then change over time if and when a veneer is
1314         // inserted, where the relocation here would be patched by this
1315         // `MachBuffer` to jump to the veneer. The problem, though, is that all
1316         // this still needs to end up, in the case of a singular function,
1317         // generating a final relocation pointing either to this particular
1318         // relocation or to the veneer inserted. Additionally
1319         // `MachBuffer` needs the concept of a label which will never be
1320         // resolved, so `emit_island` doesn't trip over not actually ever
1321         // knowning what some labels are. Currently the loop in
1322         // `finish_emission_maybe_forcing_veneers` would otherwise infinitely
1323         // loop.
1324         //
1325         // For now this means that because relocs aren't tracked at all that
1326         // AArch64 functions have a rough size limits of 64MB. For now that's
1327         // somewhat reasonable and the failure mode is a panic in `MachBuffer`
1328         // when a relocation can't otherwise be resolved later, so it shouldn't
1329         // actually result in any memory unsafety or anything like that.
1330         self.relocs.push(MachReloc {
1331             offset: self.data.len() as CodeOffset,
1332             kind,
1333             name,
1334             addend,
1335         });
1336     }
1337 
1338     /// Add a trap record at the current offset.
1339     pub fn add_trap(&mut self, code: TrapCode) {
1340         self.traps.push(MachTrap {
1341             offset: self.data.len() as CodeOffset,
1342             code,
1343         });
1344     }
1345 
1346     /// Add a call-site record at the current offset.
1347     pub fn add_call_site(&mut self, opcode: Opcode) {
1348         debug_assert!(
1349             opcode.is_call(),
1350             "adding call site info for a non-call instruction."
1351         );
1352         self.call_sites.push(MachCallSite {
1353             ret_addr: self.data.len() as CodeOffset,
1354             opcode,
1355         });
1356     }
1357 
1358     /// Add an unwind record at the current offset.
1359     pub fn add_unwind(&mut self, unwind: UnwindInst) {
1360         self.unwind_info.push((self.cur_offset(), unwind));
1361     }
1362 
1363     /// Set the `SourceLoc` for code from this offset until the offset at the
1364     /// next call to `end_srcloc()`.
1365     pub fn start_srcloc(&mut self, loc: RelSourceLoc) {
1366         self.cur_srcloc = Some((self.cur_offset(), loc));
1367     }
1368 
1369     /// Mark the end of the `SourceLoc` segment started at the last
1370     /// `start_srcloc()` call.
1371     pub fn end_srcloc(&mut self) {
1372         let (start, loc) = self
1373             .cur_srcloc
1374             .take()
1375             .expect("end_srcloc() called without start_srcloc()");
1376         let end = self.cur_offset();
1377         // Skip zero-length extends.
1378         debug_assert!(end >= start);
1379         if end > start {
1380             self.srclocs.push(MachSrcLoc { start, end, loc });
1381         }
1382     }
1383 
1384     /// Add stack map metadata for this program point: a set of stack offsets
1385     /// (from SP upward) that contain live references.
1386     ///
1387     /// The `offset_to_fp` value is the offset from the nominal SP (at which the `stack_offsets`
1388     /// are based) and the FP value. By subtracting `offset_to_fp` from each `stack_offsets`
1389     /// element, one can obtain live-reference offsets from FP instead.
1390     pub fn add_stack_map(&mut self, extent: StackMapExtent, stack_map: StackMap) {
1391         let (start, end) = match extent {
1392             StackMapExtent::UpcomingBytes(insn_len) => {
1393                 let start_offset = self.cur_offset();
1394                 (start_offset, start_offset + insn_len)
1395             }
1396             StackMapExtent::StartedAtOffset(start_offset) => {
1397                 let end_offset = self.cur_offset();
1398                 debug_assert!(end_offset >= start_offset);
1399                 (start_offset, end_offset)
1400             }
1401         };
1402         trace!("Adding stack map for offsets {start:#x}..{end:#x}");
1403         self.stack_maps.push(MachStackMap {
1404             offset: start,
1405             offset_end: end,
1406             stack_map,
1407         });
1408     }
1409 }
1410 
1411 impl<T: CompilePhase> MachBufferFinalized<T> {
1412     /// Get a list of source location mapping tuples in sorted-by-start-offset order.
1413     pub fn get_srclocs_sorted(&self) -> &[T::MachSrcLocType] {
1414         &self.srclocs[..]
1415     }
1416 
1417     /// Get the total required size for the code.
1418     pub fn total_size(&self) -> CodeOffset {
1419         self.data.len() as CodeOffset
1420     }
1421 
1422     /// Return the code in this mach buffer as a hex string for testing purposes.
1423     pub fn stringify_code_bytes(&self) -> String {
1424         // This is pretty lame, but whatever ..
1425         use std::fmt::Write;
1426         let mut s = String::with_capacity(self.data.len() * 2);
1427         for b in &self.data {
1428             write!(&mut s, "{:02X}", b).unwrap();
1429         }
1430         s
1431     }
1432 
1433     /// Get the code bytes.
1434     pub fn data(&self) -> &[u8] {
1435         // N.B.: we emit every section into the .text section as far as
1436         // the `CodeSink` is concerned; we do not bother to segregate
1437         // the contents into the actual program text, the jumptable and the
1438         // rodata (constant pool). This allows us to generate code assuming
1439         // that these will not be relocated relative to each other, and avoids
1440         // having to designate each section as belonging in one of the three
1441         // fixed categories defined by `CodeSink`. If this becomes a problem
1442         // later (e.g. because of memory permissions or similar), we can
1443         // add this designation and segregate the output; take care, however,
1444         // to add the appropriate relocations in this case.
1445 
1446         &self.data[..]
1447     }
1448 
1449     /// Get the list of external relocations for this code.
1450     pub fn relocs(&self) -> &[MachReloc] {
1451         &self.relocs[..]
1452     }
1453 
1454     /// Get the list of trap records for this code.
1455     pub fn traps(&self) -> &[MachTrap] {
1456         &self.traps[..]
1457     }
1458 
1459     /// Get the stack map metadata for this code.
1460     pub fn stack_maps(&self) -> &[MachStackMap] {
1461         &self.stack_maps[..]
1462     }
1463 
1464     /// Get the list of call sites for this code.
1465     pub fn call_sites(&self) -> &[MachCallSite] {
1466         &self.call_sites[..]
1467     }
1468 }
1469 
1470 /// A constant that is deferred to the next constant-pool opportunity.
1471 struct MachLabelConstant {
1472     /// This label will refer to the constant's offset.
1473     label: MachLabel,
1474     /// Required alignment.
1475     align: CodeOffset,
1476     /// This data will be emitted when able.
1477     data: SmallVec<[u8; 16]>,
1478 }
1479 
1480 /// A fixup to perform on the buffer once code is emitted. Fixups always refer
1481 /// to labels and patch the code based on label offsets. Hence, they are like
1482 /// relocations, but internal to one buffer.
1483 #[derive(Debug)]
1484 struct MachLabelFixup<I: VCodeInst> {
1485     /// The label whose offset controls this fixup.
1486     label: MachLabel,
1487     /// The offset to fix up / patch to refer to this label.
1488     offset: CodeOffset,
1489     /// The kind of fixup. This is architecture-specific; each architecture may have,
1490     /// e.g., several types of branch instructions, each with differently-sized
1491     /// offset fields and different places within the instruction to place the
1492     /// bits.
1493     kind: I::LabelUse,
1494 }
1495 
1496 /// A relocation resulting from a compilation.
1497 #[derive(Clone, Debug, PartialEq)]
1498 #[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
1499 pub struct MachReloc {
1500     /// The offset at which the relocation applies, *relative to the
1501     /// containing section*.
1502     pub offset: CodeOffset,
1503     /// The kind of relocation.
1504     pub kind: Reloc,
1505     /// The external symbol / name to which this relocation refers.
1506     pub name: ExternalName,
1507     /// The addend to add to the symbol value.
1508     pub addend: i64,
1509 }
1510 
1511 /// A trap record resulting from a compilation.
1512 #[derive(Clone, Debug, PartialEq)]
1513 #[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
1514 pub struct MachTrap {
1515     /// The offset at which the trap instruction occurs, *relative to the
1516     /// containing section*.
1517     pub offset: CodeOffset,
1518     /// The trap code.
1519     pub code: TrapCode,
1520 }
1521 
1522 /// A call site record resulting from a compilation.
1523 #[derive(Clone, Debug, PartialEq)]
1524 #[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
1525 pub struct MachCallSite {
1526     /// The offset of the call's return address, *relative to the containing section*.
1527     pub ret_addr: CodeOffset,
1528     /// The call's opcode.
1529     pub opcode: Opcode,
1530 }
1531 
1532 /// A source-location mapping resulting from a compilation.
1533 #[derive(PartialEq, Debug, Clone)]
1534 #[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
1535 pub struct MachSrcLoc<T: CompilePhase> {
1536     /// The start of the region of code corresponding to a source location.
1537     /// This is relative to the start of the function, not to the start of the
1538     /// section.
1539     pub start: CodeOffset,
1540     /// The end of the region of code corresponding to a source location.
1541     /// This is relative to the start of the section, not to the start of the
1542     /// section.
1543     pub end: CodeOffset,
1544     /// The source location.
1545     pub loc: T::SourceLocType,
1546 }
1547 
1548 impl MachSrcLoc<Stencil> {
1549     fn apply_params(self, params: &FunctionParameters) -> MachSrcLoc<Final> {
1550         MachSrcLoc {
1551             start: self.start,
1552             end: self.end,
1553             loc: self.loc.expand(params.base_srcloc()),
1554         }
1555     }
1556 }
1557 
1558 /// Record of stack map metadata: stack offsets containing references.
1559 #[derive(Clone, Debug, PartialEq)]
1560 #[cfg_attr(feature = "enable-serde", derive(serde::Serialize, serde::Deserialize))]
1561 pub struct MachStackMap {
1562     /// The code offset at which this stack map applies.
1563     pub offset: CodeOffset,
1564     /// The code offset just past the "end" of the instruction: that is, the
1565     /// offset of the first byte of the following instruction, or equivalently,
1566     /// the start offset plus the instruction length.
1567     pub offset_end: CodeOffset,
1568     /// The stack map itself.
1569     pub stack_map: StackMap,
1570 }
1571 
1572 /// Record of branch instruction in the buffer, to facilitate editing.
1573 #[derive(Clone, Debug)]
1574 struct MachBranch {
1575     start: CodeOffset,
1576     end: CodeOffset,
1577     target: MachLabel,
1578     fixup: usize,
1579     inverted: Option<SmallVec<[u8; 8]>>,
1580     /// All labels pointing to the start of this branch. For correctness, this
1581     /// *must* be complete (i.e., must contain all labels whose resolved offsets
1582     /// are at the start of this branch): we rely on being able to redirect all
1583     /// labels that could jump to this branch before removing it, if it is
1584     /// otherwise unreachable.
1585     labels_at_this_branch: SmallVec<[MachLabel; 4]>,
1586 }
1587 
1588 impl MachBranch {
1589     fn is_cond(&self) -> bool {
1590         self.inverted.is_some()
1591     }
1592     fn is_uncond(&self) -> bool {
1593         self.inverted.is_none()
1594     }
1595 }
1596 
1597 /// Implementation of the `TextSectionBuilder` trait backed by `MachBuffer`.
1598 ///
1599 /// Note that `MachBuffer` was primarily written for intra-function references
1600 /// of jumps between basic blocks, but it's also quite usable for entire text
1601 /// sections and resolving references between functions themselves. This
1602 /// builder interprets "blocks" as labeled functions for the purposes of
1603 /// resolving labels internally in the buffer.
1604 pub struct MachTextSectionBuilder<I: VCodeInst> {
1605     buf: MachBuffer<I>,
1606     next_func: usize,
1607     force_veneers: bool,
1608 }
1609 
1610 impl<I: VCodeInst> MachTextSectionBuilder<I> {
1611     pub fn new(num_funcs: u32) -> MachTextSectionBuilder<I> {
1612         let mut buf = MachBuffer::new();
1613         buf.reserve_labels_for_blocks(num_funcs as usize);
1614         MachTextSectionBuilder {
1615             buf,
1616             next_func: 0,
1617             force_veneers: false,
1618         }
1619     }
1620 }
1621 
1622 impl<I: VCodeInst> TextSectionBuilder for MachTextSectionBuilder<I> {
1623     fn append(&mut self, named: bool, func: &[u8], align: Option<u32>) -> u64 {
1624         // Conditionally emit an island if it's necessary to resolve jumps
1625         // between functions which are too far away.
1626         let size = func.len() as u32;
1627         if self.force_veneers || self.buf.island_needed(size) {
1628             self.buf.emit_island_maybe_forced(self.force_veneers, size);
1629         }
1630 
1631         self.buf.align_to(align.unwrap_or(I::LabelUse::ALIGN));
1632         let pos = self.buf.cur_offset();
1633         if named {
1634             self.buf
1635                 .bind_label(MachLabel::from_block(BlockIndex::new(self.next_func)));
1636             self.next_func += 1;
1637         }
1638         self.buf.put_data(func);
1639         u64::from(pos)
1640     }
1641 
1642     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: u32) -> bool {
1643         let label = MachLabel::from_block(BlockIndex::new(target as usize));
1644         let offset = u32::try_from(offset).unwrap();
1645         match I::LabelUse::from_reloc(reloc, addend) {
1646             Some(label_use) => {
1647                 self.buf.use_label_at_offset(offset, label, label_use);
1648                 true
1649             }
1650             None => false,
1651         }
1652     }
1653 
1654     fn force_veneers(&mut self) {
1655         self.force_veneers = true;
1656     }
1657 
1658     fn finish(&mut self) -> Vec<u8> {
1659         // Double-check all functions were pushed.
1660         assert_eq!(self.next_func, self.buf.label_offsets.len());
1661 
1662         // Finish up any veneers, if necessary.
1663         self.buf
1664             .finish_emission_maybe_forcing_veneers(self.force_veneers);
1665 
1666         // We don't need the data any more, so return it to the caller.
1667         mem::take(&mut self.buf.data).into_vec()
1668     }
1669 }
1670 
1671 // We use an actual instruction definition to do tests, so we depend on the `arm64` feature here.
1672 #[cfg(all(test, feature = "arm64"))]
1673 mod test {
1674     use cranelift_entity::EntityRef as _;
1675 
1676     use super::*;
1677     use crate::ir::UserExternalNameRef;
1678     use crate::isa::aarch64::inst::xreg;
1679     use crate::isa::aarch64::inst::{BranchTarget, CondBrKind, EmitInfo, Inst};
1680     use crate::machinst::MachInstEmit;
1681     use crate::settings;
1682     use std::default::Default;
1683     use std::vec::Vec;
1684 
1685     fn label(n: u32) -> MachLabel {
1686         MachLabel::from_block(BlockIndex::new(n as usize))
1687     }
1688     fn target(n: u32) -> BranchTarget {
1689         BranchTarget::Label(label(n))
1690     }
1691 
1692     #[test]
1693     fn test_elide_jump_to_next() {
1694         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
1695         let mut buf = MachBuffer::new();
1696         let mut state = Default::default();
1697 
1698         buf.reserve_labels_for_blocks(2);
1699         buf.bind_label(label(0));
1700         let inst = Inst::Jump { dest: target(1) };
1701         inst.emit(&[], &mut buf, &info, &mut state);
1702         buf.bind_label(label(1));
1703         let buf = buf.finish();
1704         assert_eq!(0, buf.total_size());
1705     }
1706 
1707     #[test]
1708     fn test_elide_trivial_jump_blocks() {
1709         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
1710         let mut buf = MachBuffer::new();
1711         let mut state = Default::default();
1712 
1713         buf.reserve_labels_for_blocks(4);
1714 
1715         buf.bind_label(label(0));
1716         let inst = Inst::CondBr {
1717             kind: CondBrKind::NotZero(xreg(0)),
1718             taken: target(1),
1719             not_taken: target(2),
1720         };
1721         inst.emit(&[], &mut buf, &info, &mut state);
1722 
1723         buf.bind_label(label(1));
1724         let inst = Inst::Jump { dest: target(3) };
1725         inst.emit(&[], &mut buf, &info, &mut state);
1726 
1727         buf.bind_label(label(2));
1728         let inst = Inst::Jump { dest: target(3) };
1729         inst.emit(&[], &mut buf, &info, &mut state);
1730 
1731         buf.bind_label(label(3));
1732 
1733         let buf = buf.finish();
1734         assert_eq!(0, buf.total_size());
1735     }
1736 
1737     #[test]
1738     fn test_flip_cond() {
1739         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
1740         let mut buf = MachBuffer::new();
1741         let mut state = Default::default();
1742 
1743         buf.reserve_labels_for_blocks(4);
1744 
1745         buf.bind_label(label(0));
1746         let inst = Inst::CondBr {
1747             kind: CondBrKind::NotZero(xreg(0)),
1748             taken: target(1),
1749             not_taken: target(2),
1750         };
1751         inst.emit(&[], &mut buf, &info, &mut state);
1752 
1753         buf.bind_label(label(1));
1754         let inst = Inst::Udf {
1755             trap_code: TrapCode::Interrupt,
1756         };
1757         inst.emit(&[], &mut buf, &info, &mut state);
1758 
1759         buf.bind_label(label(2));
1760         let inst = Inst::Nop4;
1761         inst.emit(&[], &mut buf, &info, &mut state);
1762 
1763         buf.bind_label(label(3));
1764 
1765         let buf = buf.finish();
1766 
1767         let mut buf2 = MachBuffer::new();
1768         let mut state = Default::default();
1769         let inst = Inst::TrapIf {
1770             kind: CondBrKind::NotZero(xreg(0)),
1771             trap_code: TrapCode::Interrupt,
1772         };
1773         inst.emit(&[], &mut buf2, &info, &mut state);
1774         let inst = Inst::Nop4;
1775         inst.emit(&[], &mut buf2, &info, &mut state);
1776 
1777         let buf2 = buf2.finish();
1778 
1779         assert_eq!(buf.data, buf2.data);
1780     }
1781 
1782     #[test]
1783     fn test_island() {
1784         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
1785         let mut buf = MachBuffer::new();
1786         let mut state = Default::default();
1787 
1788         buf.reserve_labels_for_blocks(4);
1789 
1790         buf.bind_label(label(0));
1791         let inst = Inst::CondBr {
1792             kind: CondBrKind::NotZero(xreg(0)),
1793             taken: target(2),
1794             not_taken: target(3),
1795         };
1796         inst.emit(&[], &mut buf, &info, &mut state);
1797 
1798         buf.bind_label(label(1));
1799         while buf.cur_offset() < 2000000 {
1800             if buf.island_needed(0) {
1801                 buf.emit_island(0);
1802             }
1803             let inst = Inst::Nop4;
1804             inst.emit(&[], &mut buf, &info, &mut state);
1805         }
1806 
1807         buf.bind_label(label(2));
1808         let inst = Inst::Nop4;
1809         inst.emit(&[], &mut buf, &info, &mut state);
1810 
1811         buf.bind_label(label(3));
1812         let inst = Inst::Nop4;
1813         inst.emit(&[], &mut buf, &info, &mut state);
1814 
1815         let buf = buf.finish();
1816 
1817         assert_eq!(2000000 + 8, buf.total_size());
1818 
1819         let mut buf2 = MachBuffer::new();
1820         let mut state = Default::default();
1821         let inst = Inst::CondBr {
1822             kind: CondBrKind::NotZero(xreg(0)),
1823 
1824             // This conditionally taken branch has a 19-bit constant, shifted
1825             // to the left by two, giving us a 21-bit range in total. Half of
1826             // this range positive so the we should be around 1 << 20 bytes
1827             // away for our jump target.
1828             //
1829             // There are two pending fixups by the time we reach this point,
1830             // one for this 19-bit jump and one for the unconditional 26-bit
1831             // jump below. A 19-bit veneer is 4 bytes large and the 26-bit
1832             // veneer is 20 bytes large, which means that pessimistically
1833             // assuming we'll need two veneers we need 24 bytes of extra
1834             // space, meaning that the actual island should come 24-bytes
1835             // before the deadline.
1836             taken: BranchTarget::ResolvedOffset((1 << 20) - 4 - 20),
1837 
1838             // This branch is in-range so no veneers should be needed, it should
1839             // go directly to the target.
1840             not_taken: BranchTarget::ResolvedOffset(2000000 + 4 - 4),
1841         };
1842         inst.emit(&[], &mut buf2, &info, &mut state);
1843 
1844         let buf2 = buf2.finish();
1845 
1846         assert_eq!(&buf.data[0..8], &buf2.data[..]);
1847     }
1848 
1849     #[test]
1850     fn test_island_backward() {
1851         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
1852         let mut buf = MachBuffer::new();
1853         let mut state = Default::default();
1854 
1855         buf.reserve_labels_for_blocks(4);
1856 
1857         buf.bind_label(label(0));
1858         let inst = Inst::Nop4;
1859         inst.emit(&[], &mut buf, &info, &mut state);
1860 
1861         buf.bind_label(label(1));
1862         let inst = Inst::Nop4;
1863         inst.emit(&[], &mut buf, &info, &mut state);
1864 
1865         buf.bind_label(label(2));
1866         while buf.cur_offset() < 2000000 {
1867             let inst = Inst::Nop4;
1868             inst.emit(&[], &mut buf, &info, &mut state);
1869         }
1870 
1871         buf.bind_label(label(3));
1872         let inst = Inst::CondBr {
1873             kind: CondBrKind::NotZero(xreg(0)),
1874             taken: target(0),
1875             not_taken: target(1),
1876         };
1877         inst.emit(&[], &mut buf, &info, &mut state);
1878 
1879         let buf = buf.finish();
1880 
1881         assert_eq!(2000000 + 12, buf.total_size());
1882 
1883         let mut buf2 = MachBuffer::new();
1884         let mut state = Default::default();
1885         let inst = Inst::CondBr {
1886             kind: CondBrKind::NotZero(xreg(0)),
1887             taken: BranchTarget::ResolvedOffset(8),
1888             not_taken: BranchTarget::ResolvedOffset(4 - (2000000 + 4)),
1889         };
1890         inst.emit(&[], &mut buf2, &info, &mut state);
1891         let inst = Inst::Jump {
1892             dest: BranchTarget::ResolvedOffset(-(2000000 + 8)),
1893         };
1894         inst.emit(&[], &mut buf2, &info, &mut state);
1895 
1896         let buf2 = buf2.finish();
1897 
1898         assert_eq!(&buf.data[2000000..], &buf2.data[..]);
1899     }
1900 
1901     #[test]
1902     fn test_multiple_redirect() {
1903         // label0:
1904         //   cbz x0, label1
1905         //   b label2
1906         // label1:
1907         //   b label3
1908         // label2:
1909         //   nop
1910         //   nop
1911         //   b label0
1912         // label3:
1913         //   b label4
1914         // label4:
1915         //   b label5
1916         // label5:
1917         //   b label7
1918         // label6:
1919         //   nop
1920         // label7:
1921         //   ret
1922         //
1923         // -- should become:
1924         //
1925         // label0:
1926         //   cbz x0, label7
1927         // label2:
1928         //   nop
1929         //   nop
1930         //   b label0
1931         // label6:
1932         //   nop
1933         // label7:
1934         //   ret
1935 
1936         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
1937         let mut buf = MachBuffer::new();
1938         let mut state = Default::default();
1939 
1940         buf.reserve_labels_for_blocks(8);
1941 
1942         buf.bind_label(label(0));
1943         let inst = Inst::CondBr {
1944             kind: CondBrKind::Zero(xreg(0)),
1945             taken: target(1),
1946             not_taken: target(2),
1947         };
1948         inst.emit(&[], &mut buf, &info, &mut state);
1949 
1950         buf.bind_label(label(1));
1951         let inst = Inst::Jump { dest: target(3) };
1952         inst.emit(&[], &mut buf, &info, &mut state);
1953 
1954         buf.bind_label(label(2));
1955         let inst = Inst::Nop4;
1956         inst.emit(&[], &mut buf, &info, &mut state);
1957         inst.emit(&[], &mut buf, &info, &mut state);
1958         let inst = Inst::Jump { dest: target(0) };
1959         inst.emit(&[], &mut buf, &info, &mut state);
1960 
1961         buf.bind_label(label(3));
1962         let inst = Inst::Jump { dest: target(4) };
1963         inst.emit(&[], &mut buf, &info, &mut state);
1964 
1965         buf.bind_label(label(4));
1966         let inst = Inst::Jump { dest: target(5) };
1967         inst.emit(&[], &mut buf, &info, &mut state);
1968 
1969         buf.bind_label(label(5));
1970         let inst = Inst::Jump { dest: target(7) };
1971         inst.emit(&[], &mut buf, &info, &mut state);
1972 
1973         buf.bind_label(label(6));
1974         let inst = Inst::Nop4;
1975         inst.emit(&[], &mut buf, &info, &mut state);
1976 
1977         buf.bind_label(label(7));
1978         let inst = Inst::Ret { rets: vec![] };
1979         inst.emit(&[], &mut buf, &info, &mut state);
1980 
1981         let buf = buf.finish();
1982 
1983         let golden_data = vec![
1984             0xa0, 0x00, 0x00, 0xb4, // cbz x0, 0x14
1985             0x1f, 0x20, 0x03, 0xd5, // nop
1986             0x1f, 0x20, 0x03, 0xd5, // nop
1987             0xfd, 0xff, 0xff, 0x17, // b 0
1988             0x1f, 0x20, 0x03, 0xd5, // nop
1989             0xc0, 0x03, 0x5f, 0xd6, // ret
1990         ];
1991 
1992         assert_eq!(&golden_data[..], &buf.data[..]);
1993     }
1994 
1995     #[test]
1996     fn test_handle_branch_cycle() {
1997         // label0:
1998         //   b label1
1999         // label1:
2000         //   b label2
2001         // label2:
2002         //   b label3
2003         // label3:
2004         //   b label4
2005         // label4:
2006         //   b label1  // note: not label0 (to make it interesting).
2007         //
2008         // -- should become:
2009         //
2010         // label0, label1, ..., label4:
2011         //   b label0
2012         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2013         let mut buf = MachBuffer::new();
2014         let mut state = Default::default();
2015 
2016         buf.reserve_labels_for_blocks(5);
2017 
2018         buf.bind_label(label(0));
2019         let inst = Inst::Jump { dest: target(1) };
2020         inst.emit(&[], &mut buf, &info, &mut state);
2021 
2022         buf.bind_label(label(1));
2023         let inst = Inst::Jump { dest: target(2) };
2024         inst.emit(&[], &mut buf, &info, &mut state);
2025 
2026         buf.bind_label(label(2));
2027         let inst = Inst::Jump { dest: target(3) };
2028         inst.emit(&[], &mut buf, &info, &mut state);
2029 
2030         buf.bind_label(label(3));
2031         let inst = Inst::Jump { dest: target(4) };
2032         inst.emit(&[], &mut buf, &info, &mut state);
2033 
2034         buf.bind_label(label(4));
2035         let inst = Inst::Jump { dest: target(1) };
2036         inst.emit(&[], &mut buf, &info, &mut state);
2037 
2038         let buf = buf.finish();
2039 
2040         let golden_data = vec![
2041             0x00, 0x00, 0x00, 0x14, // b 0
2042         ];
2043 
2044         assert_eq!(&golden_data[..], &buf.data[..]);
2045     }
2046 
2047     #[test]
2048     fn metadata_records() {
2049         let mut buf = MachBuffer::<Inst>::new();
2050 
2051         buf.reserve_labels_for_blocks(1);
2052 
2053         buf.bind_label(label(0));
2054         buf.put1(1);
2055         buf.add_trap(TrapCode::HeapOutOfBounds);
2056         buf.put1(2);
2057         buf.add_trap(TrapCode::IntegerOverflow);
2058         buf.add_trap(TrapCode::IntegerDivisionByZero);
2059         buf.add_call_site(Opcode::Call);
2060         buf.add_reloc(
2061             Reloc::Abs4,
2062             &ExternalName::User(UserExternalNameRef::new(0)),
2063             0,
2064         );
2065         buf.put1(3);
2066         buf.add_reloc(
2067             Reloc::Abs8,
2068             &ExternalName::User(UserExternalNameRef::new(1)),
2069             1,
2070         );
2071         buf.put1(4);
2072 
2073         let buf = buf.finish();
2074 
2075         assert_eq!(buf.data(), &[1, 2, 3, 4]);
2076         assert_eq!(
2077             buf.traps()
2078                 .iter()
2079                 .map(|trap| (trap.offset, trap.code))
2080                 .collect::<Vec<_>>(),
2081             vec![
2082                 (1, TrapCode::HeapOutOfBounds),
2083                 (2, TrapCode::IntegerOverflow),
2084                 (2, TrapCode::IntegerDivisionByZero)
2085             ]
2086         );
2087         assert_eq!(
2088             buf.call_sites()
2089                 .iter()
2090                 .map(|call_site| (call_site.ret_addr, call_site.opcode))
2091                 .collect::<Vec<_>>(),
2092             vec![(2, Opcode::Call)]
2093         );
2094         assert_eq!(
2095             buf.relocs()
2096                 .iter()
2097                 .map(|reloc| (reloc.offset, reloc.kind))
2098                 .collect::<Vec<_>>(),
2099             vec![(2, Reloc::Abs4), (3, Reloc::Abs8)]
2100         );
2101     }
2102 }
2103