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