1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! SSA register allocation: virtual registers to physical registers and
//! stack slots.
//!
//! The input is a MIR function in SSA form (one definition per virtual
//! register, every use dominated by its definition) in which physical
//! registers appear only in short, block-local ranges: the copies into and
//! out of argument and result registers around calls and returns, the
//! operands of fixed-register instructions (`idiv`'s `rdx:rax`, a shift's
//! `cl`), and the entry block's incoming arguments. Instruction selection
//! ([`isel`](crate::isel)) produces exactly this. The output is the same
//! function on physical registers, ready for [`emit`](crate::emit).
//!
//! # Algorithm
//!
//! 1. **Liveness** by SSA path exploration: from each use outside its
//! definition's block, walk predecessors up to the definition, marking
//! the value live-in on the way. Cost is the size of the live sets, with
//! an explicit budget. It runs once: definitions and uses come from an
//! index built in one walk, and spill rounds update it (below).
//! 2. **Constraints** in one backward walk per block: which uses are last
//! uses, which physical registers are live after each instruction, and,
//! for each value, every register written while it is live (a call's
//! clobbers, a fixed-register definition), so the value never sits in one
//! of them.
//! 3. **Coloring in dominance order.** In strict SSA, two values that
//! interfere have one definition dominating the other, and the first is
//! live where the second is defined; so walking blocks in reverse
//! postorder and giving each value at its definition a register no live
//! value holds is a correct coloring, with no interference graph.
//! Block parameters get registers at their block's start; the parallel
//! copy on each edge is resolved at emission by the move resolver.
//! 4. **Coalescing.** Values joined by a copy, a two-address tie, or a
//! block parameter and its arguments form affinity classes (union-find);
//! a value takes its class's register, its tied operand's register, or the
//! physical register it is copied to or from, whenever that register is
//! free, so the copy, the tie, or the edge move disappears. It is best
//! effort: a value that interferes with its class takes another register
//! and keeps its move.
//! 5. **Spilling** when no register is free at a definition: the value with
//! the lowest weight (uses per instruction spanned) among the definition
//! and the values occupying a usable register is spilled for its whole
//! life (spill everywhere: no live-range splitting). A spilled constant
//! or address is **rematerialized** at each use instead of stored; any
//! other value is stored to a spill slot after its definition and
//! reloaded into a short-lived temporary before each use that cannot read
//! the slot directly (x86-64 reads one memory operand per instruction,
//! and branch arguments and copies read slots as they are). A spilled
//! block parameter simply lives in its slot. Coloring then reruns;
//! temporaries are never spilled, so each round spills at least one more
//! long-lived value, and after [`MAX_ROUNDS`] every remaining long-lived
//! value is spilled, which always succeeds.
//! 6. **Incremental updates between rounds.** Spill code changes liveness in
//! a way that can be stated exactly: every spilled value leaves every
//! live-in set (it is gone, or lives only from its definition to the
//! store after it); each reload temporary lives from just before its user
//! to the user; and spill code reads and writes no physical register. So
//! the live sets, last uses, and fixed-register facts are updated in time
//! proportional to the live sets and the spill code, the affinities only
//! at the instructions that now read a temporary, and only the blocks that
//! received spill code are rebuilt: a round costs one coloring walk, not a
//! liveness analysis.
//!
//! **Callee-saved registers** are used like any other; a value live across a
//! call can only sit in one (the call clobbers the rest), and the frame
//! saves exactly the callee-saved registers the function writes.
//!
//! **Stack maps** need nothing from the allocator: instruction selection
//! stores each GC reference of a safepoint into a dedicated root slot before
//! the call and reloads the relocated value after it, so no reference is in
//! a register while the collector runs, and the slots are recorded on the
//! call ([`Function::set_call_site`]).
use Vec;
use fmt;
use crateCfg;
use crate;
use crate;
/// After this many rounds that still spill, every long-lived value is
/// spilled at once, which always allocates.
pub const MAX_ROUNDS: u32 = 6;
/// The default budget on live-set entries (one per value live into a
/// block): 16 Mi entries, 64 MiB.
pub const DEFAULT_LIVE_BUDGET: usize = 1 << 24;
/// Why a function could not be allocated.
///
/// # Examples
///
/// ```
/// use backend_lang::mir::{Function, Operand};
/// use backend_lang::regalloc::{self, RegAllocError};
/// use backend_lang::x86_64::{op, GPR, SYSV};
///
/// let mut f = Function::new("f", &SYSV);
/// let b = f.block()?;
/// let v = f.vreg(GPR)?;
/// let w = f.vreg(GPR)?;
/// f.push(b, op::MOV64, &[w.into(), v.into()])?; // v is never defined
/// f.push(b, op::RET, &[])?;
/// assert!(matches!(regalloc::allocate(&mut f), Err(RegAllocError::Mir(_))));
/// # Ok::<(), backend_lang::mir::MirError>(())
/// ```
/// Where a virtual register lives for its whole life after allocation.
///
/// # Examples
///
/// ```
/// use backend_lang::regalloc::Location;
/// use backend_lang::x86_64::RAX;
///
/// assert_eq!(Location::Reg(RAX), Location::Reg(RAX));
/// ```
/// Allocation settings.
///
/// # Examples
///
/// ```
/// use backend_lang::regalloc::Options;
///
/// let o = Options::new().with_live_budget(1 << 20).keep_assignment(true);
/// assert_eq!(o.live_budget, 1 << 20);
/// ```
/// What the allocator did.
///
/// # Examples
///
/// ```
/// use backend_lang::mir::{Effects, Function, Operand};
/// use backend_lang::regalloc;
/// use backend_lang::x86_64::{op, GPR, SYSV, RAX};
///
/// let mut f = Function::new("f", &SYSV);
/// let b = f.block()?;
/// let v = f.vreg(GPR)?;
/// f.push(b, op::MOV64RI, &[v.into(), Operand::Imm(7)])?;
/// f.push(b, op::COPY, &[RAX.into(), v.into()])?;
/// f.push_with(b, op::RET, &[], Effects::new().uses(&[RAX]))?;
/// let a = regalloc::allocate(&mut f)?;
/// assert_eq!(a.spilled(), 0);
/// // The value was given rax, the register it is copied to: no move left.
/// assert_eq!(backend_lang::emit(&f)?, [0x55, 0x48, 0x89, 0xE5, 0xB8, 7, 0, 0, 0, 0x5D, 0xC3]);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Allocates registers for `f` in place with the default [`Options`].
///
/// # Errors
///
/// A [`RegAllocError`]; `f` is unspecified after an error.
///
/// # Examples
///
/// ```
/// use backend_lang::mir::{Effects, Function, Operand};
/// use backend_lang::regalloc;
/// use backend_lang::x86_64::{op, GPR, SYSV, RAX, RDI, RSI};
///
/// // fn add(a, b) -> a + b, on virtual registers.
/// let mut f = Function::new("add", &SYSV);
/// f.omit_frame_pointer();
/// let b = f.block()?;
/// f.add_param(b, RDI.into())?;
/// f.add_param(b, RSI.into())?;
/// let (x, y, s) = (f.vreg(GPR)?, f.vreg(GPR)?, f.vreg(GPR)?);
/// f.push(b, op::PCOPY, &[x.into(), y.into(), RDI.into(), RSI.into()])?;
/// f.push(b, op::ADD64, &[s.into(), x.into(), y.into()])?;
/// f.push(b, op::COPY, &[RAX.into(), s.into()])?;
/// f.push_with(b, op::RET, &[], Effects::new().uses(&[RAX]))?;
/// regalloc::allocate(&mut f)?;
/// let code = backend_lang::emit(&f)?;
/// assert_eq!(code.last(), Some(&0xC3));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Allocates registers for `f` in place.
///
/// # Errors
///
/// A [`RegAllocError`]; `f` is unspecified after an error.
///
/// # Examples
///
/// ```
/// use backend_lang::mir::{Function, Operand};
/// use backend_lang::regalloc::{self, Options, RegAllocError};
/// use backend_lang::x86_64::{op, GPR, SYSV};
///
/// let mut f = Function::new("f", &SYSV);
/// let (a, b) = (f.block()?, f.block()?);
/// let v = f.vreg(GPR)?;
/// f.push(a, op::MOV64RI, &[v.into(), Operand::Imm(1)])?;
/// let to_b = f.block_call(b, &[])?;
/// f.push(a, op::JMP, &[to_b.into()])?;
/// f.push(b, op::CMP64, &[v.into(), Operand::Imm(0)])?;
/// f.push(b, op::RET, &[])?;
/// // v is live into b: one live-set entry, over a budget of zero.
/// let err = regalloc::allocate_with(&mut f, &Options::new().with_live_budget(0));
/// assert_eq!(err.unwrap_err(), RegAllocError::TooLarge);
/// # Ok::<(), backend_lang::mir::MirError>(())
/// ```
/// A virtual register's class, for a register known to the function.