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, stack_map: Option<StackMap>) -> MachLabel { 1223 let label = self.get_label(); 1224 self.pending_traps.push(MachLabelTrap { 1225 label, 1226 code, 1227 stack_map, 1228 loc: self.cur_srcloc.map(|(_start, loc)| loc), 1229 }); 1230 label 1231 } 1232 1233 /// Is an island needed within the next N bytes? 1234 pub fn island_needed(&self, distance: CodeOffset) -> bool { 1235 let deadline = match self.fixup_records.peek() { 1236 Some(fixup) => fixup.deadline().min(self.pending_fixup_deadline), 1237 None => self.pending_fixup_deadline, 1238 }; 1239 deadline < u32::MAX && self.worst_case_end_of_island(distance) > deadline 1240 } 1241 1242 /// Returns the maximal offset that islands can reach if `distance` more 1243 /// bytes are appended. 1244 /// 1245 /// This is used to determine if veneers need insertions since jumps that 1246 /// can't reach past this point must get a veneer of some form. 1247 fn worst_case_end_of_island(&self, distance: CodeOffset) -> CodeOffset { 1248 // Assume that all fixups will require veneers and that the veneers are 1249 // the worst-case size for each platform. This is an over-generalization 1250 // to avoid iterating over the `fixup_records` list or maintaining 1251 // information about it as we go along. 1252 let island_worst_case_size = ((self.fixup_records.len() + self.pending_fixup_records.len()) 1253 as u32) 1254 * (I::LabelUse::worst_case_veneer_size()) 1255 + self.pending_constants_size 1256 + (self.pending_traps.len() * I::TRAP_OPCODE.len()) as u32; 1257 self.cur_offset() 1258 .saturating_add(distance) 1259 .saturating_add(island_worst_case_size) 1260 } 1261 1262 /// Emit all pending constants and required pending veneers. 1263 /// 1264 /// Should only be called if `island_needed()` returns true, i.e., if we 1265 /// actually reach a deadline. It's not necessarily a problem to do so 1266 /// otherwise but it may result in unnecessary work during emission. 1267 pub fn emit_island(&mut self, distance: CodeOffset, ctrl_plane: &mut ControlPlane) { 1268 self.emit_island_maybe_forced(ForceVeneers::No, distance, ctrl_plane); 1269 } 1270 1271 /// Same as `emit_island`, but an internal API with a `force_veneers` 1272 /// argument to force all veneers to always get emitted for debugging. 1273 fn emit_island_maybe_forced( 1274 &mut self, 1275 force_veneers: ForceVeneers, 1276 distance: CodeOffset, 1277 ctrl_plane: &mut ControlPlane, 1278 ) { 1279 // We're going to purge fixups, so no latest-branch editing can happen 1280 // anymore. 1281 self.latest_branches.clear(); 1282 1283 // End the current location tracking since anything emitted during this 1284 // function shouldn't be attributed to whatever the current source 1285 // location is. 1286 // 1287 // Note that the current source location, if it's set right now, will be 1288 // restored at the end of this island emission. 1289 let cur_loc = self.cur_srcloc.map(|(_, loc)| loc); 1290 if cur_loc.is_some() { 1291 self.end_srcloc(); 1292 } 1293 1294 let forced_threshold = self.worst_case_end_of_island(distance); 1295 1296 // First flush out all traps/constants so we have more labels in case 1297 // fixups are applied against these labels. 1298 // 1299 // Note that traps are placed first since this typically happens at the 1300 // end of the function and for disassemblers we try to keep all the code 1301 // contiguously together. 1302 for MachLabelTrap { 1303 label, 1304 code, 1305 stack_map, 1306 loc, 1307 } in mem::take(&mut self.pending_traps) 1308 { 1309 // If this trap has source information associated with it then 1310 // emit this information for the trap instruction going out now too. 1311 if let Some(loc) = loc { 1312 self.start_srcloc(loc); 1313 } 1314 self.align_to(I::LabelUse::ALIGN); 1315 self.bind_label(label, ctrl_plane); 1316 self.add_trap(code); 1317 if let Some(map) = stack_map { 1318 let extent = StackMapExtent::UpcomingBytes(I::TRAP_OPCODE.len() as u32); 1319 self.add_stack_map(extent, map); 1320 } 1321 self.put_data(I::TRAP_OPCODE); 1322 if loc.is_some() { 1323 self.end_srcloc(); 1324 } 1325 } 1326 1327 for constant in mem::take(&mut self.pending_constants) { 1328 let MachBufferConstant { align, size, .. } = self.constants[constant]; 1329 let label = self.constants[constant].upcoming_label.take().unwrap(); 1330 self.align_to(align); 1331 self.bind_label(label, ctrl_plane); 1332 self.used_constants.push((constant, self.cur_offset())); 1333 self.get_appended_space(size); 1334 } 1335 1336 // Either handle all pending fixups because they're ready or move them 1337 // onto the `BinaryHeap` tracking all pending fixups if they aren't 1338 // ready. 1339 assert!(self.latest_branches.is_empty()); 1340 for fixup in mem::take(&mut self.pending_fixup_records) { 1341 if self.should_apply_fixup(&fixup, forced_threshold) { 1342 self.handle_fixup(fixup, force_veneers, forced_threshold); 1343 } else { 1344 self.fixup_records.push(fixup); 1345 } 1346 } 1347 self.pending_fixup_deadline = u32::MAX; 1348 while let Some(fixup) = self.fixup_records.peek() { 1349 trace!("emit_island: fixup {:?}", fixup); 1350 1351 // If this fixup shouldn't be applied, that means its label isn't 1352 // defined yet and there'll be remaining space to apply a veneer if 1353 // necessary in the future after this island. In that situation 1354 // because `fixup_records` is sorted by deadline this loop can 1355 // exit. 1356 if !self.should_apply_fixup(fixup, forced_threshold) { 1357 break; 1358 } 1359 1360 let fixup = self.fixup_records.pop().unwrap(); 1361 self.handle_fixup(fixup, force_veneers, forced_threshold); 1362 } 1363 1364 if let Some(loc) = cur_loc { 1365 self.start_srcloc(loc); 1366 } 1367 } 1368 1369 fn should_apply_fixup(&self, fixup: &MachLabelFixup<I>, forced_threshold: CodeOffset) -> bool { 1370 let label_offset = self.resolve_label_offset(fixup.label); 1371 label_offset != UNKNOWN_LABEL_OFFSET || fixup.deadline() < forced_threshold 1372 } 1373 1374 fn handle_fixup( 1375 &mut self, 1376 fixup: MachLabelFixup<I>, 1377 force_veneers: ForceVeneers, 1378 forced_threshold: CodeOffset, 1379 ) { 1380 let MachLabelFixup { 1381 label, 1382 offset, 1383 kind, 1384 } = fixup; 1385 let start = offset as usize; 1386 let end = (offset + kind.patch_size()) as usize; 1387 let label_offset = self.resolve_label_offset(label); 1388 1389 if label_offset != UNKNOWN_LABEL_OFFSET { 1390 // If the offset of the label for this fixup is known then 1391 // we're going to do something here-and-now. We're either going 1392 // to patch the original offset because it's an in-bounds jump, 1393 // or we're going to generate a veneer, patch the fixup to jump 1394 // to the veneer, and then keep going. 1395 // 1396 // If the label comes after the original fixup, then we should 1397 // be guaranteed that the jump is in-bounds. Otherwise there's 1398 // a bug somewhere because this method wasn't called soon 1399 // enough. All forward-jumps are tracked and should get veneers 1400 // before their deadline comes and they're unable to jump 1401 // further. 1402 // 1403 // Otherwise if the label is before the fixup, then that's a 1404 // backwards jump. If it's past the maximum negative range 1405 // then we'll emit a veneer that to jump forward to which can 1406 // then jump backwards. 1407 let veneer_required = if label_offset >= offset { 1408 assert!((label_offset - offset) <= kind.max_pos_range()); 1409 false 1410 } else { 1411 (offset - label_offset) > kind.max_neg_range() 1412 }; 1413 trace!( 1414 " -> label_offset = {}, known, required = {} (pos {} neg {})", 1415 label_offset, 1416 veneer_required, 1417 kind.max_pos_range(), 1418 kind.max_neg_range() 1419 ); 1420 1421 if (force_veneers == ForceVeneers::Yes && kind.supports_veneer()) || veneer_required { 1422 self.emit_veneer(label, offset, kind); 1423 } else { 1424 let slice = &mut self.data[start..end]; 1425 trace!("patching in-range!"); 1426 kind.patch(slice, offset, label_offset); 1427 } 1428 } else { 1429 // If the offset of this label is not known at this time then 1430 // that means that a veneer is required because after this 1431 // island the target can't be in range of the original target. 1432 assert!(forced_threshold - offset > kind.max_pos_range()); 1433 self.emit_veneer(label, offset, kind); 1434 } 1435 } 1436 1437 /// Emits a "veneer" the `kind` code at `offset` to jump to `label`. 1438 /// 1439 /// This will generate extra machine code, using `kind`, to get a 1440 /// larger-jump-kind than `kind` allows. The code at `offset` is then 1441 /// patched to jump to our new code, and then the new code is enqueued for 1442 /// a fixup to get processed at some later time. 1443 fn emit_veneer(&mut self, label: MachLabel, offset: CodeOffset, kind: I::LabelUse) { 1444 // If this `kind` doesn't support a veneer then that's a bug in the 1445 // backend because we need to implement support for such a veneer. 1446 assert!( 1447 kind.supports_veneer(), 1448 "jump beyond the range of {:?} but a veneer isn't supported", 1449 kind, 1450 ); 1451 1452 // Allocate space for a veneer in the island. 1453 self.align_to(I::LabelUse::ALIGN); 1454 let veneer_offset = self.cur_offset(); 1455 trace!("making a veneer at {}", veneer_offset); 1456 let start = offset as usize; 1457 let end = (offset + kind.patch_size()) as usize; 1458 let slice = &mut self.data[start..end]; 1459 // Patch the original label use to refer to the veneer. 1460 trace!( 1461 "patching original at offset {} to veneer offset {}", 1462 offset, 1463 veneer_offset 1464 ); 1465 kind.patch(slice, offset, veneer_offset); 1466 // Generate the veneer. 1467 let veneer_slice = self.get_appended_space(kind.veneer_size() as usize); 1468 let (veneer_fixup_off, veneer_label_use) = 1469 kind.generate_veneer(veneer_slice, veneer_offset); 1470 trace!( 1471 "generated veneer; fixup offset {}, label_use {:?}", 1472 veneer_fixup_off, 1473 veneer_label_use 1474 ); 1475 // Register a new use of `label` with our new veneer fixup and 1476 // offset. This'll recalculate deadlines accordingly and 1477 // enqueue this fixup to get processed at some later 1478 // time. 1479 self.use_label_at_offset(veneer_fixup_off, label, veneer_label_use); 1480 } 1481 1482 fn finish_emission_maybe_forcing_veneers( 1483 &mut self, 1484 force_veneers: ForceVeneers, 1485 ctrl_plane: &mut ControlPlane, 1486 ) { 1487 while !self.pending_constants.is_empty() 1488 || !self.pending_traps.is_empty() 1489 || !self.fixup_records.is_empty() 1490 || !self.pending_fixup_records.is_empty() 1491 { 1492 // `emit_island()` will emit any pending veneers and constants, and 1493 // as a side-effect, will also take care of any fixups with resolved 1494 // labels eagerly. 1495 self.emit_island_maybe_forced(force_veneers, u32::MAX, ctrl_plane); 1496 } 1497 1498 // Ensure that all labels have been fixed up after the last island is emitted. This is a 1499 // full (release-mode) assert because an unresolved label means the emitted code is 1500 // incorrect. 1501 assert!(self.fixup_records.is_empty()); 1502 assert!(self.pending_fixup_records.is_empty()); 1503 } 1504 1505 /// Finish any deferred emissions and/or fixups. 1506 pub fn finish( 1507 mut self, 1508 constants: &VCodeConstants, 1509 ctrl_plane: &mut ControlPlane, 1510 ) -> MachBufferFinalized<Stencil> { 1511 let _tt = timing::vcode_emit_finish(); 1512 1513 self.finish_emission_maybe_forcing_veneers(ForceVeneers::No, ctrl_plane); 1514 1515 let alignment = self.finish_constants(constants); 1516 1517 // Resolve all labels to their offsets. 1518 let finalized_relocs = self 1519 .relocs 1520 .iter() 1521 .map(|reloc| FinalizedMachReloc { 1522 offset: reloc.offset, 1523 kind: reloc.kind, 1524 addend: reloc.addend, 1525 target: match &reloc.target { 1526 RelocTarget::ExternalName(name) => { 1527 FinalizedRelocTarget::ExternalName(name.clone()) 1528 } 1529 RelocTarget::Label(label) => { 1530 FinalizedRelocTarget::Func(self.resolve_label_offset(*label)) 1531 } 1532 }, 1533 }) 1534 .collect(); 1535 1536 let mut srclocs = self.srclocs; 1537 srclocs.sort_by_key(|entry| entry.start); 1538 1539 MachBufferFinalized { 1540 data: self.data, 1541 relocs: finalized_relocs, 1542 traps: self.traps, 1543 call_sites: self.call_sites, 1544 srclocs, 1545 stack_maps: self.stack_maps, 1546 unwind_info: self.unwind_info, 1547 alignment, 1548 } 1549 } 1550 1551 /// Add an external relocation at the given offset from current offset. 1552 pub fn add_reloc_at_offset<T: Into<RelocTarget> + Clone>( 1553 &mut self, 1554 offset: CodeOffset, 1555 kind: Reloc, 1556 target: &T, 1557 addend: Addend, 1558 ) { 1559 let target: RelocTarget = target.clone().into(); 1560 // FIXME(#3277): This should use `I::LabelUse::from_reloc` to optionally 1561 // generate a label-use statement to track whether an island is possibly 1562 // needed to escape this function to actually get to the external name. 1563 // This is most likely to come up on AArch64 where calls between 1564 // functions use a 26-bit signed offset which gives +/- 64MB. This means 1565 // that if a function is 128MB in size and there's a call in the middle 1566 // it's impossible to reach the actual target. Also, while it's 1567 // technically possible to jump to the start of a function and then jump 1568 // further, island insertion below always inserts islands after 1569 // previously appended code so for Cranelift's own implementation this 1570 // is also a problem for 64MB functions on AArch64 which start with a 1571 // call instruction, those won't be able to escape. 1572 // 1573 // Ideally what needs to happen here is that a `LabelUse` is 1574 // transparently generated (or call-sites of this function are audited 1575 // to generate a `LabelUse` instead) and tracked internally. The actual 1576 // relocation would then change over time if and when a veneer is 1577 // inserted, where the relocation here would be patched by this 1578 // `MachBuffer` to jump to the veneer. The problem, though, is that all 1579 // this still needs to end up, in the case of a singular function, 1580 // generating a final relocation pointing either to this particular 1581 // relocation or to the veneer inserted. Additionally 1582 // `MachBuffer` needs the concept of a label which will never be 1583 // resolved, so `emit_island` doesn't trip over not actually ever 1584 // knowning what some labels are. Currently the loop in 1585 // `finish_emission_maybe_forcing_veneers` would otherwise infinitely 1586 // loop. 1587 // 1588 // For now this means that because relocs aren't tracked at all that 1589 // AArch64 functions have a rough size limits of 64MB. For now that's 1590 // somewhat reasonable and the failure mode is a panic in `MachBuffer` 1591 // when a relocation can't otherwise be resolved later, so it shouldn't 1592 // actually result in any memory unsafety or anything like that. 1593 self.relocs.push(MachReloc { 1594 offset: self.data.len() as CodeOffset + offset, 1595 kind, 1596 target, 1597 addend, 1598 }); 1599 } 1600 1601 /// Add an external relocation at the current offset. 1602 pub fn add_reloc<T: Into<RelocTarget> + Clone>( 1603 &mut self, 1604 kind: Reloc, 1605 target: &T, 1606 addend: Addend, 1607 ) { 1608 self.add_reloc_at_offset(0, kind, target, addend); 1609 } 1610 1611 /// Add a trap record at the current offset. 1612 pub fn add_trap(&mut self, code: TrapCode) { 1613 self.traps.push(MachTrap { 1614 offset: self.data.len() as CodeOffset, 1615 code, 1616 }); 1617 } 1618 1619 /// Add a call-site record at the current offset. 1620 pub fn add_call_site(&mut self, opcode: Opcode) { 1621 debug_assert!( 1622 opcode.is_call(), 1623 "adding call site info for a non-call instruction." 1624 ); 1625 self.call_sites.push(MachCallSite { 1626 ret_addr: self.data.len() as CodeOffset, 1627 opcode, 1628 }); 1629 } 1630 1631 /// Add an unwind record at the current offset. 1632 pub fn add_unwind(&mut self, unwind: UnwindInst) { 1633 self.unwind_info.push((self.cur_offset(), unwind)); 1634 } 1635 1636 /// Set the `SourceLoc` for code from this offset until the offset at the 1637 /// next call to `end_srcloc()`. 1638 /// Returns the current [CodeOffset] and [RelSourceLoc]. 1639 pub fn start_srcloc(&mut self, loc: RelSourceLoc) -> (CodeOffset, RelSourceLoc) { 1640 let cur = (self.cur_offset(), loc); 1641 self.cur_srcloc = Some(cur); 1642 cur 1643 } 1644 1645 /// Mark the end of the `SourceLoc` segment started at the last 1646 /// `start_srcloc()` call. 1647 pub fn end_srcloc(&mut self) { 1648 let (start, loc) = self 1649 .cur_srcloc 1650 .take() 1651 .expect("end_srcloc() called without start_srcloc()"); 1652 let end = self.cur_offset(); 1653 // Skip zero-length extends. 1654 debug_assert!(end >= start); 1655 if end > start { 1656 self.srclocs.push(MachSrcLoc { start, end, loc }); 1657 } 1658 } 1659 1660 /// Add stack map metadata for this program point: a set of stack offsets 1661 /// (from SP upward) that contain live references. 1662 /// 1663 /// The `offset_to_fp` value is the offset from the nominal SP (at which the `stack_offsets` 1664 /// are based) and the FP value. By subtracting `offset_to_fp` from each `stack_offsets` 1665 /// element, one can obtain live-reference offsets from FP instead. 1666 pub fn add_stack_map(&mut self, extent: StackMapExtent, stack_map: StackMap) { 1667 let (start, end) = match extent { 1668 StackMapExtent::UpcomingBytes(insn_len) => { 1669 let start_offset = self.cur_offset(); 1670 (start_offset, start_offset + insn_len) 1671 } 1672 StackMapExtent::StartedAtOffset(start_offset) => { 1673 let end_offset = self.cur_offset(); 1674 debug_assert!(end_offset >= start_offset); 1675 (start_offset, end_offset) 1676 } 1677 }; 1678 trace!("Adding stack map for offsets {start:#x}..{end:#x}: {stack_map:?}"); 1679 self.stack_maps.push(MachStackMap { 1680 offset: start, 1681 offset_end: end, 1682 stack_map, 1683 }); 1684 } 1685 } 1686 1687 impl<T: CompilePhase> MachBufferFinalized<T> { 1688 /// Get a list of source location mapping tuples in sorted-by-start-offset order. 1689 pub fn get_srclocs_sorted(&self) -> &[T::MachSrcLocType] { 1690 &self.srclocs[..] 1691 } 1692 1693 /// Get the total required size for the code. 1694 pub fn total_size(&self) -> CodeOffset { 1695 self.data.len() as CodeOffset 1696 } 1697 1698 /// Return the code in this mach buffer as a hex string for testing purposes. 1699 pub fn stringify_code_bytes(&self) -> String { 1700 // This is pretty lame, but whatever .. 1701 use std::fmt::Write; 1702 let mut s = String::with_capacity(self.data.len() * 2); 1703 for b in &self.data { 1704 write!(&mut s, "{:02X}", b).unwrap(); 1705 } 1706 s 1707 } 1708 1709 /// Get the code bytes. 1710 pub fn data(&self) -> &[u8] { 1711 // N.B.: we emit every section into the .text section as far as 1712 // the `CodeSink` is concerned; we do not bother to segregate 1713 // the contents into the actual program text, the jumptable and the 1714 // rodata (constant pool). This allows us to generate code assuming 1715 // that these will not be relocated relative to each other, and avoids 1716 // having to designate each section as belonging in one of the three 1717 // fixed categories defined by `CodeSink`. If this becomes a problem 1718 // later (e.g. because of memory permissions or similar), we can 1719 // add this designation and segregate the output; take care, however, 1720 // to add the appropriate relocations in this case. 1721 1722 &self.data[..] 1723 } 1724 1725 /// Get the list of external relocations for this code. 1726 pub fn relocs(&self) -> &[FinalizedMachReloc] { 1727 &self.relocs[..] 1728 } 1729 1730 /// Get the list of trap records for this code. 1731 pub fn traps(&self) -> &[MachTrap] { 1732 &self.traps[..] 1733 } 1734 1735 /// Get the stack map metadata for this code. 1736 pub fn stack_maps(&self) -> &[MachStackMap] { 1737 &self.stack_maps[..] 1738 } 1739 1740 /// Get the list of call sites for this code. 1741 pub fn call_sites(&self) -> &[MachCallSite] { 1742 &self.call_sites[..] 1743 } 1744 } 1745 1746 /// Metadata about a constant. 1747 struct MachBufferConstant { 1748 /// A label which has not yet been bound which can be used for this 1749 /// constant. 1750 /// 1751 /// This is lazily created when a label is requested for a constant and is 1752 /// cleared when a constant is emitted. 1753 upcoming_label: Option<MachLabel>, 1754 /// Required alignment. 1755 align: CodeOffset, 1756 /// The byte size of this constant. 1757 size: usize, 1758 } 1759 1760 /// A trap that is deferred to the next time an island is emitted for either 1761 /// traps, constants, or fixups. 1762 struct MachLabelTrap { 1763 /// This label will refer to the trap's offset. 1764 label: MachLabel, 1765 /// The code associated with this trap. 1766 code: TrapCode, 1767 /// An optional stack map to associate with this trap. 1768 stack_map: Option<StackMap>, 1769 /// An optional source location to assign for this trap. 1770 loc: Option<RelSourceLoc>, 1771 } 1772 1773 /// A fixup to perform on the buffer once code is emitted. Fixups always refer 1774 /// to labels and patch the code based on label offsets. Hence, they are like 1775 /// relocations, but internal to one buffer. 1776 #[derive(Debug)] 1777 struct MachLabelFixup<I: VCodeInst> { 1778 /// The label whose offset controls this fixup. 1779 label: MachLabel, 1780 /// The offset to fix up / patch to refer to this label. 1781 offset: CodeOffset, 1782 /// The kind of fixup. This is architecture-specific; each architecture may have, 1783 /// e.g., several types of branch instructions, each with differently-sized 1784 /// offset fields and different places within the instruction to place the 1785 /// bits. 1786 kind: I::LabelUse, 1787 } 1788 1789 impl<I: VCodeInst> MachLabelFixup<I> { 1790 fn deadline(&self) -> CodeOffset { 1791 self.offset.saturating_add(self.kind.max_pos_range()) 1792 } 1793 } 1794 1795 impl<I: VCodeInst> PartialEq for MachLabelFixup<I> { 1796 fn eq(&self, other: &Self) -> bool { 1797 self.deadline() == other.deadline() 1798 } 1799 } 1800 1801 impl<I: VCodeInst> Eq for MachLabelFixup<I> {} 1802 1803 impl<I: VCodeInst> PartialOrd for MachLabelFixup<I> { 1804 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 1805 Some(self.cmp(other)) 1806 } 1807 } 1808 1809 impl<I: VCodeInst> Ord for MachLabelFixup<I> { 1810 fn cmp(&self, other: &Self) -> Ordering { 1811 other.deadline().cmp(&self.deadline()) 1812 } 1813 } 1814 1815 /// A relocation resulting from a compilation. 1816 #[derive(Clone, Debug, PartialEq)] 1817 #[cfg_attr( 1818 feature = "enable-serde", 1819 derive(serde_derive::Serialize, serde_derive::Deserialize) 1820 )] 1821 pub struct MachRelocBase<T> { 1822 /// The offset at which the relocation applies, *relative to the 1823 /// containing section*. 1824 pub offset: CodeOffset, 1825 /// The kind of relocation. 1826 pub kind: Reloc, 1827 /// The external symbol / name to which this relocation refers. 1828 pub target: T, 1829 /// The addend to add to the symbol value. 1830 pub addend: i64, 1831 } 1832 1833 type MachReloc = MachRelocBase<RelocTarget>; 1834 1835 /// A relocation resulting from a compilation. 1836 pub type FinalizedMachReloc = MachRelocBase<FinalizedRelocTarget>; 1837 1838 /// A Relocation target 1839 #[derive(Debug, Clone, PartialEq, Eq, Hash)] 1840 pub enum RelocTarget { 1841 /// Points to an [ExternalName] outside the current function. 1842 ExternalName(ExternalName), 1843 /// Points to a [MachLabel] inside this function. 1844 /// This is different from [MachLabelFixup] in that both the relocation and the 1845 /// label will be emitted and are only resolved at link time. 1846 /// 1847 /// There is no reason to prefer this over [MachLabelFixup] unless the ABI requires it. 1848 Label(MachLabel), 1849 } 1850 1851 impl From<ExternalName> for RelocTarget { 1852 fn from(name: ExternalName) -> Self { 1853 Self::ExternalName(name) 1854 } 1855 } 1856 1857 impl From<MachLabel> for RelocTarget { 1858 fn from(label: MachLabel) -> Self { 1859 Self::Label(label) 1860 } 1861 } 1862 1863 /// A Relocation target 1864 #[derive(Debug, Clone, PartialEq, Eq, Hash)] 1865 #[cfg_attr( 1866 feature = "enable-serde", 1867 derive(serde_derive::Serialize, serde_derive::Deserialize) 1868 )] 1869 pub enum FinalizedRelocTarget { 1870 /// Points to an [ExternalName] outside the current function. 1871 ExternalName(ExternalName), 1872 /// Points to a [CodeOffset] from the start of the current function. 1873 Func(CodeOffset), 1874 } 1875 1876 impl FinalizedRelocTarget { 1877 /// Returns a display for the current [FinalizedRelocTarget], with extra context to prettify the 1878 /// output. 1879 pub fn display<'a>(&'a self, params: Option<&'a FunctionParameters>) -> String { 1880 match self { 1881 FinalizedRelocTarget::ExternalName(name) => format!("{}", name.display(params)), 1882 FinalizedRelocTarget::Func(offset) => format!("func+{offset}"), 1883 } 1884 } 1885 } 1886 1887 /// A trap record resulting from a compilation. 1888 #[derive(Clone, Debug, PartialEq)] 1889 #[cfg_attr( 1890 feature = "enable-serde", 1891 derive(serde_derive::Serialize, serde_derive::Deserialize) 1892 )] 1893 pub struct MachTrap { 1894 /// The offset at which the trap instruction occurs, *relative to the 1895 /// containing section*. 1896 pub offset: CodeOffset, 1897 /// The trap code. 1898 pub code: TrapCode, 1899 } 1900 1901 /// A call site record resulting from a compilation. 1902 #[derive(Clone, Debug, PartialEq)] 1903 #[cfg_attr( 1904 feature = "enable-serde", 1905 derive(serde_derive::Serialize, serde_derive::Deserialize) 1906 )] 1907 pub struct MachCallSite { 1908 /// The offset of the call's return address, *relative to the containing section*. 1909 pub ret_addr: CodeOffset, 1910 /// The call's opcode. 1911 pub opcode: Opcode, 1912 } 1913 1914 /// A source-location mapping resulting from a compilation. 1915 #[derive(PartialEq, Debug, Clone)] 1916 #[cfg_attr( 1917 feature = "enable-serde", 1918 derive(serde_derive::Serialize, serde_derive::Deserialize) 1919 )] 1920 pub struct MachSrcLoc<T: CompilePhase> { 1921 /// The start of the region of code corresponding to a source location. 1922 /// This is relative to the start of the function, not to the start of the 1923 /// section. 1924 pub start: CodeOffset, 1925 /// The end of the region of code corresponding to a source location. 1926 /// This is relative to the start of the section, not to the start of the 1927 /// section. 1928 pub end: CodeOffset, 1929 /// The source location. 1930 pub loc: T::SourceLocType, 1931 } 1932 1933 impl MachSrcLoc<Stencil> { 1934 fn apply_base_srcloc(self, base_srcloc: SourceLoc) -> MachSrcLoc<Final> { 1935 MachSrcLoc { 1936 start: self.start, 1937 end: self.end, 1938 loc: self.loc.expand(base_srcloc), 1939 } 1940 } 1941 } 1942 1943 /// Record of stack map metadata: stack offsets containing references. 1944 #[derive(Clone, Debug, PartialEq)] 1945 #[cfg_attr( 1946 feature = "enable-serde", 1947 derive(serde_derive::Serialize, serde_derive::Deserialize) 1948 )] 1949 pub struct MachStackMap { 1950 /// The code offset at which this stack map applies. 1951 pub offset: CodeOffset, 1952 /// The code offset just past the "end" of the instruction: that is, the 1953 /// offset of the first byte of the following instruction, or equivalently, 1954 /// the start offset plus the instruction length. 1955 pub offset_end: CodeOffset, 1956 /// The stack map itself. 1957 pub stack_map: StackMap, 1958 } 1959 1960 /// Record of branch instruction in the buffer, to facilitate editing. 1961 #[derive(Clone, Debug)] 1962 struct MachBranch { 1963 start: CodeOffset, 1964 end: CodeOffset, 1965 target: MachLabel, 1966 fixup: usize, 1967 inverted: Option<SmallVec<[u8; 8]>>, 1968 /// All labels pointing to the start of this branch. For correctness, this 1969 /// *must* be complete (i.e., must contain all labels whose resolved offsets 1970 /// are at the start of this branch): we rely on being able to redirect all 1971 /// labels that could jump to this branch before removing it, if it is 1972 /// otherwise unreachable. 1973 labels_at_this_branch: SmallVec<[MachLabel; 4]>, 1974 } 1975 1976 impl MachBranch { 1977 fn is_cond(&self) -> bool { 1978 self.inverted.is_some() 1979 } 1980 fn is_uncond(&self) -> bool { 1981 self.inverted.is_none() 1982 } 1983 } 1984 1985 /// Implementation of the `TextSectionBuilder` trait backed by `MachBuffer`. 1986 /// 1987 /// Note that `MachBuffer` was primarily written for intra-function references 1988 /// of jumps between basic blocks, but it's also quite usable for entire text 1989 /// sections and resolving references between functions themselves. This 1990 /// builder interprets "blocks" as labeled functions for the purposes of 1991 /// resolving labels internally in the buffer. 1992 pub struct MachTextSectionBuilder<I: VCodeInst> { 1993 buf: MachBuffer<I>, 1994 next_func: usize, 1995 force_veneers: ForceVeneers, 1996 } 1997 1998 impl<I: VCodeInst> MachTextSectionBuilder<I> { 1999 /// Creates a new text section builder which will have `num_funcs` functions 2000 /// pushed into it. 2001 pub fn new(num_funcs: usize) -> MachTextSectionBuilder<I> { 2002 let mut buf = MachBuffer::new(); 2003 buf.reserve_labels_for_blocks(num_funcs); 2004 MachTextSectionBuilder { 2005 buf, 2006 next_func: 0, 2007 force_veneers: ForceVeneers::No, 2008 } 2009 } 2010 } 2011 2012 impl<I: VCodeInst> TextSectionBuilder for MachTextSectionBuilder<I> { 2013 fn append( 2014 &mut self, 2015 labeled: bool, 2016 func: &[u8], 2017 align: u32, 2018 ctrl_plane: &mut ControlPlane, 2019 ) -> u64 { 2020 // Conditionally emit an island if it's necessary to resolve jumps 2021 // between functions which are too far away. 2022 let size = func.len() as u32; 2023 if self.force_veneers == ForceVeneers::Yes || self.buf.island_needed(size) { 2024 self.buf 2025 .emit_island_maybe_forced(self.force_veneers, size, ctrl_plane); 2026 } 2027 2028 self.buf.align_to(align); 2029 let pos = self.buf.cur_offset(); 2030 if labeled { 2031 self.buf.bind_label( 2032 MachLabel::from_block(BlockIndex::new(self.next_func)), 2033 ctrl_plane, 2034 ); 2035 self.next_func += 1; 2036 } 2037 self.buf.put_data(func); 2038 u64::from(pos) 2039 } 2040 2041 fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool { 2042 crate::trace!( 2043 "Resolving relocation @ {offset:#x} + {addend:#x} to target {target} of kind {reloc:?}" 2044 ); 2045 let label = MachLabel::from_block(BlockIndex::new(target)); 2046 let offset = u32::try_from(offset).unwrap(); 2047 match I::LabelUse::from_reloc(reloc, addend) { 2048 Some(label_use) => { 2049 self.buf.use_label_at_offset(offset, label, label_use); 2050 true 2051 } 2052 None => false, 2053 } 2054 } 2055 2056 fn force_veneers(&mut self) { 2057 self.force_veneers = ForceVeneers::Yes; 2058 } 2059 2060 fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8> { 2061 // Double-check all functions were pushed. 2062 assert_eq!(self.next_func, self.buf.label_offsets.len()); 2063 2064 // Finish up any veneers, if necessary. 2065 self.buf 2066 .finish_emission_maybe_forcing_veneers(self.force_veneers, ctrl_plane); 2067 2068 // We don't need the data any more, so return it to the caller. 2069 mem::take(&mut self.buf.data).into_vec() 2070 } 2071 } 2072 2073 // We use an actual instruction definition to do tests, so we depend on the `arm64` feature here. 2074 #[cfg(all(test, feature = "arm64"))] 2075 mod test { 2076 use cranelift_entity::EntityRef as _; 2077 2078 use super::*; 2079 use crate::ir::UserExternalNameRef; 2080 use crate::isa::aarch64::inst::xreg; 2081 use crate::isa::aarch64::inst::{BranchTarget, CondBrKind, EmitInfo, Inst}; 2082 use crate::machinst::{MachInstEmit, MachInstEmitState}; 2083 use crate::settings; 2084 2085 fn label(n: u32) -> MachLabel { 2086 MachLabel::from_block(BlockIndex::new(n as usize)) 2087 } 2088 fn target(n: u32) -> BranchTarget { 2089 BranchTarget::Label(label(n)) 2090 } 2091 2092 #[test] 2093 fn test_elide_jump_to_next() { 2094 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2095 let mut buf = MachBuffer::new(); 2096 let mut state = <Inst as MachInstEmit>::State::default(); 2097 let constants = Default::default(); 2098 2099 buf.reserve_labels_for_blocks(2); 2100 buf.bind_label(label(0), state.ctrl_plane_mut()); 2101 let inst = Inst::Jump { dest: target(1) }; 2102 inst.emit(&mut buf, &info, &mut state); 2103 buf.bind_label(label(1), state.ctrl_plane_mut()); 2104 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2105 assert_eq!(0, buf.total_size()); 2106 } 2107 2108 #[test] 2109 fn test_elide_trivial_jump_blocks() { 2110 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2111 let mut buf = MachBuffer::new(); 2112 let mut state = <Inst as MachInstEmit>::State::default(); 2113 let constants = Default::default(); 2114 2115 buf.reserve_labels_for_blocks(4); 2116 2117 buf.bind_label(label(0), state.ctrl_plane_mut()); 2118 let inst = Inst::CondBr { 2119 kind: CondBrKind::NotZero(xreg(0)), 2120 taken: target(1), 2121 not_taken: target(2), 2122 }; 2123 inst.emit(&mut buf, &info, &mut state); 2124 2125 buf.bind_label(label(1), state.ctrl_plane_mut()); 2126 let inst = Inst::Jump { dest: target(3) }; 2127 inst.emit(&mut buf, &info, &mut state); 2128 2129 buf.bind_label(label(2), state.ctrl_plane_mut()); 2130 let inst = Inst::Jump { dest: target(3) }; 2131 inst.emit(&mut buf, &info, &mut state); 2132 2133 buf.bind_label(label(3), state.ctrl_plane_mut()); 2134 2135 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2136 assert_eq!(0, buf.total_size()); 2137 } 2138 2139 #[test] 2140 fn test_flip_cond() { 2141 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2142 let mut buf = MachBuffer::new(); 2143 let mut state = <Inst as MachInstEmit>::State::default(); 2144 let constants = Default::default(); 2145 2146 buf.reserve_labels_for_blocks(4); 2147 2148 buf.bind_label(label(0), state.ctrl_plane_mut()); 2149 let inst = Inst::CondBr { 2150 kind: CondBrKind::Zero(xreg(0)), 2151 taken: target(1), 2152 not_taken: target(2), 2153 }; 2154 inst.emit(&mut buf, &info, &mut state); 2155 2156 buf.bind_label(label(1), state.ctrl_plane_mut()); 2157 let inst = Inst::Nop4; 2158 inst.emit(&mut buf, &info, &mut state); 2159 2160 buf.bind_label(label(2), state.ctrl_plane_mut()); 2161 let inst = Inst::Udf { 2162 trap_code: TrapCode::Interrupt, 2163 }; 2164 inst.emit(&mut buf, &info, &mut state); 2165 2166 buf.bind_label(label(3), state.ctrl_plane_mut()); 2167 2168 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2169 2170 let mut buf2 = MachBuffer::new(); 2171 let mut state = Default::default(); 2172 let inst = Inst::TrapIf { 2173 kind: CondBrKind::NotZero(xreg(0)), 2174 trap_code: TrapCode::Interrupt, 2175 }; 2176 inst.emit(&mut buf2, &info, &mut state); 2177 let inst = Inst::Nop4; 2178 inst.emit(&mut buf2, &info, &mut state); 2179 2180 let buf2 = buf2.finish(&constants, state.ctrl_plane_mut()); 2181 2182 assert_eq!(buf.data, buf2.data); 2183 } 2184 2185 #[test] 2186 fn test_island() { 2187 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2188 let mut buf = MachBuffer::new(); 2189 let mut state = <Inst as MachInstEmit>::State::default(); 2190 let constants = Default::default(); 2191 2192 buf.reserve_labels_for_blocks(4); 2193 2194 buf.bind_label(label(0), state.ctrl_plane_mut()); 2195 let inst = Inst::CondBr { 2196 kind: CondBrKind::NotZero(xreg(0)), 2197 taken: target(2), 2198 not_taken: target(3), 2199 }; 2200 inst.emit(&mut buf, &info, &mut state); 2201 2202 buf.bind_label(label(1), state.ctrl_plane_mut()); 2203 while buf.cur_offset() < 2000000 { 2204 if buf.island_needed(0) { 2205 buf.emit_island(0, state.ctrl_plane_mut()); 2206 } 2207 let inst = Inst::Nop4; 2208 inst.emit(&mut buf, &info, &mut state); 2209 } 2210 2211 buf.bind_label(label(2), state.ctrl_plane_mut()); 2212 let inst = Inst::Nop4; 2213 inst.emit(&mut buf, &info, &mut state); 2214 2215 buf.bind_label(label(3), state.ctrl_plane_mut()); 2216 let inst = Inst::Nop4; 2217 inst.emit(&mut buf, &info, &mut state); 2218 2219 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2220 2221 assert_eq!(2000000 + 8, buf.total_size()); 2222 2223 let mut buf2 = MachBuffer::new(); 2224 let mut state = Default::default(); 2225 let inst = Inst::CondBr { 2226 kind: CondBrKind::NotZero(xreg(0)), 2227 2228 // This conditionally taken branch has a 19-bit constant, shifted 2229 // to the left by two, giving us a 21-bit range in total. Half of 2230 // this range positive so the we should be around 1 << 20 bytes 2231 // away for our jump target. 2232 // 2233 // There are two pending fixups by the time we reach this point, 2234 // one for this 19-bit jump and one for the unconditional 26-bit 2235 // jump below. A 19-bit veneer is 4 bytes large and the 26-bit 2236 // veneer is 20 bytes large, which means that pessimistically 2237 // assuming we'll need two veneers. Currently each veneer is 2238 // pessimistically assumed to be the maximal size which means we 2239 // need 40 bytes of extra space, meaning that the actual island 2240 // should come 40-bytes before the deadline. 2241 taken: BranchTarget::ResolvedOffset((1 << 20) - 20 - 20), 2242 2243 // This branch is in-range so no veneers should be needed, it should 2244 // go directly to the target. 2245 not_taken: BranchTarget::ResolvedOffset(2000000 + 4 - 4), 2246 }; 2247 inst.emit(&mut buf2, &info, &mut state); 2248 2249 let buf2 = buf2.finish(&constants, state.ctrl_plane_mut()); 2250 2251 assert_eq!(&buf.data[0..8], &buf2.data[..]); 2252 } 2253 2254 #[test] 2255 fn test_island_backward() { 2256 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2257 let mut buf = MachBuffer::new(); 2258 let mut state = <Inst as MachInstEmit>::State::default(); 2259 let constants = Default::default(); 2260 2261 buf.reserve_labels_for_blocks(4); 2262 2263 buf.bind_label(label(0), state.ctrl_plane_mut()); 2264 let inst = Inst::Nop4; 2265 inst.emit(&mut buf, &info, &mut state); 2266 2267 buf.bind_label(label(1), state.ctrl_plane_mut()); 2268 let inst = Inst::Nop4; 2269 inst.emit(&mut buf, &info, &mut state); 2270 2271 buf.bind_label(label(2), state.ctrl_plane_mut()); 2272 while buf.cur_offset() < 2000000 { 2273 let inst = Inst::Nop4; 2274 inst.emit(&mut buf, &info, &mut state); 2275 } 2276 2277 buf.bind_label(label(3), state.ctrl_plane_mut()); 2278 let inst = Inst::CondBr { 2279 kind: CondBrKind::NotZero(xreg(0)), 2280 taken: target(0), 2281 not_taken: target(1), 2282 }; 2283 inst.emit(&mut buf, &info, &mut state); 2284 2285 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2286 2287 assert_eq!(2000000 + 12, buf.total_size()); 2288 2289 let mut buf2 = MachBuffer::new(); 2290 let mut state = Default::default(); 2291 let inst = Inst::CondBr { 2292 kind: CondBrKind::NotZero(xreg(0)), 2293 taken: BranchTarget::ResolvedOffset(8), 2294 not_taken: BranchTarget::ResolvedOffset(4 - (2000000 + 4)), 2295 }; 2296 inst.emit(&mut buf2, &info, &mut state); 2297 let inst = Inst::Jump { 2298 dest: BranchTarget::ResolvedOffset(-(2000000 + 8)), 2299 }; 2300 inst.emit(&mut buf2, &info, &mut state); 2301 2302 let buf2 = buf2.finish(&constants, state.ctrl_plane_mut()); 2303 2304 assert_eq!(&buf.data[2000000..], &buf2.data[..]); 2305 } 2306 2307 #[test] 2308 fn test_multiple_redirect() { 2309 // label0: 2310 // cbz x0, label1 2311 // b label2 2312 // label1: 2313 // b label3 2314 // label2: 2315 // nop 2316 // nop 2317 // b label0 2318 // label3: 2319 // b label4 2320 // label4: 2321 // b label5 2322 // label5: 2323 // b label7 2324 // label6: 2325 // nop 2326 // label7: 2327 // ret 2328 // 2329 // -- should become: 2330 // 2331 // label0: 2332 // cbz x0, label7 2333 // label2: 2334 // nop 2335 // nop 2336 // b label0 2337 // label6: 2338 // nop 2339 // label7: 2340 // ret 2341 2342 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2343 let mut buf = MachBuffer::new(); 2344 let mut state = <Inst as MachInstEmit>::State::default(); 2345 let constants = Default::default(); 2346 2347 buf.reserve_labels_for_blocks(8); 2348 2349 buf.bind_label(label(0), state.ctrl_plane_mut()); 2350 let inst = Inst::CondBr { 2351 kind: CondBrKind::Zero(xreg(0)), 2352 taken: target(1), 2353 not_taken: target(2), 2354 }; 2355 inst.emit(&mut buf, &info, &mut state); 2356 2357 buf.bind_label(label(1), state.ctrl_plane_mut()); 2358 let inst = Inst::Jump { dest: target(3) }; 2359 inst.emit(&mut buf, &info, &mut state); 2360 2361 buf.bind_label(label(2), state.ctrl_plane_mut()); 2362 let inst = Inst::Nop4; 2363 inst.emit(&mut buf, &info, &mut state); 2364 inst.emit(&mut buf, &info, &mut state); 2365 let inst = Inst::Jump { dest: target(0) }; 2366 inst.emit(&mut buf, &info, &mut state); 2367 2368 buf.bind_label(label(3), state.ctrl_plane_mut()); 2369 let inst = Inst::Jump { dest: target(4) }; 2370 inst.emit(&mut buf, &info, &mut state); 2371 2372 buf.bind_label(label(4), state.ctrl_plane_mut()); 2373 let inst = Inst::Jump { dest: target(5) }; 2374 inst.emit(&mut buf, &info, &mut state); 2375 2376 buf.bind_label(label(5), state.ctrl_plane_mut()); 2377 let inst = Inst::Jump { dest: target(7) }; 2378 inst.emit(&mut buf, &info, &mut state); 2379 2380 buf.bind_label(label(6), state.ctrl_plane_mut()); 2381 let inst = Inst::Nop4; 2382 inst.emit(&mut buf, &info, &mut state); 2383 2384 buf.bind_label(label(7), state.ctrl_plane_mut()); 2385 let inst = Inst::Ret {}; 2386 inst.emit(&mut buf, &info, &mut state); 2387 2388 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2389 2390 let golden_data = vec![ 2391 0xa0, 0x00, 0x00, 0xb4, // cbz x0, 0x14 2392 0x1f, 0x20, 0x03, 0xd5, // nop 2393 0x1f, 0x20, 0x03, 0xd5, // nop 2394 0xfd, 0xff, 0xff, 0x17, // b 0 2395 0x1f, 0x20, 0x03, 0xd5, // nop 2396 0xc0, 0x03, 0x5f, 0xd6, // ret 2397 ]; 2398 2399 assert_eq!(&golden_data[..], &buf.data[..]); 2400 } 2401 2402 #[test] 2403 fn test_handle_branch_cycle() { 2404 // label0: 2405 // b label1 2406 // label1: 2407 // b label2 2408 // label2: 2409 // b label3 2410 // label3: 2411 // b label4 2412 // label4: 2413 // b label1 // note: not label0 (to make it interesting). 2414 // 2415 // -- should become: 2416 // 2417 // label0, label1, ..., label4: 2418 // b label0 2419 let info = EmitInfo::new(settings::Flags::new(settings::builder())); 2420 let mut buf = MachBuffer::new(); 2421 let mut state = <Inst as MachInstEmit>::State::default(); 2422 let constants = Default::default(); 2423 2424 buf.reserve_labels_for_blocks(5); 2425 2426 buf.bind_label(label(0), state.ctrl_plane_mut()); 2427 let inst = Inst::Jump { dest: target(1) }; 2428 inst.emit(&mut buf, &info, &mut state); 2429 2430 buf.bind_label(label(1), state.ctrl_plane_mut()); 2431 let inst = Inst::Jump { dest: target(2) }; 2432 inst.emit(&mut buf, &info, &mut state); 2433 2434 buf.bind_label(label(2), state.ctrl_plane_mut()); 2435 let inst = Inst::Jump { dest: target(3) }; 2436 inst.emit(&mut buf, &info, &mut state); 2437 2438 buf.bind_label(label(3), state.ctrl_plane_mut()); 2439 let inst = Inst::Jump { dest: target(4) }; 2440 inst.emit(&mut buf, &info, &mut state); 2441 2442 buf.bind_label(label(4), state.ctrl_plane_mut()); 2443 let inst = Inst::Jump { dest: target(1) }; 2444 inst.emit(&mut buf, &info, &mut state); 2445 2446 let buf = buf.finish(&constants, state.ctrl_plane_mut()); 2447 2448 let golden_data = vec![ 2449 0x00, 0x00, 0x00, 0x14, // b 0 2450 ]; 2451 2452 assert_eq!(&golden_data[..], &buf.data[..]); 2453 } 2454 2455 #[test] 2456 fn metadata_records() { 2457 let mut buf = MachBuffer::<Inst>::new(); 2458 let ctrl_plane = &mut Default::default(); 2459 let constants = Default::default(); 2460 2461 buf.reserve_labels_for_blocks(1); 2462 2463 buf.bind_label(label(0), ctrl_plane); 2464 buf.put1(1); 2465 buf.add_trap(TrapCode::HeapOutOfBounds); 2466 buf.put1(2); 2467 buf.add_trap(TrapCode::IntegerOverflow); 2468 buf.add_trap(TrapCode::IntegerDivisionByZero); 2469 buf.add_call_site(Opcode::Call); 2470 buf.add_reloc( 2471 Reloc::Abs4, 2472 &ExternalName::User(UserExternalNameRef::new(0)), 2473 0, 2474 ); 2475 buf.put1(3); 2476 buf.add_reloc( 2477 Reloc::Abs8, 2478 &ExternalName::User(UserExternalNameRef::new(1)), 2479 1, 2480 ); 2481 buf.put1(4); 2482 2483 let buf = buf.finish(&constants, ctrl_plane); 2484 2485 assert_eq!(buf.data(), &[1, 2, 3, 4]); 2486 assert_eq!( 2487 buf.traps() 2488 .iter() 2489 .map(|trap| (trap.offset, trap.code)) 2490 .collect::<Vec<_>>(), 2491 vec![ 2492 (1, TrapCode::HeapOutOfBounds), 2493 (2, TrapCode::IntegerOverflow), 2494 (2, TrapCode::IntegerDivisionByZero) 2495 ] 2496 ); 2497 assert_eq!( 2498 buf.call_sites() 2499 .iter() 2500 .map(|call_site| (call_site.ret_addr, call_site.opcode)) 2501 .collect::<Vec<_>>(), 2502 vec![(2, Opcode::Call)] 2503 ); 2504 assert_eq!( 2505 buf.relocs() 2506 .iter() 2507 .map(|reloc| (reloc.offset, reloc.kind)) 2508 .collect::<Vec<_>>(), 2509 vec![(2, Reloc::Abs4), (3, Reloc::Abs8)] 2510 ); 2511 } 2512 } 2513