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