lib/std/lang/lower.rad 277.2 KiB raw
1
//! AST to IL lowering pass.
2
//!
3
//! This module converts the typed AST produced by the resolver into a linear
4
//! SSA-based intermediate language (IL). The IL is suitable for further
5
//! optimization and code generation.
6
//!
7
//! # Design Overview
8
//!
9
//! The lowering process works in two main phases:
10
//!
11
//! 1. Module-level pass: Iterates over top-level declarations, lowering
12
//!    each function independently while accumulating global data items (strings,
13
//!    constants, static arrays) into a shared data section.
14
//!
15
//! 2. Function-level pass: For each function, constructs an SSA-form control
16
//!    flow graph (CFG) with basic blocks connected by jumps and branches. Uses
17
//!    a simplified SSA construction algorithm where variables are tracked per-block
18
//!    and block parameters are inserted lazily when a variable is used before
19
//!    being defined in a block.
20
//!
21
//! # Memory Model
22
//!
23
//! All allocations use an arena allocator passed through the `Lowerer` context.
24
//! The IL is entirely stack-based at runtime -- there's no heap allocation during
25
//! program execution. Aggregate values (records, slices, optionals) are passed
26
//! by pointer on the stack.
27
//!
28
//! # SSA Construction
29
//!
30
//! SSA form is built incrementally as the AST is walked. When a variable is
31
//! defined (via `defVar`), its current value is recorded in the current block.
32
//! When a variable is used (via `useVar`), the algorithm either:
33
//! - Returns the value if defined in this block
34
//! - Recurses to predecessors if the block is sealed (all predecessors known)
35
//! - Inserts a block parameter if the variable value must come from multiple paths
36
//!
37
//! Block "sealing" indicates that all predecessor edges are known, enabling
38
//! the SSA construction to resolve cross-block variable references.
39
//!
40
//! # SSA Variable API
41
//!
42
//! 1. `newVar` creates a logical variable that can be defined differently in each block.
43
//! 2. `defVar` defines the variable's value in the current block.
44
//! 3. `useVar` reads the variable; if called in a block with multiple
45
//!             predecessors that defined it differently, the SSA algorithm
46
//!             automatically creates a block parameter.
47
//!
48
//! # Expression Lowering
49
//!
50
//! Expressions produce IL values which can be:
51
//!
52
//! - Imm(i64): immediate/constant values
53
//! - Reg(u32): SSA register references
54
//! - Sym(name): symbol references (for function pointers, data addresses)
55
//! - Undef: for unused values
56
//!
57
//! For aggregate types (records, arrays, slices, optionals), the "value" is
58
//! actually a pointer to stack-allocated memory containing the aggregate.
59
//!
60
//! # Block ordering invariant
61
//!
62
//! The register allocator processes blocks in forward index order and uses a
63
//! single global assignment array. This means a value's definition block must
64
//! have a lower index than any block that uses the value (except through
65
//! back-edges, where block parameters handle the merge). The lowerer maintains
66
//! this by creating blocks in control-flow order. For `for` loops, the step
67
//! block is created lazily (after the loop body) so that its index is higher
68
//! than all body blocks -- see [`lowerForLoop`] and [`getOrCreateContinueBlock`].
69
//!
70
//! A more robust alternative would be per-block register maps with edge-copy
71
//! resolution (as in QBE's `rega.c`), which is block-order-independent. That
72
//! would eliminate this invariant at the cost of a more complex allocator.
73
//!
74
//! # Notes on constant data lowering
75
//!
76
//! The lowerer flattens constant AST expressions directly into IL data values.
77
//! Primitive constants use [`resolver::ConstValue`] as an intermediate form.
78
//! Record padding is explicit: `undef * N;` for N padding bytes.
79
//!
80
//!   AST Node (ArrayLit, RecordLit, literals, etc.)
81
//!       ↓ [`lowerConstData`]
82
//!   resolver::ConstValue (Bool, Char, String, Int)
83
//!       ↓ [`constValueToDataItem`]
84
//!   il::DataItem (Val, Sym, Str, Undef)
85
//!       ↓
86
//!   il::DataValue
87
//!       ↓
88
//!   il::Data
89
//!
90
use std::fmt;
91
use std::io;
92
use std::lang::alloc;
93
use std::lang::types;
94
use std::mem;
95
use std::lang::ast;
96
use std::lang::il;
97
use std::lang::module;
98
use std::lang::resolver;
99
100
// TODO: Search for all `_ as i32` to ensure that casts from u32 to i32 don't
101
// happen, since they are potentially truncating values.
102
103
// TODO: Support constant union lowering.
104
// TODO: Void unions should be passed by value.
105
106
////////////////////
107
// Error Handling //
108
////////////////////
109
110
/// Lowering errors are typically unrecoverable since they indicate bugs in
111
/// the resolver or malformed AST that should have been caught earlier.
112
export union LowerError: Copy {
113
    /// A node's symbol was not set before lowering.
114
    MissingSymbol(*ast::Node),
115
    /// A node's type was not set before lowering.
116
    MissingType(*ast::Node),
117
    /// A node's constant value was not set before lowering.
118
    MissingConst(*ast::Node),
119
    /// An optional type was expected.
120
    ExpectedOptional,
121
    /// A record type was expected.
122
    ExpectedRecord,
123
    /// An array was expected.
124
    ExpectedArray,
125
    /// A block was expected.
126
    ExpectedBlock(*ast::Node),
127
    /// An identifier was expected.
128
    ExpectedIdentifier,
129
    /// A function parameter was expected.
130
    ExpectedFunctionParam,
131
    /// A function type was expected.
132
    ExpectedFunction,
133
    /// Trying to lower loop construct outside of loop.
134
    OutsideOfLoop,
135
    /// Invalid variable use.
136
    InvalidUse,
137
    /// Unexpected node value.
138
    UnexpectedNodeValue(*ast::Node),
139
    /// Unexpected type.
140
    UnexpectedType(resolver::Type),
141
142
    /// Missing control flow target.
143
    MissingTarget,
144
    /// Missing metadata that should have been set by resolver.
145
    MissingMetadata,
146
    /// Expected a slice or array type for operation.
147
    ExpectedSliceOrArray,
148
    /// Expected a variant symbol.
149
    ExpectedVariant,
150
    /// Expected a call expression.
151
    ExpectedCall,
152
    /// Field not found in record or invalid field access.
153
    FieldNotFound,
154
    /// Assignment to an immutable variable.
155
    ImmutableAssignment,
156
    /// Nil used in non-optional context.
157
    NilInNonOptional,
158
    /// Invalid argument count for builtin.
159
    InvalidArgCount,
160
    /// Feature or pattern not supported by the lowerer.
161
    Unsupported,
162
    /// Unknown intrinsic function.
163
    UnknownIntrinsic,
164
    /// Allocation failure.
165
    AllocationFailed,
166
}
167
168
/// Print a LowerError for debugging.
169
export fn printError(err: LowerError) {
170
    match err {
171
        case LowerError::MissingSymbol(_) => io::print("MissingSymbol"),
172
        case LowerError::MissingType(_) => io::print("MissingType"),
173
        case LowerError::MissingConst(_) => io::print("MissingConst"),
174
        case LowerError::ExpectedOptional => io::print("ExpectedOptional"),
175
        case LowerError::ExpectedRecord => io::print("ExpectedRecord"),
176
        case LowerError::ExpectedArray => io::print("ExpectedArray"),
177
        case LowerError::ExpectedBlock(_) => io::print("ExpectedBlock"),
178
        case LowerError::ExpectedIdentifier => io::print("ExpectedIdentifier"),
179
        case LowerError::ExpectedFunctionParam => io::print("ExpectedFunctionParam"),
180
        case LowerError::ExpectedFunction => io::print("ExpectedFunction"),
181
        case LowerError::OutsideOfLoop => io::print("OutsideOfLoop"),
182
        case LowerError::InvalidUse => io::print("InvalidUse"),
183
        case LowerError::UnexpectedNodeValue(_) => io::print("UnexpectedNodeValue"),
184
        case LowerError::UnexpectedType(_) => io::print("UnexpectedType"),
185
        case LowerError::MissingTarget => io::print("MissingTarget"),
186
        case LowerError::MissingMetadata => io::print("MissingMetadata"),
187
        case LowerError::ExpectedSliceOrArray => io::print("ExpectedSliceOrArray"),
188
        case LowerError::ExpectedVariant => io::print("ExpectedVariant"),
189
        case LowerError::ExpectedCall => io::print("ExpectedCall"),
190
        case LowerError::FieldNotFound => io::print("FieldNotFound"),
191
        case LowerError::ImmutableAssignment => io::print("ImmutableAssignment"),
192
        case LowerError::NilInNonOptional => io::print("NilInNonOptional"),
193
        case LowerError::InvalidArgCount => io::print("InvalidArgCount"),
194
        case LowerError::Unsupported => io::print("Unsupported"),
195
        case LowerError::UnknownIntrinsic => io::print("UnknownIntrinsic"),
196
        case LowerError::AllocationFailed => io::print("AllocationFailed"),
197
    }
198
}
199
200
///////////////
201
// Constants //
202
///////////////
203
204
/// Maximum nesting depth of loops.
205
constant MAX_LOOP_DEPTH: u32 = 16;
206
/// Maximum number of `catch` clauses per `try`.
207
constant MAX_CATCH_CLAUSES: u32 = 32;
208
209
// Slice Layout
210
//
211
// A slice is a fat pointer consisting of a data pointer, a length and a capacity.
212
// `{ ptr: u32, len: u32, cap: u32 }`.
213
214
/// Slice data pointer offset.
215
constant SLICE_PTR_OFFSET: i32 = 0;
216
/// Offset of slice length in slice data structure.
217
constant SLICE_LEN_OFFSET: i32 = resolver::PTR_SIZE as i32;
218
/// Offset of slice capacity in slice data structure.
219
constant SLICE_CAP_OFFSET: i32 = resolver::PTR_SIZE as i32 + 4;
220
221
// Trait Object Layout
222
//
223
// A trait object is a fat pointer consisting of a data pointer and a
224
// v-table pointer. `{ data: *T, vtable: *VTable }`.
225
226
/// Trait object data pointer offset.
227
constant TRAIT_OBJ_DATA_OFFSET: i32 = 0;
228
/// Trait object v-table pointer offset.
229
constant TRAIT_OBJ_VTABLE_OFFSET: i32 = resolver::PTR_SIZE as i32;
230
231
// Tagged Value Layout (optionals, tagged unions)
232
//
233
// Optionals and unions use 1-byte tags. Results use 8-byte tags.
234
//
235
// `{ tag: u8, [padding], payload: T }`
236
//
237
// Optionals use `tag: 0` for `nil` and `tag: 1` otherwise.
238
// When `T` is a pointer, the entire optional is stored as a single pointer.
239
//
240
// Tagged unions have a payload the size of the maximum variant size.
241
242
/// Offset of tag in tagged value data structure.
243
constant TVAL_TAG_OFFSET: i32 = 0;
244
/// Offset of value in result data structure (8-byte tag).
245
constant RESULT_VAL_OFFSET: i32 = resolver::PTR_SIZE as i32;
246
247
//////////////////////////
248
// Core Data Structures //
249
//////////////////////////
250
251
/// Options controlling the lowering pass.
252
export record LowerOptions: Copy {
253
    /// Whether to emit source location info.
254
    debug: bool,
255
    /// Whether to lower `@test` functions.
256
    buildTest: bool,
257
}
258
259
/// Role of a lowered function in the final program.
260
export union FnRole: Copy {
261
    /// Regular function.
262
    Normal,
263
    /// Program entry function marked with `@default`.
264
    Default,
265
}
266
267
/// Function sink used by lowerers that consume functions as they are produced.
268
export record FnSink: Copy {
269
    /// Opaque context. It must remain valid for every sink callback.
270
    ctx: *unsafe mut opaque,
271
    /// Callback invoked for each lowered function.
272
    emitFn: unsafe fn(*unsafe mut opaque, *unsafe il::Fn, FnRole),
273
}
274
275
/// Destination for functions produced by the lowerer.
276
export union FnOutput: Copy {
277
    /// Store lowered functions in the provided slice.
278
    Accumulate(*unsafe mut [*unsafe il::Fn]),
279
    /// Send lowered functions to an external consumer immediately.
280
    Stream(FnSink),
281
}
282
283
/// Module-level lowering context. Shared across all function lowerings.
284
/// Holds global state like the data section (strings, constants) and provides
285
/// access to the resolver for type queries.
286
export record Lowerer {
287
    /// Arena for persistent lowering state, including data and symbol names.
288
    arena: *unsafe mut alloc::Arena,
289
    /// Arena for allocations owned by the function currently being lowered.
290
    fnArena: *unsafe mut alloc::Arena,
291
    /// Allocator backed by the arena.
292
    allocator: alloc::Allocator,
293
    /// Resolver for type information. Used to query types, symbols, and
294
    /// compile-time constant values during lowering.
295
    resolver: *unsafe resolver::Resolver,
296
    /// Module graph for cross-module symbol resolution.
297
    moduleGraph: ?*unsafe module::ModuleGraph,
298
    /// Package name for qualified symbol names.
299
    pkgName: *[u8],
300
    /// Current module being lowered.
301
    currentMod: ?u16,
302
    /// Global data items (string literals, constants, static arrays).
303
    /// These become the data sections in the final binary.
304
    data: *mut [il::Data],
305
    /// Destination for lowered functions.
306
    output: FnOutput,
307
    /// Map of function symbols to qualified names.
308
    fnSyms: *mut [FnSymEntry],
309
    /// Global error type tag table. Maps nominal types to unique tags.
310
    errTags: *mut [ErrTagEntry],
311
    /// Next error tag to assign (starts at 1; 0 = success).
312
    errTagCounter: u32,
313
    /// Lowering options.
314
    options: LowerOptions,
315
}
316
317
/// Entry mapping a function symbol to its qualified name.
318
record FnSymEntry: Copy {
319
    sym: *unsafe resolver::Symbol,
320
    qualName: *[u8],
321
}
322
323
/// Entry in the global error tag table.
324
record ErrTagEntry: Copy {
325
    /// The type of this error, identified by its interned pointer.
326
    ty: resolver::Type,
327
    /// The globally unique tag assigned to this error type (non-zero).
328
    tag: u32,
329
}
330
331
/// Compute the maximum size of any error type in a throw list.
332
unsafe fn maxErrSize(throwList: *[*resolver::Type]) -> u32 {
333
    let mut maxSize: u32 = 0;
334
    for ty in throwList {
335
        let size = resolver::getTypeLayout(*ty).size;
336
        if size > maxSize {
337
            set maxSize = size;
338
        }
339
    }
340
    return maxSize;
341
}
342
343
/// Get or assign a globally unique error tag for the given error type.
344
/// Tag `0` is reserved for success; error tags start at `1`.
345
fn getOrAssignErrorTag(self: &mut Lowerer, errType: resolver::Type) -> u32 {
346
    for entry in &self.errTags[..] {
347
        if entry.ty == errType {
348
            return entry.tag;
349
        }
350
    }
351
    let tag = self.errTagCounter;
352
353
    set self.errTagCounter += 1;
354
    self.errTags.append(ErrTagEntry { ty: errType, tag }, self.allocator);
355
356
    return tag;
357
}
358
359
/// Emit one function to the active output.
360
unsafe fn emitFunction(self: &mut Lowerer, func: *unsafe il::Fn, role: FnRole) {
361
    match self.output {
362
        case FnOutput::Accumulate(accumulated) => {
363
            let mut fns = accumulated;
364
            fns.append(func, self.allocator);
365
            set self.output = FnOutput::Accumulate(fns);
366
        }
367
        case FnOutput::Stream(sink) => {
368
            sink.emitFn(sink.ctx, func, role);
369
        }
370
    }
371
}
372
373
/// Get the function role for a top-level function declaration.
374
fn lowerFnRole(isRoot: bool, attrs: ?ast::Attributes) -> FnRole {
375
    if isRoot and checkAttr(attrs, ast::Attribute::Default) {
376
        return FnRole::Default;
377
    }
378
    return FnRole::Normal;
379
}
380
381
/// Builder for accumulating data values during constant lowering.
382
record DataValueBuilder {
383
    /// Allocator used to grow the value storage.
384
    allocator: alloc::Allocator,
385
    /// Owned values under construction.
386
    values: *mut [il::DataValue],
387
    /// Whether all pushed values can be represented by zero-filled memory.
388
    zeroInit: bool,
389
}
390
391
/// Result of lowering constant data.
392
record ConstDataResult: Copy {
393
    /// Immutable initializer values.
394
    values: *[il::DataValue],
395
    /// Whether the values can be represented by zero-filled memory.
396
    zeroInit: bool,
397
}
398
399
/// Create a new builder.
400
fn dataBuilder(allocator: alloc::Allocator) -> DataValueBuilder {
401
    return DataValueBuilder { allocator, values: &mut [], zeroInit: true };
402
}
403
404
/// Return whether a data item can be omitted from a zero-filled image.
405
fn dataIsZero(item: il::DataItem) -> bool {
406
    match item {
407
        case il::DataItem::Undef => return true,
408
        case il::DataItem::Val { val, .. } => return val == 0,
409
        else => return false,
410
    }
411
}
412
413
/// Return whether all data values can be omitted from a zero-filled image.
414
fn dataValuesAreZeroInit(values: *[il::DataValue]) -> bool {
415
    for value in values {
416
        if value.count > 0 and not dataIsZero(value.item) {
417
            return false;
418
        }
419
    }
420
    return true;
421
}
422
423
/// Append a data value to the builder.
424
fn dataBuilderPush(b: &mut DataValueBuilder, value: il::DataValue) {
425
    b.values.append(value, b.allocator);
426
427
    if value.count > 0 and not dataIsZero(value.item) {
428
        set b.zeroInit = false;
429
    }
430
}
431
432
/// Return the accumulated values.
433
fn dataBuilderFinish(b: DataValueBuilder) -> ConstDataResult {
434
    let case DataValueBuilder { values, zeroInit, .. } = b
435
        else panic "expected data builder";
436
    return ConstDataResult { values, zeroInit };
437
}
438
439
///////////////////////////
440
// SSA Variable Tracking //
441
///////////////////////////
442
443
// The SSA construction algorithm tracks variable definitions per-block.
444
// Each source-level variable gets a [`Var`] handle, and each block maintains
445
// a mapping from [`Var`] to current SSA value. When control flow merges,
446
// block parameters are inserted to merge values from different control flow paths.
447
448
/// A variable handle. Represents a source-level variable during lowering.
449
/// The same [`Var`] can have different SSA values in different blocks.
450
export record Var: Copy(u32);
451
452
/// Metadata for a source-level variable, stored once per function.
453
///
454
/// Each variable declaration in the source creates one [`VarData`] entry in the
455
/// function's `variables` array, indexed by `id`. This contains static
456
/// properties that don't change across basic blocks.
457
///
458
/// Per-block SSA values are tracked separately in [`BlockData::vars`] as [`?il::Val`],
459
/// where `nil` means "not yet assigned in this block". Together they implement
460
/// SSA construction.
461
///
462
record VarData: Copy {
463
    /// Variable name, used by [`lookupVarByName`] to resolve identifiers.
464
    /// Nil for anonymous variables (e.g., internal loop counters).
465
    name: ?*[u8],
466
    /// IL type of this variable. Set at declaration time and used when
467
    /// generating loads, stores, and type-checking assignments.
468
    type: il::Type,
469
    /// Whether this variable was declared with `mut`. Controls whether [`defVar`]
470
    /// is allowed after the initial definition.
471
    mutable: bool,
472
    /// Whether this variable's address has been taken (e.g. via `&mut x`).
473
    /// When true, the SSA value is a pointer to a stack slot and reads/writes
474
    /// must go through memory instead of using the cached SSA value directly.
475
    addressTaken: bool,
476
}
477
478
/// Links a function parameter to its corresponding variable for the entry block.
479
/// After creating the entry block, we iterate through these to define initial values.
480
record FnParamBinding: Copy {
481
    /// The variable that receives this parameter's value.
482
    var: Var,
483
    /// SSA register containing the parameter value from the caller.
484
    reg: il::Reg,
485
}
486
487
////////////////////////////////
488
// Basic Block Representation //
489
////////////////////////////////
490
491
// During lowering, we build a CFG of basic blocks. Each block accumulates
492
// instructions until terminated by a jump, branch, return, or unreachable.
493
// Blocks can be created before they're filled (forward references for jumps).
494
495
/// A handle to a basic block within the current function.
496
/// Block handles are stable, they don't change as more blocks are added.
497
export record BlockId: Copy(u32);
498
499
/// Internal block state during construction.
500
///
501
/// The key invariants:
502
///
503
/// - A block is "open" if it has no terminator; instructions can be added.
504
/// - A block is "sealed" when all predecessor edges are known.
505
/// - Sealing resolves the predecessor arguments for block parameters.
506
///
507
/// This differs from the final [`il::Block`] which is immutable and fully formed.
508
record BlockData: Copy {
509
    /// Block label for debugging and IL printing.
510
    label: *[u8],
511
    /// Block parameters for merging values at control flow joins. These
512
    /// receive values from predecessor edges when control flow merges.
513
    params: *unsafe mut [il::Param],
514
    /// Variable ids in parameter order. Before sealing, these are the variables
515
    /// whose predecessor arguments must be resolved.
516
    paramVars: *unsafe mut [u32],
517
    /// Instructions accumulated so far. The last instruction should eventually
518
    /// be a terminator.
519
    instrs: *unsafe mut [il::Instr],
520
    /// Debug source locations, one per instruction. Only populated when
521
    /// debug info is enabled.
522
    locs: *unsafe mut [il::SrcLoc],
523
    /// Predecessor block ids. Used for SSA construction to propagate values
524
    /// from predecessors when a variable is used before being defined locally.
525
    preds: *unsafe mut [u32],
526
    /// The current SSA value of each variable in this block. Indexed by variable
527
    /// id. A `nil` means the variable wasn't assigned in this block. Updated by
528
    /// [`defVar`], queried by [`useVarInBlock`].
529
    vars: *unsafe mut [?il::Val],
530
    /// Sealing state. Once sealed, all predecessors are known and we can resolve
531
    /// variable uses that need to pull values from predecessors.
532
    sealState: Sealed,
533
    /// Loop nesting depth when this block was created.
534
    loopDepth: u32,
535
}
536
537
/// Block sealing state for SSA construction.
538
///
539
/// A block is "unsealed" while its predecessors are still being discovered.
540
/// Before sealing, `BlockData.paramVars` records each variable that needs a
541
/// block parameter. Once all predecessors are known, the block is sealed and
542
/// those parameters are resolved via [`resolveBlockArgs`].
543
union Sealed: Copy {
544
    /// Block is unsealed; predecessors may still be added.
545
    No,
546
    /// Block is sealed; all predecessors are known.
547
    Yes,
548
}
549
550
///////////////////////////////////
551
// Loop and Control Flow Context //
552
///////////////////////////////////
553
554
/// Context for break/continue statements within a loop.
555
/// Each nested loop pushes a new context onto the loop stack.
556
export record LoopCtx: Copy {
557
    /// Where `break` should transfer control (the loop's exit block).
558
    breakTarget: BlockId,
559
    /// Where `continue` should transfer control.
560
    continueTarget: ?BlockId,
561
}
562
563
/// Logical operator.
564
union LogicalOp: Copy { And, Or }
565
566
/// Iterator state for for-loop lowering.
567
union ForIter: Copy {
568
    /// Range iterator: `for i in 0..n`.
569
    Range {
570
        valVar: Var,
571
        indexVar: ?Var,
572
        endVal: il::Val,
573
        valType: il::Type,
574
        unsigned: bool,
575
    },
576
    /// Collection iterator: `for elem in slice`.
577
    Collection {
578
        valVar: ?Var,
579
        idxVar: Var,
580
        dataReg: il::Reg,
581
        lengthVal: il::Val,
582
        elemType: *resolver::Type,
583
    },
584
}
585
586
//////////////////////////////
587
// Pattern Matching Support //
588
//////////////////////////////
589
590
// Match expressions are lowered by evaluating the subject once, then emitting
591
// a chain of comparison-and-branch sequences for each arm. The algorithm
592
// handles several subject types specially:
593
//
594
// - Optional pointers: compared against `null`.
595
// - Optional aggregates: tag checked then payload extracted.
596
// - Unions: tag compared against variant indices.
597
598
/// Cached information about a match subject. Computed once and reused across
599
/// all arms to avoid redundant lowering and type queries.
600
record MatchSubject: Copy {
601
    /// The lowered subject value.
602
    val: il::Val,
603
    /// Source-level type from the resolver.
604
    type: resolver::Type,
605
    /// IL-level type for code generation.
606
    ilType: il::Type,
607
    /// The type that binding arms should use. For optionals, this is the
608
    /// inner type; for regular values, it's the same as `type`.
609
    bindType: resolver::Type,
610
    /// Classification of how the subject should be compared and destructured.
611
    kind: MatchSubjectKind,
612
    /// How bindings are created: by value, or by reference.
613
    by: resolver::MatchBy,
614
}
615
616
/// Classifies a match subject by how it should be compared and destructured.
617
union MatchSubjectKind: Copy {
618
    /// Regular value: direct equality comparison.
619
    Regular,
620
    /// Optional with null pointer optimization: `?*T`, `?*[T]`.
621
    OptionalPtr,
622
    /// Optional aggregate `?T`: tagged union with payload.
623
    OptionalAggregate,
624
    /// Union type: tag compared against variant indices.
625
    Union(resolver::UnionType),
626
}
627
628
/// Determine the kind of a match subject from its type.
629
unsafe fn matchSubjectKind(type: resolver::Type) -> MatchSubjectKind {
630
    if resolver::isOptionalPointer(type) {
631
        return MatchSubjectKind::OptionalPtr;
632
    }
633
    if resolver::isOptionalAggregate(type) {
634
        return MatchSubjectKind::OptionalAggregate;
635
    }
636
    if let info = unionInfoFromType(type) {
637
        return MatchSubjectKind::Union(info);
638
    }
639
    return MatchSubjectKind::Regular;
640
}
641
642
//////////////////////////
643
// Field Access Support //
644
//////////////////////////
645
646
/// Result of resolving a place expression to a memory location.
647
record FieldRef: Copy {
648
    /// Base pointer register (points to the container).
649
    base: il::Reg,
650
    /// Byte offset of the value within the container.
651
    offset: i32,
652
    /// Type of the value held at that location.
653
    fieldType: resolver::Type,
654
}
655
656
/// Result of computing an element pointer for array/slice subscript operations.
657
/// Used by [`lowerElemPtr`] to return both the element address register and
658
/// the element type for subsequent load or address-of operations.
659
record ElemPtrResult: Copy {
660
    /// Register holding the computed element address.
661
    elemReg: il::Reg,
662
    /// Source-level type of the element.
663
    elemType: resolver::Type,
664
}
665
666
/// Result of resolving a slice range to a data pointer and element count.
667
record SliceRangeResult: Copy {
668
    dataReg: il::Reg,
669
    count: il::Val,
670
}
671
672
/////////////////////////////
673
// Function Lowering State //
674
/////////////////////////////
675
676
/// Per-function lowering state. Created fresh for each function and contains
677
/// all the mutable state needed during function body lowering.
678
record FnLowerer: Copy {
679
    /// Reference to the module-level lowerer.
680
    low: *unsafe mut Lowerer,
681
    /// Allocator for IL allocations.
682
    allocator: alloc::Allocator,
683
    /// Type signature of the function being lowered.
684
    fnType: *resolver::FnType,
685
    /// Number of SSA variable slots required for each block.
686
    localCount: u32,
687
    /// Function name, used as prefix for generated data symbols.
688
    fnName: *[u8],
689
690
    // ~ SSA variable tracking ~ //
691
692
    /// Metadata (name, type, mutability) for each variable. Indexed by variable
693
    /// id. Doesn't change after declaration. For the SSA value of a variable in
694
    /// a specific block, see [`BlockData::vars`].
695
    vars: *unsafe mut [VarData],
696
    /// Parameter-to-variable bindings, initialized in the entry block.
697
    params: *unsafe mut [FnParamBinding],
698
699
    // ~ Basic block management ~ //
700
701
    /// Block storage array, indexed by block id.
702
    blockData: *unsafe mut [BlockData],
703
    /// The entry block for this function.
704
    entryBlock: ?BlockId,
705
    /// The block currently receiving new instructions.
706
    currentBlock: ?BlockId,
707
708
    // ~ Loop management ~ //
709
710
    /// Stack of loop contexts for break/continue resolution.
711
    loopStack: *unsafe mut [LoopCtx],
712
    /// Current nesting depth (index into loopStack).
713
    loopDepth: u32,
714
715
    // ~ Counters ~ //
716
717
    /// Counter for generating unique block labels like `then#0`, `loop#1`, etc.
718
    labelCounter: u32,
719
    /// Counter for generating unique data names within this function.
720
    /// Each literal gets a name like `fnName$literal$N`.
721
    dataCounter: u32,
722
    /// Counter for generating SSA register numbers.
723
    regCounter: u32,
724
    /// When the function returns an aggregate type, the caller passes a hidden
725
    /// pointer as the first parameter. The callee writes the return value into
726
    /// this buffer and returns the pointer.
727
    returnReg: ?il::Reg,
728
    /// Whether the function is a leaf.
729
    isLeaf: bool,
730
731
    // ~ Debug info ~ //
732
733
    /// Current debug source location, set when processing AST nodes.
734
    srcLoc: il::SrcLoc,
735
}
736
737
/////////////////////////////////
738
// Module Lowering Entry Point //
739
/////////////////////////////////
740
741
/// Lower a complete module AST to an IL program.
742
///
743
/// This is the main entry point for the lowering pass. It:
744
/// 1. Counts functions to preallocate the output array.
745
/// 2. Iterates over top-level declarations, lowering each.
746
/// 3. Returns the complete IL program with functions and data section.
747
///
748
/// The resolver must have already processed the AST -- we rely on its type
749
/// annotations, symbol table, and constant evaluations.
750
export unsafe fn lower(
751
    res: &resolver::Resolver,
752
    root: *ast::Node,
753
    pkgName: *[u8],
754
    arena: &mut alloc::Arena
755
) -> il::Program throws (LowerError) {
756
    let mut low = Lowerer {
757
        arena: (&mut *arena) as *unsafe mut alloc::Arena,
758
        fnArena: (&mut *arena) as *unsafe mut alloc::Arena,
759
        allocator: alloc::arenaAllocator(arena),
760
        resolver: res as *unsafe resolver::Resolver,
761
        moduleGraph: nil,
762
        pkgName,
763
        currentMod: nil,
764
        data: &mut [],
765
        output: FnOutput::Accumulate(&mut []),
766
        fnSyms: &mut [],
767
        errTags: &mut [],
768
        errTagCounter: 1,
769
        options: LowerOptions { debug: false, buildTest: false },
770
    };
771
    try lowerDecls(&mut low, root, true);
772
773
    return finalize(low);
774
}
775
776
/////////////////////////////////
777
// Multi-Module Lowering API   //
778
/////////////////////////////////
779
780
/// Create a lowerer for multi-module compilation.
781
/// The resolver, graph, and both arenas must outlive the returned lowerer.
782
export unsafe fn lowerer(
783
    res: *unsafe resolver::Resolver,
784
    graph: &module::ModuleGraph,
785
    pkgName: *[u8],
786
    arena: *unsafe mut alloc::Arena,
787
    fnArena: *unsafe mut alloc::Arena,
788
    options: LowerOptions
789
) -> Lowerer {
790
    return Lowerer {
791
        arena,
792
        fnArena,
793
        allocator: alloc::arenaAllocator(arena),
794
        resolver: res,
795
        moduleGraph: graph as *unsafe module::ModuleGraph,
796
        pkgName,
797
        currentMod: nil,
798
        data: &mut [],
799
        output: FnOutput::Accumulate(&mut []),
800
        fnSyms: &mut [],
801
        errTags: &mut [],
802
        errTagCounter: 1,
803
        options,
804
    };
805
}
806
807
/// Lower a module's AST into the lowerer.
808
/// Call this for each module in the package, then use `finalize` to get the program.
809
export unsafe fn lowerModule(
810
    low: &mut Lowerer,
811
    moduleId: u16,
812
    root: *ast::Node,
813
    isRoot: bool
814
) throws (LowerError) {
815
    set low.currentMod = moduleId;
816
    try lowerDecls(low, root, isRoot);
817
}
818
819
/// Lower all top-level declarations in a block.
820
unsafe fn lowerDecls(low: &mut Lowerer, root: *ast::Node, isRoot: bool) throws (LowerError) {
821
    let case ast::NodeValue::Block(block) = root.value else {
822
        throw LowerError::ExpectedBlock(root);
823
    };
824
    let stmtsList = block.statements;
825
826
    for node in stmtsList {
827
        match node.value {
828
            case ast::NodeValue::FnDecl(decl) => {
829
                if let f = try lowerFnDecl(low, node, decl) {
830
                    let role = lowerFnRole(isRoot, decl.attrs);
831
                    emitFunction(low, f, role);
832
                }
833
            }
834
            case ast::NodeValue::ConstDecl(decl) => {
835
                try lowerDataDecl(low, node, decl.value, true);
836
            }
837
            case ast::NodeValue::StaticDecl(decl) => {
838
                try lowerDataDecl(low, node, decl.value, false);
839
            }
840
            case ast::NodeValue::InstanceDecl { traitName, targetType, methods } => {
841
                try lowerInstanceDecl(low, node, traitName, targetType, methods);
842
            }
843
            case ast::NodeValue::MethodDecl { name, receiverName, receiverType, sig, body, .. } => {
844
                if let f = try lowerMethodDecl(low, node, name, receiverName, sig, body) {
845
                    emitFunction(low, f, FnRole::Normal);
846
                }
847
            }
848
            else => {},
849
        }
850
    }
851
}
852
853
/// Consume the lowerer and publish its global data as an immutable array.
854
export fn finalize(low: Lowerer) -> il::Program {
855
    let case Lowerer { data, output, .. } = low
856
        else panic "expected lowerer";
857
    match output {
858
        case FnOutput::Accumulate(accumulated) => {
859
            return il::Program {
860
                data,
861
                fns: accumulated,
862
            };
863
        }
864
        case FnOutput::Stream(_) => {
865
            panic "finalize: cannot finalize streaming lowerer";
866
        }
867
    }
868
}
869
870
/////////////////////////////////
871
// Qualified Name Construction //
872
/////////////////////////////////
873
874
/// Get module path segments for the current or specified module.
875
/// Returns empty slice if no module graph or module not found.
876
unsafe fn getModulePath(self: &mut Lowerer, modId: ?u16) -> *[*[u8]] {
877
    let graph = self.moduleGraph else {
878
        return &[];
879
    };
880
    let mut id = modId;
881
    if id == nil {
882
        set id = self.currentMod;
883
    }
884
    let actualId = id else {
885
        return &[];
886
    };
887
    let entry = module::get(graph, actualId) else {
888
        return &[];
889
    };
890
    return module::moduleQualifiedPath(entry);
891
}
892
893
/// Build a qualified name string for a symbol.
894
/// If `modId` is nil, uses current module.
895
unsafe fn qualifyName(self: &mut Lowerer, modId: ?u16, name: *[u8]) -> *[u8] {
896
    let path = getModulePath(self, modId);
897
    if path.len == 0 {
898
        return name;
899
    }
900
    return il::formatQualifiedName(self.arena, path, name);
901
}
902
903
/// Register a function symbol with its qualified name.
904
/// Called when lowering function declarations, so cross-package calls can find
905
/// the function by name.
906
fn registerFnSym(self: &mut Lowerer, sym: *unsafe resolver::Symbol, qualName: *[u8]) {
907
    self.fnSyms.append(FnSymEntry { sym, qualName }, self.allocator);
908
}
909
910
/// Look up a function's qualified name by its symbol.
911
/// Returns `nil` if the symbol wasn't registered (e.g. callee's module is not yet lowered).
912
// TODO: This is kind of dubious as an optimization, if it depends on the order
913
// in which modules are lowered.
914
// TODO: Use a hash table here?
915
unsafe fn lookupFnSym(self: &Lowerer, sym: *unsafe resolver::Symbol) -> ?*[u8] {
916
    for entry in &self.fnSyms[..] {
917
        if entry.sym == sym {
918
            return entry.qualName;
919
        }
920
    }
921
    return nil;
922
}
923
924
/// Set the package context for lowering.
925
/// Called before lowering each package.
926
/// The graph must outlive later uses of the lowerer.
927
export unsafe fn setPackage(self: &mut Lowerer, graph: &module::ModuleGraph, pkgName: *[u8]) {
928
    set self.moduleGraph = graph as *unsafe module::ModuleGraph;
929
    set self.pkgName = pkgName;
930
    set self.currentMod = nil;
931
}
932
933
/// Create a new function lowerer for a given function type and name.
934
unsafe fn fnLowerer(
935
    self: &mut Lowerer,
936
    node: *ast::Node,
937
    fnType: *resolver::FnType,
938
    qualName: *[u8]
939
) -> FnLowerer {
940
    let loopStack = try! alloc::allocRawSlice(self.fnArena, @sizeOf(LoopCtx), @alignOf(LoopCtx), MAX_LOOP_DEPTH) as *unsafe mut [LoopCtx];
941
942
    let mut fnLow = FnLowerer {
943
        low: (&mut *self) as *unsafe mut Lowerer,
944
        allocator: alloc::arenaAllocator(self.fnArena),
945
        fnType: fnType,
946
        localCount: resolver::nodeData(self.resolver, node).localCount,
947
        fnName: qualName,
948
        vars: &mut [],
949
        params: &mut [],
950
        blockData: &mut [],
951
        entryBlock: nil,
952
        currentBlock: nil,
953
        loopStack,
954
        loopDepth: 0,
955
        labelCounter: 0,
956
        dataCounter: 0,
957
        regCounter: 0,
958
        returnReg: nil,
959
        isLeaf: true,
960
        srcLoc: undefined,
961
    };
962
    if self.options.debug {
963
        let modId = self.currentMod else {
964
            panic "fnLowerer: debug enabled but no current module";
965
        };
966
        set fnLow.srcLoc = il::SrcLoc {
967
            moduleId: modId,
968
            offset: node.span.offset,
969
        };
970
    }
971
    return fnLow;
972
}
973
974
/// Lower a function declaration.
975
///
976
/// This sets up the per-function lowering state, processes parameters,
977
/// then lowers the function body into a CFG of basic blocks.
978
///
979
/// For throwing functions, the return type is a result aggregate
980
/// rather than the declared return type.
981
unsafe fn lowerFnDecl(self: &mut Lowerer, node: *ast::Node, decl: ast::FnDecl) -> ?*unsafe il::Fn throws (LowerError) {
982
    if not shouldLowerFn(&decl, self.options.buildTest) {
983
        return nil;
984
    }
985
    let case ast::NodeValue::Ident(name) = decl.name.value else {
986
        throw LowerError::ExpectedIdentifier;
987
    };
988
    let data = resolver::nodeData(self.resolver, node);
989
    let case resolver::Type::Fn(fnType) = data.ty else {
990
        throw LowerError::ExpectedFunction;
991
    };
992
    let isExtern = checkAttr(decl.attrs, ast::Attribute::Extern);
993
994
    // Build qualified function name for multi-module compilation.
995
    let qualName = qualifyName(self, nil, name);
996
997
    // Register function symbol for cross-package call resolution.
998
    if let sym = data.sym {
999
        registerFnSym(self, sym, qualName);
1000
    }
1001
    let mut fnLow = fnLowerer(self, node, fnType, qualName);
1002
1003
    // If the function returns an aggregate or is throwing, prepend a hidden
1004
    // return parameter. The caller allocates the buffer and passes it
1005
    // as the first argument; the callee writes the return value into it.
1006
    if requiresReturnParam(fnType) and not isExtern {
1007
        set fnLow.returnReg = nextReg(&mut fnLow);
1008
    }
1009
    let lowParams = try lowerParams(&mut fnLow, *fnType, decl.sig.params, nil);
1010
    let func = try! alloc::allocRaw(self.fnArena, @sizeOf(il::Fn), @alignOf(il::Fn)) as *unsafe mut il::Fn;
1011
1012
    set *func = il::Fn {
1013
        name: qualName,
1014
        params: lowParams,
1015
        returnType: undefined,
1016
        isExtern,
1017
        isLeaf: true,
1018
        blocks: &[],
1019
    };
1020
    // Throwing functions return a result aggregate (word-sized pointer).
1021
    // TODO: The resolver should set an appropriate type that takes into account
1022
    //       the throws list. It shouldn't set the return type to the "success"
1023
    //       value only.
1024
    if fnType.throwList.len > 0 {
1025
        set func.returnType = il::Type::W64;
1026
    } else {
1027
        set func.returnType = ilType(self, *fnType.returnType);
1028
    }
1029
    let body = decl.body else {
1030
        // Extern functions have no body.
1031
        assert isExtern;
1032
        return func;
1033
    };
1034
    set func.blocks = try lowerFnBody(&mut fnLow, body);
1035
    set func.isLeaf = fnLow.isLeaf;
1036
1037
    return func;
1038
}
1039
1040
/// Build a qualified name of the form "Type::method".
1041
unsafe fn instanceMethodName(self: &mut Lowerer, modId: ?u16, typeName: *[u8], methodName: *[u8]) -> *[u8] {
1042
    let sepLen: u32 = 2; // "::"
1043
    let totalLen = typeName.len + sepLen + methodName.len;
1044
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
1045
    let mut pos: u32 = 0;
1046
1047
    set pos += try! mem::copy(&mut buf[pos..], typeName);
1048
    set pos += try! mem::copy(&mut buf[pos..], "::");
1049
    set pos += try! mem::copy(&mut buf[pos..], methodName);
1050
    assert pos == totalLen;
1051
1052
    return qualifyName(self, modId, &buf[..totalLen]);
1053
}
1054
1055
/// Build a v-table data name of the form "vtable::Type::Trait".
1056
unsafe fn vtableName(self: &mut Lowerer, modId: ?u16, typeName: *[u8], traitName: *[u8]) -> *[u8] {
1057
    let prefix = "vtable::";
1058
    let sepLen: u32 = 2; // "::"
1059
    let totalLen = prefix.len + typeName.len + sepLen + traitName.len;
1060
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
1061
    let mut pos: u32 = 0;
1062
1063
    set pos += try! mem::copy(&mut buf[pos..], prefix);
1064
    set pos += try! mem::copy(&mut buf[pos..], typeName);
1065
    set pos += try! mem::copy(&mut buf[pos..], "::");
1066
    set pos += try! mem::copy(&mut buf[pos..], traitName);
1067
    assert pos == totalLen;
1068
1069
    return qualifyName(self, modId, &buf[..totalLen]);
1070
}
1071
1072
/// Lower an instance declaration (`instance Trait for Type { ... }`).
1073
///
1074
/// Each method in the instance block is lowered as a standalone function
1075
/// with a qualified name of the form `Type::method`. A read-only v-table
1076
/// data record is emitted containing pointers to these functions, ordered
1077
/// by the trait's method indices. The v-table is later referenced when
1078
/// constructing trait objects for dynamic dispatch.
1079
unsafe fn lowerInstanceDecl(
1080
    self: &mut Lowerer,
1081
    node: *ast::Node,
1082
    traitNameNode: *ast::Node,
1083
    targetTypeNode: *ast::Node,
1084
    methods: *[*ast::Node]
1085
) throws (LowerError) {
1086
    // Look up the trait and type from the resolver.
1087
    let traitSym = resolver::nodeData(self.resolver, traitNameNode).sym
1088
        else throw LowerError::MissingSymbol(traitNameNode);
1089
    let case resolver::SymbolData::Trait(traitInfo) = traitSym.data
1090
        else throw LowerError::MissingMetadata;
1091
    let typeSym = resolver::nodeData(self.resolver, targetTypeNode).sym
1092
        else throw LowerError::MissingSymbol(targetTypeNode);
1093
1094
    let tName = traitSym.name;
1095
    let typeName = typeSym.name;
1096
1097
    // Lower each instance method as a regular function.
1098
    // Collect qualified names for the v-table. Empty entries are filled
1099
    // later from inherited supertrait methods.
1100
    let mut methodNames: [*[u8]; ast::MAX_TRAIT_METHODS] = undefined;
1101
    let mut methodNameSet: [bool; ast::MAX_TRAIT_METHODS] = [false; ast::MAX_TRAIT_METHODS];
1102
1103
    for methodNode in methods {
1104
        let case ast::NodeValue::MethodDecl {
1105
            name, receiverName, receiverType, sig, body, ..
1106
        } = methodNode.value else continue;
1107
1108
        let case ast::NodeValue::Ident(mName) = name.value else {
1109
            throw LowerError::ExpectedIdentifier;
1110
        };
1111
        let qualName = instanceMethodName(self, nil, typeName, mName);
1112
        let func = try lowerMethod(self, methodNode, qualName, receiverName, sig, body)
1113
            else continue;
1114
        emitFunction(self, func, FnRole::Normal);
1115
1116
        let method = resolver::findTraitMethod(traitInfo, mName)
1117
            else panic "lowerInstanceDecl: method not found in trait";
1118
1119
        set methodNames[method.index] = qualName;
1120
        set methodNameSet[method.index] = true;
1121
    }
1122
1123
    // Fill inherited method slots from supertraits.
1124
    // These methods were already lowered as part of the supertrait instance
1125
    // declarations and use the same `Type::method` qualified name.
1126
    for method, i in traitInfo.methods {
1127
        if not methodNameSet[i] {
1128
            set methodNames[i] = instanceMethodName(self, nil, typeName, method.name);
1129
        }
1130
    }
1131
1132
    // Create v-table in data section, used for dynamic dispatch.
1133
    let vName = vtableName(self, nil, typeName, tName);
1134
    let values = try! alloc::allocSlice(
1135
        self.arena, @sizeOf(il::DataValue), @alignOf(il::DataValue), traitInfo.methods.len as u32
1136
    ) as *mut [il::DataValue];
1137
1138
    for i in 0..traitInfo.methods.len {
1139
        set values[i] = il::DataValue {
1140
            item: il::DataItem::Fn(methodNames[i]),
1141
            count: 1,
1142
        };
1143
    }
1144
    self.data.append(il::Data {
1145
        name: vName,
1146
        size: traitInfo.methods.len as u32 * resolver::PTR_SIZE,
1147
        alignment: resolver::PTR_SIZE,
1148
        readOnly: true,
1149
        isZeroInit: false,
1150
        values: &values[..traitInfo.methods.len as u32],
1151
    }, self.allocator);
1152
}
1153
1154
/// Lower a method node into an IL function with the given qualified name.
1155
/// Shared by both instance methods and standalone methods.
1156
unsafe fn lowerMethod(
1157
    self: &mut Lowerer,
1158
    node: *ast::Node,
1159
    qualName: *[u8],
1160
    receiverName: *ast::Node,
1161
    sig: ast::FnSig,
1162
    body: *ast::Node,
1163
) -> ?*unsafe il::Fn throws (LowerError) {
1164
    let data = resolver::nodeData(self.resolver, node);
1165
    let case resolver::Type::Fn(fnType) = data.ty else {
1166
        throw LowerError::ExpectedFunction;
1167
    };
1168
    let sym = data.sym else throw LowerError::MissingSymbol(node);
1169
    registerFnSym(self, sym, qualName);
1170
1171
    let mut fnLow = fnLowerer(self, node, fnType, qualName);
1172
    if requiresReturnParam(fnType) {
1173
        set fnLow.returnReg = nextReg(&mut fnLow);
1174
    }
1175
    let lowParams = try lowerParams(&mut fnLow, *fnType, sig.params, receiverName);
1176
    let func = try! alloc::allocRaw(self.fnArena, @sizeOf(il::Fn), @alignOf(il::Fn)) as *unsafe mut il::Fn;
1177
1178
    set *func = il::Fn {
1179
        name: qualName,
1180
        params: lowParams,
1181
        returnType: ilType(self, *fnType.returnType),
1182
        isExtern: false,
1183
        isLeaf: true,
1184
        blocks: &[],
1185
    };
1186
    if fnType.throwList.len > 0 {
1187
        set func.returnType = il::Type::W64;
1188
    }
1189
    set func.blocks = try lowerFnBody(&mut fnLow, body);
1190
    set func.isLeaf = fnLow.isLeaf;
1191
1192
    return func;
1193
}
1194
1195
/// Lower a standalone method declaration.
1196
/// Produces a function with qualified name `Type::method`.
1197
unsafe fn lowerMethodDecl(
1198
    self: &mut Lowerer,
1199
    node: *ast::Node,
1200
    name: *ast::Node,
1201
    receiverName: *ast::Node,
1202
    sig: ast::FnSig,
1203
    body: *ast::Node,
1204
) -> ?*unsafe il::Fn throws (LowerError) {
1205
    let sym = resolver::nodeData(self.resolver, node).sym
1206
        else throw LowerError::MissingSymbol(node);
1207
    let case ast::NodeValue::Ident(mName) = name.value
1208
        else throw LowerError::ExpectedIdentifier;
1209
    let me = resolver::findMethodBySymbol(self.resolver, sym)
1210
        else throw LowerError::MissingMetadata;
1211
    let qualName = instanceMethodName(self, nil, me.concreteTypeName, mName);
1212
1213
    return try lowerMethod(self, node, qualName, receiverName, sig, body);
1214
}
1215
1216
/// Check if a function should be lowered.
1217
fn shouldLowerFn(decl: &ast::FnDecl, buildTest: bool) -> bool {
1218
    if checkAttr(decl.attrs, ast::Attribute::Test) {
1219
        return buildTest;
1220
    }
1221
    return true;
1222
}
1223
1224
/// Check if a specific attribute is present in the attribute set.
1225
fn checkAttr(attrs: ?ast::Attributes, attr: ast::Attribute) -> bool {
1226
    if let a = attrs {
1227
        return ast::attributesContains(&a, attr);
1228
    }
1229
    return false;
1230
}
1231
1232
/// Create a label with a numeric suffix, eg. `@base0`.
1233
/// This ensures unique labels like `@then0`, `@then1`, etc.
1234
unsafe fn labelWithSuffix(self: &mut FnLowerer, base: *[u8], suffix: u32) -> *[u8] throws (LowerError) {
1235
    let mut digits: [u8; fmt::U32_STR_LEN] = undefined;
1236
    let start = fmt::formatU32(suffix, &mut digits[..]);
1237
    let totalLen = base.len + digits.len - start;
1238
    let buf = try! alloc::allocSlice(self.low.fnArena, 1, 1, totalLen) as *mut [u8];
1239
1240
    try! mem::copy(&mut buf[..base.len], base);
1241
    try! mem::copy(&mut buf[base.len..totalLen], &digits[start..]);
1242
1243
    return &buf[..totalLen];
1244
}
1245
1246
/// Generate a unique label by appending the global counter to the base.
1247
unsafe fn nextLabel(self: &mut FnLowerer, base: *[u8]) -> *[u8] throws (LowerError) {
1248
    let idx = self.labelCounter;
1249
    set self.labelCounter += 1;
1250
1251
    return try labelWithSuffix(self, base, idx);
1252
}
1253
1254
///////////////////////////////
1255
// Data Section Construction //
1256
///////////////////////////////
1257
1258
// Functions for building the data section from constant/static
1259
// declarations and inline literals.
1260
1261
/// Convert a constant integer payload to a signed 64-bit value.
1262
fn constIntToI64(intVal: resolver::ConstInt) -> i64 {
1263
    return (0 - intVal.magnitude as i64) if intVal.negative else intVal.magnitude as i64;
1264
}
1265
1266
/// Convert a scalar constant value to an i64.
1267
/// String constants are not handled here and should be checked before calling.
1268
/// Panics if a non-scalar value is passed.
1269
fn constToScalar(val: resolver::ConstValue) -> i64 {
1270
    match val {
1271
        case resolver::ConstValue::Bool(b) => return 1 if b else 0,
1272
        case resolver::ConstValue::Char(c) => return c as i64,
1273
        case resolver::ConstValue::Int(i) => return constIntToI64(i),
1274
        else => panic,
1275
    }
1276
}
1277
1278
/// Convert a constant value to an IL value.
1279
unsafe fn constValueToVal(self: &mut FnLowerer, val: resolver::ConstValue, node: *ast::Node) -> il::Val throws (LowerError) {
1280
    if let case resolver::ConstValue::String(s) = val {
1281
        return try lowerStringLit(self, node, s);
1282
    }
1283
    return il::Val::Imm(constToScalar(val));
1284
}
1285
1286
/// Convert a resolver constant value to an IL data initializer item.
1287
unsafe fn constValueToDataItem(self: &mut Lowerer, val: resolver::ConstValue, typ: resolver::Type) -> il::DataItem {
1288
    if let case resolver::ConstValue::String(s) = val {
1289
        return il::DataItem::Str(s);
1290
    }
1291
    // Bool and char are byte-sized; integer uses the declared type.
1292
    let mut irTyp = il::Type::W8;
1293
    if let case resolver::ConstValue::Int(_) = val {
1294
        set irTyp = ilType(self, typ);
1295
    }
1296
    return il::DataItem::Val { typ: irTyp, val: constToScalar(val) };
1297
}
1298
1299
/// Lower scalar-like constant nodes into data values, including fallback handling
1300
/// for void-variant tags and slice string initializers.
1301
unsafe fn lowerConstScalarDataInto(
1302
    self: &mut Lowerer,
1303
    node: *ast::Node,
1304
    ty: resolver::Type,
1305
    dataPrefix: *[u8],
1306
    b: &mut DataValueBuilder
1307
) throws (LowerError) {
1308
    let val = resolver::constValueEntry(self.resolver, node) else {
1309
        if let idx = voidVariantIndex(self.resolver, node) {
1310
            dataBuilderPush(b, il::DataValue {
1311
                item: il::DataItem::Val { typ: il::Type::W8, val: idx },
1312
                count: 1
1313
            });
1314
            return;
1315
        }
1316
        throw LowerError::MissingConst(node);
1317
    };
1318
1319
    if let case resolver::ConstValue::String(s) = val {
1320
        if let case resolver::Type::Slice { .. } = ty {
1321
            let strSym = try getOrCreateStringData(self, s, dataPrefix);
1322
            dataSliceHeader(b, strSym, s.len);
1323
            return;
1324
        }
1325
    }
1326
    dataBuilderPush(b, il::DataValue {
1327
        item: constValueToDataItem(self, val, ty),
1328
        count: 1
1329
    });
1330
}
1331
1332
/// Lower a constant or static declaration to the data section.
1333
unsafe fn lowerDataDecl(
1334
    self: &mut Lowerer,
1335
    node: *ast::Node,
1336
    value: *ast::Node,
1337
    readOnly: bool
1338
) throws (LowerError) {
1339
    let data = resolver::nodeData(self.resolver, node);
1340
    let sym = data.sym else {
1341
        throw LowerError::MissingSymbol(node);
1342
    };
1343
    if data.ty == resolver::Type::Unknown {
1344
        throw LowerError::MissingType(node);
1345
    }
1346
    let layout = resolver::getTypeLayout(data.ty);
1347
    let qualName = qualifyName(self, nil, sym.name);
1348
    let mut b = dataBuilder(self.allocator);
1349
    try lowerConstDataInto(self, value, data.ty, layout.size, qualName, &mut b);
1350
    let result = dataBuilderFinish(b);
1351
1352
    self.data.append(il::Data {
1353
        name: qualName,
1354
        size: layout.size,
1355
        alignment: layout.alignment,
1356
        readOnly,
1357
        isZeroInit: not readOnly and result.zeroInit,
1358
        values: result.values,
1359
    }, self.allocator);
1360
}
1361
1362
/// Emit the in-memory representation of a slice header: `{ ptr, len, cap }`.
1363
fn dataSliceHeader(b: &mut DataValueBuilder, dataSym: *[u8], len: u32) {
1364
    dataBuilderPush(b, il::DataValue {
1365
        item: il::DataItem::Sym(dataSym),
1366
        count: 1
1367
    });
1368
    dataBuilderPush(b, il::DataValue {
1369
        item: il::DataItem::Val {
1370
            typ: il::Type::W32,
1371
            val: len as i64
1372
        },
1373
        count: 1
1374
    });
1375
    dataBuilderPush(b, il::DataValue {
1376
        item: il::DataItem::Val {
1377
            typ: il::Type::W32,
1378
            val: len as i64
1379
        },
1380
        count: 1
1381
    });
1382
}
1383
1384
/// Lower a compile-time `&[...]` expression to a concrete slice header.
1385
unsafe fn lowerConstAddressSliceInto(
1386
    self: &mut Lowerer,
1387
    addr: ast::AddressOf,
1388
    ty: resolver::Type,
1389
    dataPrefix: *[u8],
1390
    b: &mut DataValueBuilder
1391
) throws (LowerError) {
1392
    let case resolver::Type::Slice { mutable, .. } = ty
1393
        else throw LowerError::ExpectedSliceOrArray;
1394
    let targetTy = resolver::typeFor(self.resolver, addr.target)
1395
        else throw LowerError::MissingType(addr.target);
1396
    let case resolver::Type::Array(arrInfo) = targetTy
1397
        else throw LowerError::ExpectedArray;
1398
1399
    let mut nested = dataBuilder(self.allocator);
1400
    let layout = resolver::getTypeLayout(targetTy);
1401
    try lowerConstDataInto(self, addr.target, targetTy, layout.size, dataPrefix, &mut nested);
1402
1403
    let backing = dataBuilderFinish(nested);
1404
    let readOnly = not mutable;
1405
    let mut dataName: *[u8] = undefined;
1406
    if readOnly {
1407
        if let found = findConstData(self, backing.values, layout.alignment) {
1408
            set dataName = found;
1409
        } else {
1410
            set dataName = try pushDeclData(self, layout.size, layout.alignment, readOnly, backing.values, dataPrefix);
1411
        }
1412
    } else {
1413
        set dataName = try pushDeclData(self, layout.size, layout.alignment, readOnly, backing.values, dataPrefix);
1414
    }
1415
    dataSliceHeader(b, dataName, arrInfo.length);
1416
}
1417
1418
/// Lower a constant expression payload into a builder without slot padding.
1419
/// Compute the type layout when nil or undefined data needs a byte count.
1420
unsafe fn lowerConstDataPayloadInto(
1421
    self: &mut Lowerer,
1422
    node: *ast::Node,
1423
    ty: resolver::Type,
1424
    dataPrefix: *[u8],
1425
    b: &mut DataValueBuilder
1426
) throws (LowerError) {
1427
    // Optional coercions define the tag and payload layout of constant values.
1428
    if let case resolver::Type::Optional(inner) = ty {
1429
        if let coercion = resolver::coercionFor(self.resolver, node) {
1430
            if let case resolver::Coercion::OptionalLift(target) = coercion {
1431
                if resolver::typesEqual(target, ty) {
1432
                    if resolver::isNullableType(*inner) {
1433
                        try lowerConstDataPayloadInto(self, node, *inner, dataPrefix, b);
1434
                    } else {
1435
                        let layout = resolver::getTypeLayout(ty);
1436
                        let offset = resolver::getOptionalValOffset(*inner);
1437
                        dataBuilderPush(b, il::DataValue {
1438
                            item: il::DataItem::Val { typ: il::Type::W8, val: 1 }, count: 1,
1439
                        });
1440
                        if offset > 1 {
1441
                            dataBuilderPush(b, il::DataValue { item: il::DataItem::Undef, count: offset - 1 });
1442
                        }
1443
                        try lowerConstDataInto(self, node, *inner, layout.size - offset, dataPrefix, b);
1444
                    }
1445
                    return;
1446
                }
1447
            }
1448
        }
1449
    }
1450
    // Function pointer references in constant data.
1451
    if let case resolver::Type::Fn(_) = ty {
1452
        let sym = resolver::nodeData(self.resolver, node).sym
1453
            else throw LowerError::MissingSymbol(node);
1454
        let modId = resolver::moduleIdForSymbol(self.resolver, sym);
1455
        let qualName = qualifyName(self, modId, sym.name);
1456
        dataBuilderPush(b, il::DataValue {
1457
            item: il::DataItem::Fn(qualName), count: 1,
1458
        });
1459
        return;
1460
    }
1461
    // In constant data, a void variant of a mixed union still occupies the
1462
    // full tagged-union slot. Emitting only the tag corrupts following fields.
1463
    if let sym = resolver::nodeData(self.resolver, node).sym {
1464
        if let case resolver::SymbolData::Variant { type: resolver::Type::Void, .. } = sym.data {
1465
            if let case resolver::Type::Nominal(resolver::NominalType::Union(_)) = ty {
1466
                try lowerConstUnionVariantInto(self, node, sym, ty, &mut [], dataPrefix, b);
1467
                return;
1468
            }
1469
        }
1470
    }
1471
    match node.value {
1472
        case ast::NodeValue::Nil => {
1473
            let case resolver::Type::Optional(_) = ty else throw LowerError::NilInNonOptional;
1474
            let layout = resolver::getTypeLayout(ty);
1475
            dataBuilderPush(b, il::DataValue {
1476
                item: il::DataItem::Val { typ: il::Type::W8, val: 0 }, count: layout.size,
1477
            });
1478
        },
1479
        case ast::NodeValue::Undef => {
1480
            let layout = resolver::getTypeLayout(ty);
1481
            dataBuilderPush(b, il::DataValue {
1482
                item: il::DataItem::Undef,
1483
                count: layout.size
1484
            });
1485
        }
1486
        case ast::NodeValue::ArrayLit(elems) =>
1487
            try lowerConstArrayLitInto(self, elems, ty, dataPrefix, b),
1488
        case ast::NodeValue::ArrayRepeatLit(repeat) =>
1489
            try lowerConstArrayRepeatInto(self, repeat, ty, dataPrefix, b),
1490
        case ast::NodeValue::RecordLit(recLit) =>
1491
            try lowerConstRecordLitInto(self, node, recLit, ty, dataPrefix, b),
1492
        case ast::NodeValue::Call(call) => {
1493
            let calleeSym = resolver::nodeData(self.resolver, call.callee).sym
1494
                else throw LowerError::MissingSymbol(call.callee);
1495
            match calleeSym.data {
1496
                case resolver::SymbolData::Variant { .. } =>
1497
                    try lowerConstUnionVariantInto(self, node, calleeSym, ty, call.args, dataPrefix, b),
1498
                case resolver::SymbolData::Type(resolver::NominalType::Record(recInfo)) => {
1499
                    try lowerConstRecordCtorInto(self, call.args, recInfo, dataPrefix, b);
1500
                }
1501
                else => throw LowerError::MissingConst(node)
1502
            }
1503
        }
1504
        case ast::NodeValue::AddressOf(addr) => {
1505
            try lowerConstAddressSliceInto(self, addr, ty, dataPrefix, b);
1506
        }
1507
        case ast::NodeValue::Ident(_) => {
1508
            // Identifier referencing a constant.
1509
            let sym = resolver::nodeData(self.resolver, node).sym
1510
                else throw LowerError::MissingSymbol(node);
1511
            let case ast::NodeValue::ConstDecl(decl) = sym.node.value
1512
                else throw LowerError::MissingConst(node);
1513
1514
            try lowerConstDataPayloadInto(self, decl.value, ty, dataPrefix, b);
1515
        },
1516
        case ast::NodeValue::ScopeAccess(_) => {
1517
            let sym = resolver::nodeData(self.resolver, node).sym
1518
                else throw LowerError::MissingSymbol(node);
1519
            if let case ast::NodeValue::ConstDecl(decl) = sym.node.value {
1520
                try lowerConstDataPayloadInto(self, decl.value, ty, dataPrefix, b);
1521
            } else {
1522
                try lowerConstScalarDataInto(self, node, ty, dataPrefix, b);
1523
            }
1524
        }
1525
        else => {
1526
            // Scalar values: integers, bools, strings, void union variants, etc.
1527
            try lowerConstScalarDataInto(self, node, ty, dataPrefix, b);
1528
        }
1529
    }
1530
}
1531
1532
/// Lower a constant expression into a builder, padding to the given slot size.
1533
unsafe fn lowerConstDataInto(
1534
    self: &mut Lowerer,
1535
    node: *ast::Node,
1536
    ty: resolver::Type,
1537
    slotSize: u32,
1538
    dataPrefix: *[u8],
1539
    b: &mut DataValueBuilder
1540
) throws (LowerError) {
1541
    let layout = resolver::getTypeLayout(ty);
1542
    try lowerConstDataPayloadInto(self, node, ty, dataPrefix, b);
1543
    // Pad to fill the enclosing slot.
1544
    let padding = slotSize - layout.size;
1545
    if padding > 0 {
1546
        dataBuilderPush(b, il::DataValue { item: il::DataItem::Undef, count: padding });
1547
    }
1548
}
1549
1550
/// Flatten a constant array literal `[a, b, c]` into a builder.
1551
/// Each element payload fills its type size; no extra slot padding is needed.
1552
unsafe fn lowerConstArrayLitInto(
1553
    self: &mut Lowerer,
1554
    elems: *[*ast::Node],
1555
    ty: resolver::Type,
1556
    dataPrefix: *[u8],
1557
    b: &mut DataValueBuilder
1558
) throws (LowerError) {
1559
    let case resolver::Type::Array(arrInfo) = ty
1560
        else throw LowerError::ExpectedArray;
1561
    let elemTy = *arrInfo.item;
1562
1563
    for elem in elems {
1564
        try lowerConstDataPayloadInto(self, elem, elemTy, dataPrefix, b);
1565
    }
1566
}
1567
1568
/// Build data values for a constant array repeat literal `[item; count]`.
1569
/// Repeat element payloads without extra slot padding. Undefined data uses
1570
/// the element layout to compute the total byte count.
1571
unsafe fn lowerConstArrayRepeatInto(
1572
    self: &mut Lowerer,
1573
    repeat: ast::ArrayRepeatLit,
1574
    ty: resolver::Type,
1575
    dataPrefix: *[u8],
1576
    b: &mut DataValueBuilder
1577
) throws (LowerError) {
1578
    let case resolver::Type::Array(arrInfo) = ty
1579
        else throw LowerError::ExpectedArray;
1580
    let length = arrInfo.length;
1581
    let elemTy = *arrInfo.item;
1582
1583
    if let case resolver::Type::Optional(_) = elemTy {
1584
        for _ in 0..length {
1585
            try lowerConstDataPayloadInto(self, repeat.item, elemTy, dataPrefix, b);
1586
        }
1587
        return;
1588
    }
1589
1590
    if let case ast::NodeValue::Undef = repeat.item.value {
1591
        let elemLayout = resolver::getTypeLayout(elemTy);
1592
        dataBuilderPush(b, il::DataValue {
1593
            item: il::DataItem::Undef,
1594
            count: elemLayout.size * length
1595
        });
1596
    } else if let val = resolver::constValueEntry(self.resolver, repeat.item) {
1597
        if let case resolver::ConstValue::String(_) = val {
1598
            // A string used as a slice is represented by a three-word slice
1599
            // header, not by the bytes of the string itself.
1600
            for _ in 0..length {
1601
                try lowerConstDataPayloadInto(self, repeat.item, elemTy, dataPrefix, b);
1602
            }
1603
        } else {
1604
            dataBuilderPush(b, il::DataValue {
1605
                item: constValueToDataItem(self, val, elemTy),
1606
                count: length
1607
            });
1608
        }
1609
    } else {
1610
        for _ in 0..length {
1611
            try lowerConstDataPayloadInto(self, repeat.item, elemTy, dataPrefix, b);
1612
        }
1613
    }
1614
}
1615
1616
/// Build data values for a constant record literal.
1617
/// Each field is lowered with a slot size that includes trailing padding.
1618
unsafe fn lowerConstRecordLitInto(
1619
    self: &mut Lowerer,
1620
    node: *ast::Node,
1621
    recLit: ast::RecordLit,
1622
    ty: resolver::Type,
1623
    dataPrefix: *[u8],
1624
    b: &mut DataValueBuilder
1625
) throws (LowerError) {
1626
    match ty {
1627
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) => {
1628
            try lowerConstRecordCtorInto(self, recLit.fields, recInfo, dataPrefix, b);
1629
        }
1630
        case resolver::Type::Nominal(resolver::NominalType::Union(_)) => {
1631
            let typeName = recLit.typeName else {
1632
                throw LowerError::ExpectedVariant;
1633
            };
1634
            let sym = resolver::nodeData(self.resolver, typeName).sym else {
1635
                throw LowerError::MissingSymbol(typeName);
1636
            };
1637
            try lowerConstUnionVariantInto(self, node, sym, ty, recLit.fields, dataPrefix, b);
1638
        }
1639
        else => throw LowerError::ExpectedRecord,
1640
    }
1641
}
1642
1643
/// Build data values for record constants.
1644
unsafe fn lowerConstRecordCtorInto(
1645
    self: &mut Lowerer,
1646
    args: *[*ast::Node],
1647
    recInfo: resolver::RecordType,
1648
    dataPrefix: *[u8],
1649
    b: &mut DataValueBuilder
1650
) throws (LowerError) {
1651
    let layout = recInfo.layout;
1652
    for argNode, i in args {
1653
        let mut valueNode = argNode;
1654
        if let case ast::NodeValue::RecordLitField(fieldLit) = argNode.value {
1655
            set valueNode = fieldLit.value;
1656
        }
1657
        let fieldInfo = recInfo.fields[i];
1658
        let fieldOffset = fieldInfo.offset as u32;
1659
1660
        // Slot extends to the next field's offset,
1661
        // or record size for the last field.
1662
        let slotEnd = recInfo.fields[i + 1].offset as u32 if i + 1 < recInfo.fields.len else layout.size;
1663
        let slotSize = slotEnd - fieldOffset;
1664
1665
        try lowerConstDataInto(self, valueNode, fieldInfo.fieldType, slotSize, dataPrefix, b);
1666
    }
1667
}
1668
1669
/// Build data values for a constant union variant value from payload fields/args.
1670
unsafe fn lowerConstUnionVariantInto(
1671
    self: &mut Lowerer,
1672
    node: *ast::Node,
1673
    variantSym: *unsafe mut resolver::Symbol,
1674
    ty: resolver::Type,
1675
    payloadArgs: *[*ast::Node],
1676
    dataPrefix: *[u8],
1677
    b: &mut DataValueBuilder
1678
) throws (LowerError) {
1679
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } = variantSym.data
1680
        else throw LowerError::UnexpectedNodeValue(node);
1681
1682
    let unionInfo = unionInfoFromType(ty) else {
1683
        throw LowerError::MissingMetadata;
1684
    };
1685
    let unionLayout = resolver::getTypeLayout(ty);
1686
    let payloadSlotSize = unionLayout.size - unionInfo.valOffset;
1687
1688
    // Tag byte.
1689
    dataBuilderPush(b, il::DataValue {
1690
        item: il::DataItem::Val {
1691
            typ: il::Type::W8,
1692
            val: index as i64
1693
        },
1694
        count: 1
1695
    });
1696
    // Padding between tag and payload.
1697
    if unionInfo.valOffset > 1 {
1698
        dataBuilderPush(b, il::DataValue {
1699
            item: il::DataItem::Undef,
1700
            count: unionInfo.valOffset - 1
1701
        });
1702
    }
1703
    if payloadType == resolver::Type::Void {
1704
        if payloadSlotSize > 0 {
1705
            dataBuilderPush(b, il::DataValue {
1706
                item: il::DataItem::Undef,
1707
                count: payloadSlotSize
1708
            });
1709
        }
1710
        return;
1711
    }
1712
1713
    let case resolver::Type::Nominal(resolver::NominalType::Record(payloadRec)) = payloadType else {
1714
        throw LowerError::ExpectedRecord;
1715
    };
1716
    let payloadLayout = payloadRec.layout;
1717
    try lowerConstRecordCtorInto(self, payloadArgs, payloadRec, dataPrefix, b);
1718
1719
    // Unused bytes in the union payload slot for smaller variants.
1720
    if payloadSlotSize > payloadLayout.size {
1721
        dataBuilderPush(b, il::DataValue {
1722
            item: il::DataItem::Undef,
1723
            count: payloadSlotSize - payloadLayout.size
1724
        });
1725
    }
1726
}
1727
1728
/// Find an existing string data entry with matching content.
1729
// TODO: Optimize with hash table or remove?
1730
fn findStringData(self: &Lowerer, s: *[u8]) -> ?*[u8] {
1731
    for d in &self.data[..] {
1732
        if d.values.len == 1 {
1733
            if let case il::DataItem::Str(existing) = d.values[0].item {
1734
                if mem::eq(existing, s) {
1735
                    return d.name;
1736
                }
1737
            }
1738
        }
1739
    }
1740
    return nil;
1741
}
1742
1743
/// Compose a segmented symbol name from a list of path segments.
1744
/// Example: `["func", "nominal", "VALUE"]` -> `func$nominal$VALUE`.
1745
unsafe fn buildSegmentedName(
1746
    self: &mut Lowerer,
1747
    segments: &[*[u8]]
1748
) -> *[u8] throws (LowerError) {
1749
    assert segments.len > 0;
1750
1751
    let mut totalLen: u32 = 0;
1752
    for segment in segments {
1753
        set totalLen += segment.len;
1754
    }
1755
    if segments.len > 1 {
1756
        set totalLen += segments.len - 1;
1757
    }
1758
    let buf = try! alloc::allocSlice(self.arena, 1, 1, totalLen) as *mut [u8];
1759
    let mut pos: u32 = 0;
1760
1761
    for segment, i in segments {
1762
        set pos += try! mem::copy(&mut buf[pos..], segment);
1763
        if i + 1 <> segments.len {
1764
            set buf[pos] = '$';
1765
            set pos += 1;
1766
        }
1767
    }
1768
    assert pos == totalLen;
1769
1770
    return &buf[..totalLen];
1771
}
1772
1773
/// Generate a unique name for declaration-local backing data entries.
1774
unsafe fn nextDeclDataName(
1775
    self: &mut Lowerer,
1776
    prefix: *[u8],
1777
    count: u32,
1778
    namespace: *[u8]
1779
) -> *[u8] throws (LowerError) {
1780
    let mut digits: [u8; fmt::U32_STR_LEN] = undefined;
1781
    let start = fmt::formatU32(count, &mut digits[..]);
1782
    let suffix = try! alloc::allocSlice(self.arena, 1, 1, digits.len - start) as *mut [u8];
1783
    try! mem::copy(suffix, &digits[start..]);
1784
    let segments = [prefix, namespace, suffix];
1785
1786
    return try buildSegmentedName(self, &segments[..]);
1787
}
1788
1789
/// Append a data entry using a function-local literal namespace (`prefix$literal$N`).
1790
unsafe fn pushDeclData(
1791
    self: &mut Lowerer,
1792
    size: u32,
1793
    alignment: u32,
1794
    readOnly: bool,
1795
    values: *[il::DataValue],
1796
    dataPrefix: *[u8]
1797
) -> *[u8] throws (LowerError) {
1798
    let dataCount = self.data.len;
1799
    let name = try nextDeclDataName(self, dataPrefix, dataCount, "literal");
1800
    self.data.append(il::Data {
1801
        name,
1802
        size,
1803
        alignment,
1804
        readOnly,
1805
        isZeroInit: not readOnly and dataValuesAreZeroInit(values),
1806
        values,
1807
    }, self.allocator);
1808
1809
    return name;
1810
}
1811
1812
/// Find or create read-only string data and return its symbol name.
1813
unsafe fn getOrCreateStringData(
1814
    self: &mut Lowerer,
1815
    s: *[u8],
1816
    dataPrefix: *[u8]
1817
) -> *[u8] throws (LowerError) {
1818
    if let existing = findStringData(self, s) {
1819
        return existing;
1820
    }
1821
    let values = try! alloc::allocSlice(
1822
        self.arena, @sizeOf(il::DataValue), @alignOf(il::DataValue), 1
1823
    ) as *mut [il::DataValue];
1824
1825
    set values[0] = il::DataValue {
1826
        item: il::DataItem::Str(s),
1827
        count: 1
1828
    };
1829
    return try pushDeclData(self, s.len, 1, true, &values[..1], dataPrefix);
1830
}
1831
1832
/// Compare two data items for structural equality.
1833
/// Unlike raw byte comparison, this correctly ignores padding bytes in unions.
1834
fn dataItemEq(a: il::DataItem, b: il::DataItem) -> bool {
1835
    match a {
1836
        case il::DataItem::Val { typ: aTyp, val: aVal } =>
1837
            if let case il::DataItem::Val { typ: bTyp, val: bVal } = b {
1838
                return aTyp == bTyp and aVal == bVal;
1839
            } else {
1840
                return false;
1841
            },
1842
        case il::DataItem::Sym(aPtr) =>
1843
            if let case il::DataItem::Sym(bPtr) = b {
1844
                return mem::eq(aPtr, bPtr);
1845
            } else {
1846
                return false;
1847
            },
1848
        case il::DataItem::Fn(aName) =>
1849
            if let case il::DataItem::Fn(bName) = b {
1850
                return mem::eq(aName, bName);
1851
            } else {
1852
                return false;
1853
            },
1854
        case il::DataItem::Str(aStr) =>
1855
            if let case il::DataItem::Str(bStr) = b {
1856
                return mem::eq(aStr, bStr);
1857
            } else {
1858
                return false;
1859
            },
1860
        case il::DataItem::Undef =>
1861
            if let case il::DataItem::Undef = b {
1862
                return true;
1863
            } else {
1864
                return false;
1865
            },
1866
    }
1867
}
1868
1869
/// Compare two data value slices for structural equality.
1870
fn dataValuesEq(a: &[il::DataValue], b: &[il::DataValue]) -> bool {
1871
    if a.len <> b.len {
1872
        return false;
1873
    }
1874
    for i in 0..a.len {
1875
        if a[i].count <> b[i].count {
1876
            return false;
1877
        }
1878
        if not dataItemEq(a[i].item, b[i].item) {
1879
            return false;
1880
        }
1881
    }
1882
    return true;
1883
}
1884
1885
/// Find an existing read-only slice data entry with matching values.
1886
// TODO: Optimize with hash table or remove?
1887
fn findSliceData(self: &Lowerer, values: *[il::DataValue], alignment: u32) -> ?*[u8] {
1888
    for d in &self.data[..] {
1889
        if d.alignment == alignment and d.readOnly and dataValuesEq(d.values, values) {
1890
            return d.name;
1891
        }
1892
    }
1893
    return nil;
1894
}
1895
1896
/// Find existing constant data entry with matching content.
1897
/// Handles both string data and slice data.
1898
fn findConstData(self: &Lowerer, values: *[il::DataValue], alignment: u32) -> ?*[u8] {
1899
    // Fast path for strings.
1900
    if values.len == 1 and alignment == 1 {
1901
        if let case il::DataItem::Str(s) = values[0].item {
1902
            return findStringData(self, s);
1903
        }
1904
    }
1905
    // General case: byte comparison of data values.
1906
    return findSliceData(self, values, alignment);
1907
}
1908
1909
/// Lower constant data to a slice value.
1910
/// Creates or reuses a data section entry, then builds a slice header on the stack.
1911
unsafe fn lowerConstDataAsSlice(
1912
    self: &mut FnLowerer,
1913
    result: &ConstDataResult,
1914
    alignment: u32,
1915
    readOnly: bool,
1916
    elemTy: *resolver::Type,
1917
    mutable: bool,
1918
    length: u32
1919
) -> il::Val throws (LowerError) {
1920
    let values = result.values;
1921
    let elemLayout = resolver::getTypeLayout(*elemTy);
1922
    let size = elemLayout.size * length;
1923
    let mut dataName: *[u8] = undefined;
1924
    let mut found: ?*[u8] = nil;
1925
    if readOnly {
1926
        set found = findConstData(self.low, values, alignment);
1927
    }
1928
    if let name = found {
1929
        set dataName = name;
1930
    } else {
1931
        set dataName = try nextDataName(self);
1932
        self.low.data.append(il::Data {
1933
            name: dataName,
1934
            size,
1935
            alignment,
1936
            readOnly,
1937
            isZeroInit: not readOnly and result.zeroInit,
1938
            values,
1939
        }, self.low.allocator);
1940
    }
1941
1942
    // Get data address.
1943
    let ptrReg = nextReg(self);
1944
    emit(self, il::Instr::Copy { dst: ptrReg, val: il::Val::DataSym(dataName) });
1945
1946
    return try buildSliceValue(
1947
        self, elemTy, mutable, il::Val::Reg(ptrReg), il::Val::Imm(length as i64), il::Val::Imm(length as i64)
1948
    );
1949
}
1950
1951
/// Generate a unique data name for inline literals, eg. `fnName$literal$N`.
1952
unsafe fn nextDataName(self: &mut FnLowerer) -> *[u8] throws (LowerError) {
1953
    let counter = self.dataCounter;
1954
    set self.dataCounter += 1;
1955
    let fnName = self.fnName;
1956
    return try nextDeclDataName(self.low, fnName, counter, "literal");
1957
}
1958
1959
/// Assign a unique function-local data symbol name.
1960
unsafe fn registerLocalDataDeclName(self: &mut FnLowerer, node: *ast::Node) throws (LowerError) {
1961
    let sym = resolver::nodeData(self.low.resolver, node).sym
1962
        else throw LowerError::MissingSymbol(node);
1963
1964
    let prefix = self.fnName;
1965
    let segments = [prefix, "nominal", sym.name];
1966
    let name = try buildSegmentedName(self.low, &segments[..]);
1967
1968
    set sym.name = name;
1969
}
1970
1971
/// Get the next available SSA register.
1972
fn nextReg(self: &mut FnLowerer) -> il::Reg {
1973
    let reg = il::Reg { n: self.regCounter };
1974
    set self.regCounter += 1;
1975
    return reg;
1976
}
1977
1978
/// Look up the resolved type of an AST node, or throw `MissingType`.
1979
unsafe fn typeOf(self: &mut FnLowerer, node: *ast::Node) -> resolver::Type throws (LowerError) {
1980
    let ty = resolver::typeFor(self.low.resolver, node)
1981
        else throw LowerError::MissingType(node);
1982
    return ty;
1983
}
1984
1985
/// Look up the symbol for an AST node, or throw `MissingSymbol`.
1986
unsafe fn symOf(self: &mut FnLowerer, node: *ast::Node) -> *unsafe mut resolver::Symbol throws (LowerError) {
1987
    let sym = resolver::nodeData(self.low.resolver, node).sym
1988
        else throw LowerError::MissingSymbol(node);
1989
    return sym;
1990
}
1991
1992
/// Remove the last block parameter and its associated variable.
1993
/// Used when detecting a trivial phi that can be eliminated.
1994
unsafe fn removeLastBlockParam(self: &mut FnLowerer, block: BlockId) {
1995
    let blk = getBlockMut(self, block);
1996
    if blk.params.len > 0 {
1997
        // TODO: Use `pop`?
1998
        set blk.params = @sliceOf(blk.params.ptr, blk.params.len - 1, blk.params.cap);
1999
    }
2000
    if blk.paramVars.len > 0 {
2001
        // TODO: Use `pop`?
2002
        set blk.paramVars = @sliceOf(blk.paramVars.ptr, blk.paramVars.len - 1, blk.paramVars.cap);
2003
    }
2004
}
2005
2006
/// Rewrite cached SSA values for a variable across all blocks, and also
2007
/// rewrite any terminator arguments that reference the provisional register.
2008
/// The latter is necessary because recursive SSA resolution may have already
2009
/// patched terminator arguments with the provisional value before it was
2010
/// found to be trivial.
2011
unsafe fn rewriteCachedVarValue(self: &mut FnLowerer, v: Var, from: il::Val, to: il::Val) {
2012
    for i in 0..self.blockData.len {
2013
        let blk = getBlockMut(self, BlockId(i));
2014
        if blk.vars[*v] == from {
2015
            set blk.vars[*v] = to;
2016
        }
2017
        if blk.instrs.len > 0 {
2018
            let ix = blk.instrs.len - 1;
2019
            match &mut blk.instrs[ix] {
2020
                case il::Instr::Jmp { args, .. } =>
2021
                    rewriteValInSlice(*args, from, to),
2022
                case il::Instr::Br { thenArgs, elseArgs, .. } => {
2023
                    rewriteValInSlice(*thenArgs, from, to);
2024
                    rewriteValInSlice(*elseArgs, from, to);
2025
                }
2026
                case il::Instr::Switch { defaultArgs, cases, .. } => {
2027
                    rewriteValInSlice(*defaultArgs, from, to);
2028
                    for j in 0..cases.len {
2029
                        rewriteValInSlice(cases[j].args, from, to);
2030
                    }
2031
                }
2032
                else => {}
2033
            }
2034
        }
2035
    }
2036
}
2037
2038
/// Replace all occurrences of `from` with `to` in an args slice.
2039
unsafe fn rewriteValInSlice(args: *unsafe mut [il::Val], from: il::Val, to: il::Val) {
2040
    for i in 0..args.len {
2041
        if args[i] == from {
2042
            set args[i] = to;
2043
        }
2044
    }
2045
}
2046
2047
////////////////////////////
2048
// Basic Block Management //
2049
////////////////////////////
2050
2051
// Basic blocks are the fundamental unit of the CFG. Each block contains a
2052
// sequence of instructions ending in a terminator (jump, branch, return).
2053
//
2054
// The block management API supports forward references -- you can create a
2055
// block before switching to it and emitting instructions.
2056
// This is essential for control flow where we need to reference target blocks
2057
// before we've built them (e.g., the "else" block when building "then").
2058
//
2059
// Sealing is a key concept for SSA construction: a block is sealed once all
2060
// its predecessor edges are known. Before sealing, we can't resolve variable
2061
// uses that require looking up values from predecessors.
2062
2063
/// Create a new basic block with the given label base.
2064
///
2065
/// The block is initially unsealed (predecessors may be added later) and empty.
2066
/// Returns a [`BlockId`] that can be used for jumps and branches. The block must
2067
/// be switched to via [`switchToBlock`] before instructions can be emitted.
2068
unsafe fn createBlock(self: &mut FnLowerer, labelBase: *[u8]) -> BlockId throws (LowerError) {
2069
    let label = try nextLabel(self, labelBase);
2070
    let id = BlockId(self.blockData.len);
2071
    let varCount = self.localCount;
2072
    let vars = try! alloc::allocRawSlice(self.low.fnArena, @sizeOf(?il::Val), @alignOf(?il::Val), varCount) as *unsafe mut [?il::Val];
2073
2074
    for i in 0..varCount {
2075
        set vars[i] = nil;
2076
    }
2077
    self.blockData.append(BlockData {
2078
        label,
2079
        params: &mut [],
2080
        paramVars: &mut [],
2081
        instrs: &mut [],
2082
        locs: &mut [],
2083
        preds: &mut [],
2084
        vars,
2085
        sealState: Sealed::No,
2086
        loopDepth: self.loopDepth,
2087
    }, self.allocator);
2088
2089
    return id;
2090
}
2091
2092
/// Create a new block with a single parameter.
2093
unsafe fn createBlockWithParam(
2094
    self: &mut FnLowerer,
2095
    labelBase: *[u8],
2096
    param: il::Param
2097
) -> BlockId throws (LowerError) {
2098
    let block = try createBlock(self, labelBase);
2099
    let blk = getBlockMut(self, block);
2100
    blk.params.append(param, self.allocator);
2101
2102
    return block;
2103
}
2104
2105
/// Switch to building a different block.
2106
/// All subsequent `emit` calls will add instructions to this block.
2107
fn switchToBlock(self: &mut FnLowerer, block: BlockId) {
2108
    set self.currentBlock = block;
2109
}
2110
2111
/// Seal a block, indicating all predecessor edges are now known.
2112
///
2113
/// Sealing enables SSA construction to resolve variable uses by looking up
2114
/// values from predecessors and inserting block parameters as needed. It
2115
/// does not prevent instructions from being added to the block.
2116
unsafe fn sealBlock(self: &mut FnLowerer, block: BlockId) throws (LowerError) {
2117
    let blk = getBlockMut(self, block);
2118
    let case Sealed::No = blk.sealState else {
2119
        return; // Already sealed.
2120
    };
2121
    // Keep the current parameter list. Resolution can add more parameters.
2122
    let paramVars = blk.paramVars;
2123
    set blk.sealState = Sealed::Yes;
2124
2125
    // Complete each parameter that was created before sealing.
2126
    for varId, paramIdx in paramVars {
2127
        try resolveBlockArgs(self, block, Var(varId), paramIdx);
2128
    }
2129
}
2130
2131
/// Seal a block and switch to it.
2132
unsafe fn switchToAndSeal(self: &mut FnLowerer, block: BlockId) throws (LowerError) {
2133
    try sealBlock(self, block);
2134
    switchToBlock(self, block);
2135
}
2136
2137
/// Get block data by block id.
2138
unsafe fn getBlock(self: &FnLowerer, block: BlockId) -> *unsafe BlockData {
2139
    return &self.blockData[*block];
2140
}
2141
2142
/// Get mutable block data by block id.
2143
unsafe fn getBlockMut(self: &mut FnLowerer, block: BlockId) -> *unsafe mut BlockData {
2144
    return &mut self.blockData[*block];
2145
}
2146
2147
/// Get the current block being built.
2148
fn currentBlock(self: &FnLowerer) -> BlockId {
2149
    let block = self.currentBlock else {
2150
        panic "currentBlock: no current block";
2151
    };
2152
    return block;
2153
}
2154
2155
//////////////////////////
2156
// Instruction Emission //
2157
//////////////////////////
2158
2159
/// Emit an instruction to the current block.
2160
unsafe fn emit(self: &mut FnLowerer, instr: il::Instr) {
2161
    let blk = self.currentBlock else panic;
2162
    let mut block = getBlockMut(self, blk);
2163
2164
    // Track whether this function is a leaf.
2165
    if self.isLeaf {
2166
        match instr {
2167
            case il::Instr::Call { .. },
2168
                 il::Instr::Ecall { .. } => set self.isLeaf = false,
2169
            else => {},
2170
        }
2171
    }
2172
    // Record source location alongside instruction when enabled.
2173
    if self.low.options.debug {
2174
        block.locs.append(self.srcLoc, self.allocator);
2175
    }
2176
    block.instrs.append(instr, self.allocator);
2177
}
2178
2179
/// Emit an unconditional jump to `target`.
2180
unsafe fn emitJmp(self: &mut FnLowerer, target: BlockId) throws (LowerError) {
2181
    emit(self, il::Instr::Jmp { target: *target, args: &mut [] });
2182
    addPredecessor(self, target, currentBlock(self));
2183
}
2184
2185
/// Emit an unconditional jump to `target` with a single argument.
2186
unsafe fn emitJmpWithArg(self: &mut FnLowerer, target: BlockId, arg: il::Val) throws (LowerError) {
2187
    let args = try allocVal(self, arg);
2188
    emit(self, il::Instr::Jmp { target: *target, args });
2189
    addPredecessor(self, target, currentBlock(self));
2190
}
2191
2192
/// Emit an unconditional jump to `target` and switch to it.
2193
unsafe fn switchAndJumpTo(self: &mut FnLowerer, target: BlockId) throws (LowerError) {
2194
    try emitJmp(self, target);
2195
    switchToBlock(self, target);
2196
}
2197
2198
/// Emit a conditional branch based on `cond`.
2199
unsafe fn emitBr(self: &mut FnLowerer, cond: il::Reg, thenBlock: BlockId, elseBlock: BlockId) throws (LowerError) {
2200
    assert thenBlock <> elseBlock;
2201
    emit(self, il::Instr::Br {
2202
        op: il::CmpOp::Ne,
2203
        typ: il::Type::W32,
2204
        a: il::Val::Reg(cond),
2205
        b: il::Val::Imm(0),
2206
        thenTarget: *thenBlock,
2207
        thenArgs: &mut [],
2208
        elseTarget: *elseBlock,
2209
        elseArgs: &mut [],
2210
    });
2211
    addPredecessor(self, thenBlock, currentBlock(self));
2212
    addPredecessor(self, elseBlock, currentBlock(self));
2213
}
2214
2215
/// Emit a compare-and-branch instruction with the given comparison op.
2216
unsafe fn emitBrCmp(
2217
    self: &mut FnLowerer,
2218
    op: il::CmpOp,
2219
    typ: il::Type,
2220
    a: il::Val,
2221
    b: il::Val,
2222
    thenBlock: BlockId,
2223
    elseBlock: BlockId
2224
) throws (LowerError) {
2225
    assert thenBlock <> elseBlock;
2226
    emit(self, il::Instr::Br {
2227
        op, typ, a, b,
2228
        thenTarget: *thenBlock, thenArgs: &mut [],
2229
        elseTarget: *elseBlock, elseArgs: &mut [],
2230
    });
2231
    addPredecessor(self, thenBlock, currentBlock(self));
2232
    addPredecessor(self, elseBlock, currentBlock(self));
2233
}
2234
2235
/// Emit a guard that traps with `ebreak` when a comparison is false.
2236
unsafe fn emitTrapUnlessCmp(
2237
    self: &mut FnLowerer,
2238
    op: il::CmpOp,
2239
    typ: il::Type,
2240
    a: il::Val,
2241
    b: il::Val
2242
) throws (LowerError) {
2243
    let passBlock = try createBlock(self, "guard#pass");
2244
    let trapBlock = try createBlock(self, "guard#trap");
2245
2246
    try emitBrCmp(self, op, typ, a, b, passBlock, trapBlock);
2247
    try switchToAndSeal(self, trapBlock);
2248
2249
    emit(self, il::Instr::Ebreak);
2250
    emit(self, il::Instr::Unreachable);
2251
2252
    try switchToAndSeal(self, passBlock);
2253
}
2254
2255
/// Return whether two IL values are known `u32` immediates satisfying `a <= b`.
2256
fn isLtEq(a: il::Val, b: il::Val) -> bool {
2257
    if a == b {
2258
        return true;
2259
    }
2260
    if a == il::Val::Imm(0) {
2261
        return true;
2262
    }
2263
    let case il::Val::Imm(aa) = a else {
2264
        return false;
2265
    };
2266
    let case il::Val::Imm(bb) = b else {
2267
        return false;
2268
    };
2269
    if aa < 0 or bb < 0 {
2270
        return false;
2271
    }
2272
    return aa <= bb;
2273
}
2274
2275
/// Emit an `ebreak` when `a < b` holds.
2276
unsafe fn emitTrapIfLt(
2277
    self: &mut FnLowerer,
2278
    typ: il::Type,
2279
    a: il::Val,
2280
    b: il::Val
2281
) throws (LowerError) {
2282
    let trapBlock = try createBlock(self, "guard#trap");
2283
    let passBlock = try createBlock(self, "guard#pass");
2284
2285
    try emitBrCmp(self, il::CmpOp::Ult, typ, a, b, trapBlock, passBlock);
2286
    try switchToAndSeal(self, trapBlock);
2287
2288
    emit(self, il::Instr::Ebreak);
2289
    emit(self, il::Instr::Unreachable);
2290
2291
    try switchToAndSeal(self, passBlock);
2292
}
2293
2294
/// Emit a conditional branch. Uses fused compare-and-branch for simple scalar
2295
/// comparisons, falls back to separate comparison plus branch otherwise.
2296
unsafe fn emitCondBranch(
2297
    self: &mut FnLowerer,
2298
    cond: *ast::Node,
2299
    thenBlock: BlockId,
2300
    elseBlock: BlockId
2301
) throws (LowerError) {
2302
    // Try fused compare-and-branch for simple scalar comparisons.
2303
    if let case ast::NodeValue::BinOp(binop) = cond.value {
2304
        let leftTy = try typeOf(self, binop.left);
2305
        let rightTy = try typeOf(self, binop.right);
2306
        if not isAggregateType(leftTy) and not isAggregateType(rightTy) {
2307
            let operandTy = scalarComparisonType(leftTy, rightTy);
2308
            let unsigned = isUnsignedType(operandTy);
2309
            if let op = cmpOpFrom(binop.op, unsigned) {
2310
                let a = try lowerExpr(self, binop.left);
2311
                let b = try lowerExpr(self, binop.right);
2312
                let typ = ilType(self.low, operandTy);
2313
2314
                // Swap operands if needed.
2315
                match binop.op {
2316
                    case ast::BinaryOp::Gt => // `a > b` = `b < a`
2317
                        try emitBrCmp(self, op, typ, b, a, thenBlock, elseBlock),
2318
                    case ast::BinaryOp::Lte => // `a <= b` = `!(b < a)`
2319
                        try emitBrCmp(self, op, typ, b, a, elseBlock, thenBlock),
2320
                    case ast::BinaryOp::Gte => // `a >= b` = `!(a < b)`
2321
                        try emitBrCmp(self, op, typ, a, b, elseBlock, thenBlock),
2322
                    else =>
2323
                        try emitBrCmp(self, op, typ, a, b, thenBlock, elseBlock),
2324
                }
2325
                return;
2326
            }
2327
        }
2328
    }
2329
    // Fallback: evaluate condition and emit boolean branch.
2330
    let condVal = try lowerExpr(self, cond);
2331
    let condReg = emitValToReg(self, condVal);
2332
2333
    try emitBr(self, condReg, thenBlock, elseBlock);
2334
}
2335
2336
/// Emit a 32-bit store instruction at the given offset.
2337
unsafe fn emitStoreW32At(self: &mut FnLowerer, src: il::Val, dst: il::Reg, offset: i32) {
2338
    emit(self, il::Instr::Store { typ: il::Type::W32, src, dst, offset });
2339
}
2340
2341
/// Emit a 32-bit load instruction at the given offset.
2342
unsafe fn emitLoadW32At(self: &mut FnLowerer, dst: il::Reg, src: il::Reg, offset: i32) {
2343
    emit(self, il::Instr::Load { typ: il::Type::W32, dst, src, offset });
2344
}
2345
2346
/// Emit an 8-bit store instruction at the given offset.
2347
unsafe fn emitStoreW8At(self: &mut FnLowerer, src: il::Val, dst: il::Reg, offset: i32) {
2348
    emit(self, il::Instr::Store { typ: il::Type::W8, src, dst, offset });
2349
}
2350
2351
/// Emit an 8-bit load instruction at the given offset.
2352
unsafe fn emitLoadW8At(self: &mut FnLowerer, dst: il::Reg, src: il::Reg, offset: i32) {
2353
    emit(self, il::Instr::Load { typ: il::Type::W8, dst, src, offset });
2354
}
2355
2356
/// Emit a 64-bit store instruction at the given offset.
2357
unsafe fn emitStoreW64At(self: &mut FnLowerer, src: il::Val, dst: il::Reg, offset: i32) {
2358
    emit(self, il::Instr::Store { typ: il::Type::W64, src, dst, offset });
2359
}
2360
2361
/// Emit a 64-bit load instruction at the given offset.
2362
unsafe fn emitLoadW64At(self: &mut FnLowerer, dst: il::Reg, src: il::Reg, offset: i32) {
2363
    emit(self, il::Instr::Load { typ: il::Type::W64, dst, src, offset });
2364
}
2365
2366
/// Load a tag from memory at `src` plus `offset` with the given IL type.
2367
unsafe fn loadTag(self: &mut FnLowerer, src: il::Reg, offset: i32, tagType: il::Type) -> il::Val {
2368
    let dst = nextReg(self);
2369
    emit(self, il::Instr::Load { typ: tagType, dst, src, offset });
2370
    return il::Val::Reg(dst);
2371
}
2372
2373
/// Load the data pointer from a slice value.
2374
unsafe fn loadSlicePtr(self: &mut FnLowerer, sliceReg: il::Reg) -> il::Reg {
2375
    let ptrReg = nextReg(self);
2376
    emitLoadW64At(self, ptrReg, sliceReg, SLICE_PTR_OFFSET);
2377
    return ptrReg;
2378
}
2379
2380
/// Load the length from a slice value.
2381
unsafe fn loadSliceLen(self: &mut FnLowerer, sliceReg: il::Reg) -> il::Val {
2382
    let lenReg = nextReg(self);
2383
    emitLoadW32At(self, lenReg, sliceReg, SLICE_LEN_OFFSET);
2384
    return il::Val::Reg(lenReg);
2385
}
2386
2387
/// Load the capacity from a slice value.
2388
unsafe fn loadSliceCap(self: &mut FnLowerer, sliceReg: il::Reg) -> il::Val {
2389
    let capReg = nextReg(self);
2390
    emitLoadW32At(self, capReg, sliceReg, SLICE_CAP_OFFSET);
2391
    return il::Val::Reg(capReg);
2392
}
2393
2394
/// Emit a load instruction for a scalar value at `src` plus `offset`.
2395
/// For reading values that may be aggregates, use `emitRead` instead.
2396
unsafe fn emitLoad(self: &mut FnLowerer, src: il::Reg, offset: i32, typ: resolver::Type) -> il::Val {
2397
    let dst = nextReg(self);
2398
    let ilTyp = ilType(self.low, typ);
2399
2400
    if isSignedType(typ) {
2401
        emit(self, il::Instr::Sload { typ: ilTyp, dst, src, offset });
2402
    } else {
2403
        emit(self, il::Instr::Load { typ: ilTyp, dst, src, offset });
2404
    }
2405
    return il::Val::Reg(dst);
2406
}
2407
2408
/// Read a value from memory at `src` plus `offset`. Aggregates are represented
2409
/// as pointers, so we return the address directly. Scalars are loaded via [`emitLoad`].
2410
unsafe fn emitRead(self: &mut FnLowerer, src: il::Reg, offset: i32, typ: resolver::Type) -> il::Val {
2411
    if isAggregateType(typ) {
2412
        let ptr = emitPtrOffset(self, src, offset);
2413
        return il::Val::Reg(ptr);
2414
    }
2415
    return emitLoad(self, src, offset, typ);
2416
}
2417
2418
/// Emit a copy instruction that loads a data symbol's address into a register.
2419
unsafe fn emitDataAddr(self: &mut FnLowerer, sym: *unsafe resolver::Symbol) -> il::Reg {
2420
    let dst = nextReg(self);
2421
    let modId = resolver::moduleIdForSymbol(self.low.resolver, sym);
2422
    let qualName = qualifyName(self.low, modId, sym.name);
2423
2424
    emit(self, il::Instr::Copy { dst, val: il::Val::DataSym(qualName) });
2425
2426
    return dst;
2427
}
2428
2429
/// Emit a copy instruction that loads a function's address into a register.
2430
unsafe fn emitFnAddr(self: &mut FnLowerer, sym: *unsafe resolver::Symbol) -> il::Reg {
2431
    let dst = nextReg(self);
2432
    let modId = resolver::moduleIdForSymbol(self.low.resolver, sym);
2433
    let qualName = qualifyName(self.low, modId, sym.name);
2434
2435
    emit(self, il::Instr::Copy { dst, val: il::Val::FnAddr(qualName) });
2436
2437
    return dst;
2438
}
2439
2440
/// Emit pattern tests for a single pattern.
2441
unsafe fn emitPatternMatch(
2442
    self: &mut FnLowerer,
2443
    subject: &MatchSubject,
2444
    pattern: *ast::Node,
2445
    matchBlock: BlockId,
2446
    fallthrough: BlockId
2447
) throws (LowerError) {
2448
    // Wildcards always match; array patterns are tested element-by-element
2449
    // during binding, so they also unconditionally enter the match block.
2450
    if isWildcardPattern(pattern) {
2451
        try emitJmp(self, matchBlock);
2452
        return;
2453
    }
2454
    if let case ast::NodeValue::ArrayLit(_) = pattern.value {
2455
        try emitJmp(self, matchBlock);
2456
        return;
2457
    }
2458
    if let case resolver::Type::Nominal(resolver::NominalType::Record(_)) = subject.type {
2459
        if let case ast::NodeValue::RecordLit(_) = pattern.value {
2460
            try emitJmp(self, matchBlock);
2461
            return;
2462
        }
2463
    }
2464
    let isNil = pattern.value == ast::NodeValue::Nil;
2465
2466
    match subject.kind {
2467
        case MatchSubjectKind::OptionalPtr if isNil => {
2468
            // Null pointer optimization: branch on the data pointer being null.
2469
            let nilReg = try optionalNilReg(self, subject.val, subject.type);
2470
            try emitBrCmp(self, il::CmpOp::Eq, il::Type::W64, il::Val::Reg(nilReg), il::Val::Imm(0), matchBlock, fallthrough);
2471
        }
2472
        case MatchSubjectKind::OptionalAggregate => {
2473
            let base = emitValToReg(self, subject.val);
2474
2475
            if isNil { // Optional aggregate: `nil` means tag is zero.
2476
                let tagReg = tvalTagReg(self, base);
2477
                try emitBr(self, tagReg, fallthrough, matchBlock);
2478
            } else {
2479
                // `lowerExpr` applies the resolver's optional-lift coercion,
2480
                // materializing the tagged representation for value patterns.
2481
                let pattVal = try lowerExpr(self, pattern);
2482
                let pattReg = emitValToReg(self, pattVal);
2483
                let eq = try lowerOptionalEq(self, subject.bindType, base, pattReg, 0);
2484
                let eqReg = emitValToReg(self, eq);
2485
2486
                try emitBr(self, eqReg, matchBlock, fallthrough);
2487
            }
2488
        }
2489
        case MatchSubjectKind::Union(unionInfo) => {
2490
            assert not isNil;
2491
2492
            let case resolver::NodeExtra::UnionVariant { tag: variantTag, .. } =
2493
                resolver::nodeData(self.low.resolver, pattern).extra
2494
            else {
2495
                throw LowerError::ExpectedVariant;
2496
            };
2497
            // Void unions are passed by value (the tag itself).
2498
            // Non-void unions are passed by reference (need to load tag).
2499
            // When matching by reference, always load from the pointer.
2500
            if unionInfo.isAllVoid {
2501
                let mut tagVal = subject.val;
2502
                match subject.by {
2503
                    case resolver::MatchBy::Ref, resolver::MatchBy::MutRef => {
2504
                        let base = emitValToReg(self, subject.val);
2505
                        set tagVal = loadTag(self, base, 0, il::Type::W8);
2506
                    }
2507
                    case resolver::MatchBy::Value => {}
2508
                }
2509
                try emitBrCmp(self, il::CmpOp::Eq, il::Type::W8, tagVal, il::Val::Imm(variantTag as i64), matchBlock, fallthrough);
2510
            } else {
2511
                let base = emitValToReg(self, subject.val);
2512
                let tagReg = tvalTagReg(self, base);
2513
2514
                try emitBrCmp(self, il::CmpOp::Eq, il::Type::W8, il::Val::Reg(tagReg), il::Val::Imm(variantTag as i64), matchBlock, fallthrough);
2515
            }
2516
        }
2517
        else => { // Value comparison.
2518
            assert not isNil;
2519
            let pattVal = try lowerExpr(self, pattern);
2520
            if isAggregateType(subject.type) {
2521
                // Aggregate types need structural comparison rather than
2522
                // scalar compare.
2523
                let subjectReg = emitValToReg(self, subject.val);
2524
                let pattReg = emitValToReg(self, pattVal);
2525
                let eq = try lowerAggregateEq(self, subject.type, subjectReg, pattReg, 0);
2526
                let eqReg = emitValToReg(self, eq);
2527
2528
                try emitBr(self, eqReg, matchBlock, fallthrough);
2529
            } else {
2530
                try emitBrCmp(self, il::CmpOp::Eq, subject.ilType, subject.val, pattVal, matchBlock, fallthrough);
2531
            }
2532
        }
2533
    }
2534
}
2535
2536
/// Emit branches for multiple patterns. The first pattern that matches
2537
/// causes a jump to the match block. If no patterns match, we jump to the
2538
/// fallthrough block.
2539
unsafe fn emitPatternMatches(
2540
    self: &mut FnLowerer,
2541
    subject: &MatchSubject,
2542
    patterns: &[*ast::Node],
2543
    matchBlock: BlockId,
2544
    fallthrough: BlockId
2545
) throws (LowerError) {
2546
    assert patterns.len > 0;
2547
2548
    for i in 0..(patterns.len - 1) {
2549
        let pattern = patterns[i];
2550
        let nextArm = try createBlock(self, "arm");
2551
        try emitPatternMatch(self, subject, pattern, matchBlock, nextArm);
2552
2553
        // Seal the intermediate arm block: all predecessor edges are known
2554
        // This ensures SSA construction can resolve variable uses through
2555
        // single-predecessor optimization instead of creating unresolved block
2556
        // parameters.
2557
        try switchToAndSeal(self, nextArm);
2558
    }
2559
    // Handle last pattern: go to fallthrough block on failure.
2560
    let last = patterns[patterns.len - 1];
2561
    try emitPatternMatch(self, subject, last, matchBlock, fallthrough);
2562
}
2563
2564
/// Emit a match binding pattern.
2565
/// Binding patterns always match for regular values, but for optionals they
2566
/// check for the presence of a value. Jumps to `valuePresent` on success,
2567
/// `valueAbsent` on failure.
2568
unsafe fn emitBindingTest(
2569
    self: &mut FnLowerer,
2570
    subject: &MatchSubject,
2571
    valuePresent: BlockId,
2572
    valueAbsent: BlockId
2573
) throws (LowerError) {
2574
    match subject.kind {
2575
        case MatchSubjectKind::OptionalPtr, MatchSubjectKind::OptionalAggregate => {
2576
            let nilReg = try optionalNilReg(self, subject.val, subject.type);
2577
            try emitBr(self, nilReg, valuePresent, valueAbsent);
2578
        }
2579
        else => {
2580
            // Regular values always match binding patterns unconditionally.
2581
            try emitJmp(self, valuePresent);
2582
        }
2583
    }
2584
}
2585
2586
/// Emit a jump to target if the current block hasn't terminated, then seal the target block.
2587
unsafe fn emitJmpAndSeal(self: &mut FnLowerer, target: BlockId) throws (LowerError) {
2588
    if not blockHasTerminator(self) {
2589
        try emitJmp(self, target);
2590
    }
2591
    try sealBlock(self, target);
2592
}
2593
2594
/// Check if the current block already has a terminator instruction.
2595
unsafe fn blockHasTerminator(self: &FnLowerer) -> bool {
2596
    let blk = getBlock(self, currentBlock(self));
2597
    if blk.instrs.len == 0 {
2598
        return false;
2599
    }
2600
    match blk.instrs[blk.instrs.len - 1] {
2601
        case il::Instr::Ret { .. },
2602
             il::Instr::Jmp { .. },
2603
             il::Instr::Br { .. },
2604
             il::Instr::Switch { .. },
2605
             il::Instr::Unreachable =>
2606
            return true,
2607
        else =>
2608
            return false,
2609
    }
2610
}
2611
2612
/// Emit a jump to merge block if the current block hasn't terminated.
2613
///
2614
/// This is used after lowering branches of an if-else, for example. If the
2615
/// branch diverges, the block already has a terminator and no jump is needed.
2616
///
2617
/// This handles cases like:
2618
///
2619
///     if cond {
2620
///         return 1;   // @then diverges, no jump to merge.
2621
///     } else {
2622
///         return 0;   // @else diverges, no jump to merge.
2623
///     }
2624
///
2625
/// In the above example, the merge block stays `nil`, and no code is generated
2626
/// after the `if`. The merge block is created on first use.
2627
unsafe fn emitMergeIfUnterminated(self: &mut FnLowerer, mergeBlock: &mut ?BlockId) throws (LowerError) {
2628
    if not blockHasTerminator(self) {
2629
        if *mergeBlock == nil {
2630
            set *mergeBlock = try createBlock(self, "merge");
2631
        }
2632
        let target = *mergeBlock else { throw LowerError::MissingTarget; };
2633
        try emitJmp(self, target);
2634
    }
2635
}
2636
2637
//////////////////////////////////
2638
// Control Flow Edge Management //
2639
//////////////////////////////////
2640
2641
/// Add a predecessor edge from `pred` to `target`.
2642
/// Must be called before the target block is sealed. Duplicates are ignored.
2643
unsafe fn addPredecessor(self: &mut FnLowerer, target: BlockId, pred: BlockId) {
2644
    let blk = getBlockMut(self, target);
2645
    assert blk.sealState <> Sealed::Yes, "addPredecessor: adding predecessor to sealed block";
2646
    let preds = &mut blk.preds;
2647
    for i in 0..preds.len {
2648
        if preds[i] == *pred { // Avoid duplicate predecessor entries.
2649
            return;
2650
        }
2651
    }
2652
    preds.append(*pred, self.allocator);
2653
}
2654
2655
/// Finalize all blocks and return the block array.
2656
unsafe fn finalizeBlocks(self: &mut FnLowerer) -> *unsafe [il::Block] throws (LowerError) {
2657
    let blockCount = self.blockData.len;
2658
    let blocks = try! alloc::allocRawSlice(
2659
        self.low.fnArena, @sizeOf(il::Block), @alignOf(il::Block), blockCount
2660
    ) as *unsafe mut [il::Block];
2661
2662
    for i in 0..self.blockData.len {
2663
        let data = &self.blockData[i];
2664
2665
        set blocks[i] = il::Block {
2666
            label: data.label,
2667
            params: &data.params[..],
2668
            instrs: data.instrs,
2669
            locs: &data.locs[..],
2670
            preds: &data.preds[..],
2671
            loopDepth: data.loopDepth,
2672
        };
2673
    }
2674
    return &blocks[..self.blockData.len];
2675
}
2676
2677
/////////////////////
2678
// Loop Management //
2679
/////////////////////
2680
2681
/// Enter a loop context for break/continue handling.
2682
/// `continueBlock` is `nil` when the continue target is created lazily.
2683
unsafe fn enterLoop(self: &mut FnLowerer, breakBlock: BlockId, continueBlock: ?BlockId) {
2684
    assert self.loopDepth < self.loopStack.len, "enterLoop: loop depth overflow";
2685
    let slot = &mut self.loopStack[self.loopDepth];
2686
2687
    set slot.breakTarget = breakBlock;
2688
    set slot.continueTarget = continueBlock;
2689
    set self.loopDepth += 1;
2690
}
2691
2692
/// Exit the current loop context.
2693
fn exitLoop(self: &mut FnLowerer) {
2694
    assert self.loopDepth <> 0, "exitLoop: loopDepth is zero";
2695
    set self.loopDepth -= 1;
2696
}
2697
2698
/// Get the current loop context.
2699
unsafe fn currentLoop(self: &mut FnLowerer) -> ?*unsafe mut LoopCtx {
2700
    if self.loopDepth == 0 {
2701
        return nil;
2702
    }
2703
    return &mut self.loopStack[self.loopDepth - 1];
2704
}
2705
2706
/// Get or lazily create the continue target block for the current loop.
2707
unsafe fn getOrCreateContinueBlock(self: &mut FnLowerer) -> BlockId throws (LowerError) {
2708
    let ctx = currentLoop(self) else {
2709
        throw LowerError::OutsideOfLoop;
2710
    };
2711
    if let block = ctx.continueTarget {
2712
        return block;
2713
    }
2714
    let block = try createBlock(self, "step");
2715
    set ctx.continueTarget = block;
2716
    return block;
2717
}
2718
2719
/// Allocate a slice of values in the lowering arena.
2720
unsafe fn allocVals(self: &mut FnLowerer, len: u32) -> *unsafe mut [il::Val] throws (LowerError) {
2721
    return try! alloc::allocRawSlice(self.low.fnArena, @sizeOf(il::Val), @alignOf(il::Val), len) as *unsafe mut [il::Val];
2722
}
2723
2724
/// Allocate a single-value slice in the lowering arena.
2725
unsafe fn allocVal(self: &mut FnLowerer, val: il::Val) -> *unsafe mut [il::Val] throws (LowerError) {
2726
    let args = try allocVals(self, 1);
2727
    set args[0] = val;
2728
    return args;
2729
}
2730
2731
////////////////////////
2732
// SSA Var Management //
2733
////////////////////////
2734
2735
// This section implements SSA construction following "Simple and Efficient
2736
// Construction of Static Single Assignment Form" (Braun et al., 2013). The IL
2737
// uses block parameters (equivalent to phi nodes) that receive values via
2738
// terminator arguments. Block args are resolved eagerly at seal time via
2739
// [`resolveBlockArgs`], matching Braun's on-the-fly approach.
2740
//
2741
// In SSA form, each variable definition creates a unique value. When control
2742
// flow diverges and merges (like after an if-else), a variable might have
2743
// different definitions from different paths.
2744
//
2745
// # What "Value" means
2746
//
2747
// An [`il::Val`] is a compile-time representation of *where* a runtime value
2748
// lives, not the runtime value itself. Values can live in registers, as symbol
2749
// references, or as immediate values, ie. static constants.
2750
//
2751
// When we "find the value" of a variable, we're answering: "Which SSA register
2752
// (or constant) represents this variable at this program point?"
2753
//
2754
// Each source-level variable gets a `Var` handle on declaration. When a
2755
// variable is defined via [`defVar`], its SSA value is recorded in the current
2756
// block's variable mapping. When a variable is used with [`useVar`] or
2757
// [`useVarInBlock`], we either return the local definition or recursively look
2758
// up the value from predecessor blocks. When multiple predecessors define
2759
// different values for a given variable, we insert a block parameter
2760
// (equivalent to a phi node).
2761
//
2762
// The algorithm used by [`useVarInBlock`] handles three cases:
2763
//
2764
// 1. **Local definition exists**: If the variable was assigned in this block,
2765
//    return that value immediately (fast path).
2766
//
2767
// 2. **Sealed block with single predecessor**: If all incoming edges are known
2768
//    and there's exactly one predecessor, recurse to that predecessor. No merge
2769
//    is needed since there's only one path. The result is cached.
2770
//
2771
// 3. **Unsealed block or multiple predecessors**: Create a block parameter to
2772
//    receive the merged value. If sealed, look up each predecessor's value and
2773
//    patch its terminator via [`resolveBlockArgs`]. If unsealed, `paramVars`
2774
//    records the variable in parameter order. [`sealBlock`] resolves these
2775
//    parameters after all incoming edges are known.
2776
//
2777
// Consider this code:
2778
//
2779
//     let mut x = 1;
2780
//     if cond {
2781
//         x = 2;
2782
//     } else {
2783
//         x = f();   // Result in register %r.
2784
//     }
2785
//     print(x);      // Which value?
2786
//
2787
// The Control Flow Graph (CFG) looks like:
2788
//
2789
//         [entry]
2790
//           _|_
2791
//          /   \
2792
//     [then]   [else]
2793
//     x = 2    x = %r
2794
//         \    /
2795
//        [merge]
2796
//         use(x)
2797
//
2798
// At the `print(x)` point, the compiler doesn't know which branch ran (that's
2799
// a runtime decision), but it needs to emit code that works for either case.
2800
// This is where [`useVarInBlock`] is called.
2801
//
2802
// The generated IL looks like this:
2803
//
2804
//     @then
2805
//       jmp @merge(2);           // pass immediate `2`
2806
//     @else
2807
//       jmp @merge(%r);          // pass register `%r`
2808
//     @merge(w32 %m)             // `%m` receives whichever value arrives at runtime
2809
//       call w32 $print(%m);     // `print` is called with runtime value in `%m`
2810
//
2811
// A block is "sealed" when all predecessor edges are known. This is crucial
2812
// because until sealed, we can't know how many paths merge into the block,
2813
// and thus can't create the right number of block parameter arguments.
2814
//
2815
// If a block isn't sealed but we need a variable's value, we still create
2816
// a block parameter, but defer filling in the terminator arguments. When the
2817
// block is later sealed via [`sealBlock`], all incomplete block params are resolved.
2818
2819
/// Declare a new source-level variable and define its initial value.
2820
/// If called before any block exists (e.g., for parameters), the definition is skipped.
2821
unsafe fn newVar(
2822
    self: &mut FnLowerer,
2823
    name: ?*[u8],
2824
    type: il::Type,
2825
    mutable: bool,
2826
    val: il::Val
2827
) -> Var {
2828
    let id = self.vars.len;
2829
    self.vars.append(VarData { name, type, mutable, addressTaken: false }, self.allocator);
2830
2831
    let v = Var(id);
2832
    if self.currentBlock <> nil {
2833
        defVar(self, v, val);
2834
    }
2835
    return v;
2836
}
2837
2838
/// Define (write) a variable. Record the SSA value of a variable in the
2839
/// current block. Called when a variable is assigned or initialized (`let`
2840
/// bindings, assignments, loop updates). When [`useVar`] is later called,
2841
/// it will retrieve this value.
2842
unsafe fn defVar(self: &mut FnLowerer, v: Var, val: il::Val) {
2843
    assert *v < self.vars.len;
2844
    set getBlockMut(self, currentBlock(self)).vars[*v] = val;
2845
}
2846
2847
/// Use (read) the current value of a variable in the current block.
2848
/// May insert block parameters if the value must come from predecessors.
2849
unsafe fn useVar(self: &mut FnLowerer, v: Var) -> il::Val throws (LowerError) {
2850
    return try useVarInBlock(self, currentBlock(self), v);
2851
}
2852
2853
/// Resolve which SSA definition of a variable reaches a use point in a given block.
2854
///
2855
/// Given a variable and a block where it's used, this function finds the
2856
/// correct [`il::Val`] that holds the variable's value at that program point.
2857
/// When control flow merges from multiple predecessors with different
2858
/// definitions, it creates a block parameter to unify them.
2859
unsafe fn useVarInBlock(self: &mut FnLowerer, block: BlockId, v: Var) -> il::Val throws (LowerError) {
2860
    assert *v < self.vars.len;
2861
2862
    let blk = getBlockMut(self, block);
2863
    if let val = blk.vars[*v] {
2864
        return val;
2865
    }
2866
    // Entry block cannot have block parameters. If variable isn't defined
2867
    // in entry, we return undefined.
2868
    if block == self.entryBlock {
2869
        return il::Val::Undef;
2870
    }
2871
    if blk.sealState == Sealed::Yes {
2872
        if blk.preds.len == 0 {
2873
            // Variable used in sealed block with no predecessors.
2874
            throw LowerError::InvalidUse;
2875
        }
2876
        // Single predecessor means no merge needed, variable is implicitly
2877
        // available without a block parameter.
2878
        if blk.preds.len == 1 {
2879
            let pred = BlockId(blk.preds[0]);
2880
            if *pred <> *block {
2881
                let val = try useVarInBlock(self, pred, v);
2882
                set blk.vars[*v] = val; // Cache.
2883
                return val;
2884
            }
2885
        }
2886
    }
2887
    // Multiple predecessors or unsealed block: need a block parameter to merge
2888
    // the control flow paths.
2889
    return try createBlockParam(self, block, v);
2890
}
2891
2892
/// Look up a variable by name in the current scope.
2893
/// Searches from most recently declared to first, enabling shadowing.
2894
unsafe fn lookupVarByName(self: &FnLowerer, name: *[u8]) -> ?Var {
2895
    let mut id = self.vars.len;
2896
    while id > 0 {
2897
        set id -= 1;
2898
        if let varName = self.vars[id].name {
2899
            // Names are interned strings, so pointer comparison suffices.
2900
            if varName == name {
2901
                return Var(id);
2902
            }
2903
        }
2904
    }
2905
    return nil;
2906
}
2907
2908
/// Look up a local variable bound to an identifier node.
2909
unsafe fn lookupLocalVar(self: &FnLowerer, node: *ast::Node) -> ?Var {
2910
    let case ast::NodeValue::Ident(name) = node.value else {
2911
        return nil;
2912
    };
2913
    return lookupVarByName(self, name);
2914
}
2915
2916
/// Save current lexical variable scope depth.
2917
unsafe fn enterVarScope(self: &FnLowerer) -> u32 {
2918
    return self.vars.len;
2919
}
2920
2921
/// Restore lexical variable scope depth.
2922
unsafe fn exitVarScope(self: &mut FnLowerer, savedVarsLen: u32) {
2923
    set self.vars = @sliceOf(self.vars.ptr, savedVarsLen, self.vars.cap);
2924
}
2925
2926
/// Get the metadata for a variable.
2927
unsafe fn getVar(self: &FnLowerer, v: Var) -> *unsafe VarData {
2928
    assert *v < self.vars.len;
2929
    return &self.vars[*v];
2930
}
2931
2932
/// Create a block parameter to merge a variable's value from multiple
2933
/// control flow paths.
2934
///
2935
/// Called when [`useVarInBlock`] cannot find a local definition and the block is
2936
/// unsealed or has multiple predecessors. For example, `x` can be used in `@end`
2937
/// but defined differently in `@then` and `@else`:
2938
///
2939
///     @then
2940
///       jmp @end(1);            // x = 1
2941
///     @else
2942
///       jmp @end(2);            // x = 2
2943
///     @end(w32 %1)              // x = %1, merged from predecessors
2944
///       ret %1;
2945
///
2946
/// Create a register `%1` as a block parameter. In a sealed block, patch each
2947
/// predecessor's jump to pass its value of `x`. Otherwise, defer until sealing.
2948
unsafe fn createBlockParam(self: &mut FnLowerer, block: BlockId, v: Var) -> il::Val throws (LowerError) {
2949
    // Entry block must not have block parameters.
2950
    assert block <> self.entryBlock, "createBlockParam: entry block must not have block parameters";
2951
    // Allocate a register to hold the merged value.
2952
    let reg = nextReg(self);
2953
    let type = getVar(self, v).type;
2954
2955
    // Create block parameter and add it to the block.
2956
    let param = il::Param { value: reg, type };
2957
    let blk = getBlockMut(self, block);
2958
    let paramIdx = blk.paramVars.len;
2959
    blk.params.append(param, self.allocator);
2960
    blk.paramVars.append(*v, self.allocator); // Associate variable with parameter.
2961
2962
    // Record that this variable's value in this block is now the parameter register.
2963
    // This must happen before the predecessor loop to handle self-referential loops.
2964
    set blk.vars[*v] = il::Val::Reg(reg);
2965
2966
    if blk.sealState == Sealed::Yes {
2967
        // Block sealed: check for trivial phi before committing. If all
2968
        // predecessors provide the same value, we can remove the param we
2969
        // just created and use that value directly.
2970
        if let trivial = try getTrivialPhiVal(self, block, v) {
2971
            let provisional = il::Val::Reg(reg);
2972
            removeLastBlockParam(self, block);
2973
            rewriteCachedVarValue(self, v, provisional, trivial);
2974
            set getBlockMut(self, block).vars[*v] = trivial;
2975
            return trivial;
2976
        }
2977
        // Non-trivial phi: patch predecessors to pass their values.
2978
        try resolveBlockArgs(self, block, v, paramIdx);
2979
    }
2980
    return il::Val::Reg(reg);
2981
}
2982
2983
/// Complete the block parameter at `paramIdx`. Look up the variable's value in
2984
/// each predecessor and patch its terminator with the edge argument.
2985
///
2986
/// This is the block-parameter equivalent of adding operands to a phi-function in
2987
/// traditional SSA. Where a phi-function merges values at the join point:
2988
///
2989
///     x3 = phi(x1, x2)
2990
///
2991
/// This representation avoids the need for phi nodes to reference their
2992
/// predecessor blocks explicitly, since the control flow edges already encode
2993
/// that information.
2994
unsafe fn resolveBlockArgs(self: &mut FnLowerer, block: BlockId, v: Var, paramIdx: u32) throws (LowerError) {
2995
    let blk = getBlock(self, block);
2996
2997
    // For each predecessor, recursively look up the variable's reaching definition
2998
    // in that block, then patch the predecessor's terminator to pass that value
2999
    // as an argument to this block's parameter.
3000
    for predId in blk.preds {
3001
        let pred = BlockId(predId);
3002
        // This may recursively trigger more block arg resolution if the
3003
        // predecessor also needs to look up the variable from its predecessors.
3004
        let val = try useVarInBlock(self, pred, v);
3005
        assert val <> il::Val::Undef, "createBlockParam: predecessor provides undef value for block parameter";
3006
        patchTerminatorArg(self, pred, *block, paramIdx, val);
3007
    }
3008
}
3009
3010
/// Check if a block parameter is trivial, i.e. all predecessors provide
3011
/// the same value. Returns the trivial value if so.
3012
unsafe fn getTrivialPhiVal(self: &mut FnLowerer, block: BlockId, v: Var) -> ?il::Val throws (LowerError) {
3013
    let blk = getBlock(self, block);
3014
    // Get the block parameter register.
3015
    let paramReg = blk.vars[*v];
3016
    // Check if all predecessors provide the same value.
3017
    let mut sameVal: ?il::Val = nil;
3018
3019
    for predId in blk.preds {
3020
        let pred = BlockId(predId);
3021
        let val = try useVarInBlock(self, pred, v);
3022
3023
        // Check if this is a self-reference.
3024
        // This happens in cycles where the loop back-edge passes the phi to
3025
        // itself. We skip self-references when checking for trivial phis.
3026
        if let reg = paramReg {
3027
            if val == reg {
3028
                // Self-reference, skip this predecessor.
3029
            } else if let sv = sameVal {
3030
                if val <> sv {
3031
                    // Multiple different values, not trivial.
3032
                    return nil;
3033
                }
3034
            } else {
3035
                set sameVal = val;
3036
            }
3037
        } else { // No param reg set yet, can't be trivial.
3038
            return nil;
3039
        }
3040
    }
3041
    return sameVal;
3042
}
3043
3044
/// Patch a single terminator argument for a specific edge. This is used during
3045
/// SSA construction to pass variable values along control flow edges.
3046
unsafe fn patchTerminatorArg(
3047
    self: &mut FnLowerer,
3048
    from: BlockId,         // The predecessor block containing the terminator to patch.
3049
    target: u32,           // The index of the target block we're passing the value to.
3050
    paramIdx: u32,         // The index of the block parameter to set.
3051
    val: il::Val           // The value to pass as the argument.
3052
) {
3053
    let data = getBlockMut(self, from);
3054
    let ix = data.instrs.len - 1; // The terminator is always the last instruction.
3055
3056
    // TODO: We shouldn't need to use a mutable subscript here, given that the
3057
    // fields are already mutable.
3058
    match &mut data.instrs[ix] {
3059
        case il::Instr::Jmp { args, .. } => {
3060
            set *args = growArgs(self, *args, paramIdx + 1);
3061
            set args[paramIdx] = val;
3062
        }
3063
        case il::Instr::Br { thenTarget, thenArgs, elseTarget, elseArgs, .. } => {
3064
            // Nb. both branches could target the same block (e.g. `if cond { x } else { x }`).
3065
            if *thenTarget == target {
3066
                set *thenArgs = growArgs(self, *thenArgs, paramIdx + 1);
3067
                set thenArgs[paramIdx] = val;
3068
            }
3069
            if *elseTarget == target {
3070
                set *elseArgs = growArgs(self, *elseArgs, paramIdx + 1);
3071
                set elseArgs[paramIdx] = val;
3072
            }
3073
        }
3074
        case il::Instr::Switch { defaultTarget, defaultArgs, cases, .. } => {
3075
            if *defaultTarget == target {
3076
                set *defaultArgs = growArgs(self, *defaultArgs, paramIdx + 1);
3077
                set defaultArgs[paramIdx] = val;
3078
            }
3079
            let idx = paramIdx + 1;
3080
            for ci in 0..cases.len {
3081
                if cases[ci].target == target {
3082
                    set cases[ci].args = growArgs(self, cases[ci].args, idx);
3083
                    set cases[ci].args[paramIdx] = val;
3084
                }
3085
            }
3086
        }
3087
        else => {
3088
            // Other terminators (e.g. `Ret`, `Unreachable`) don't have successor blocks.
3089
        }
3090
    }
3091
}
3092
3093
/// Grow an args array to hold at least the given capacity.
3094
unsafe fn growArgs(self: &mut FnLowerer, args: *unsafe mut [il::Val], capacity: u32) -> *unsafe mut [il::Val] {
3095
    if args.len >= capacity {
3096
        return args;
3097
    }
3098
    let newArgs = try! alloc::allocRawSlice(
3099
        self.low.fnArena, @sizeOf(il::Val), @alignOf(il::Val), capacity
3100
    ) as *unsafe mut [il::Val];
3101
3102
    for arg, i in args {
3103
        set newArgs[i] = arg;
3104
    }
3105
    for i in args.len..capacity {
3106
        set newArgs[i] = il::Val::Undef;
3107
    }
3108
    return newArgs;
3109
}
3110
3111
/// Extract the parameter name from an [`FnParam`] AST node value.
3112
fn paramName(value: *ast::NodeValue) -> *[u8] throws (LowerError) {
3113
    let case ast::NodeValue::FnParam(param) = *value else {
3114
        throw LowerError::ExpectedFunctionParam;
3115
    };
3116
    let case ast::NodeValue::Ident(name) = param.name.value else {
3117
        throw LowerError::ExpectedIdentifier;
3118
    };
3119
    return name;
3120
}
3121
3122
/// Lower function parameters. Declares variables for each parameter.
3123
/// When a receiver name is passed, we're handling a trait method.
3124
unsafe fn lowerParams(
3125
    self: &mut FnLowerer,
3126
    fnType: resolver::FnType,
3127
    astParams: *[*ast::Node],
3128
    receiverName: ?*ast::Node
3129
) -> *unsafe [il::Param] throws (LowerError) {
3130
    let offset: u32 = 1 if self.returnReg <> nil else 0;
3131
    let totalLen = fnType.paramTypes.len as u32 + offset;
3132
    if totalLen == 0 {
3133
        return &[];
3134
    }
3135
    assert fnType.paramTypes.len as u32 <= resolver::MAX_FN_PARAMS;
3136
3137
    let params = try! alloc::allocRawSlice(
3138
        self.low.fnArena, @sizeOf(il::Param), @alignOf(il::Param), totalLen
3139
    ) as *unsafe mut [il::Param];
3140
3141
    if let reg = self.returnReg {
3142
        set params[0] = il::Param { value: reg, type: il::Type::W64 };
3143
    }
3144
    for i in 0..fnType.paramTypes.len as u32 {
3145
        let type = ilType(self.low, *fnType.paramTypes[i]);
3146
        let reg = nextReg(self);
3147
3148
        set params[i + offset] = il::Param { value: reg, type };
3149
3150
        // Declare the parameter variable. For the receiver, the name comes
3151
        // from the receiver node.
3152
        // For all other parameters, the name comes from the AST params.
3153
        let mut name: *[u8] = undefined;
3154
        if let recNode = receiverName {
3155
            if i == 0 {
3156
                let case ast::NodeValue::Ident(recName) = recNode.value else {
3157
                    throw LowerError::ExpectedIdentifier;
3158
                };
3159
                set name = recName;
3160
            } else {
3161
                set name = try paramName(&astParams[i - 1].value);
3162
            }
3163
        } else {
3164
            set name = try paramName(&astParams[i].value);
3165
        }
3166
        let v = newVar(self, name, type, false, il::Val::Undef);
3167
3168
        self.params.append(FnParamBinding { var: v, reg }, self.allocator);
3169
    }
3170
    return params;
3171
}
3172
3173
/// Resolve match subject.
3174
unsafe fn lowerMatchSubject(self: &mut FnLowerer, subject: *ast::Node) -> MatchSubject throws (LowerError) {
3175
    let mut val = try lowerExpr(self, subject);
3176
    let subjectType = try typeOf(self, subject);
3177
    let unwrapped = resolver::unwrapMatchSubject(subjectType);
3178
3179
    // When matching an aggregate by value, copy it to a fresh stack slot so
3180
    // that bindings are independent of the original memory.  Without this,
3181
    // the lowerer returns a pointer into the source and mutations to the
3182
    // source silently corrupt the bound variables.
3183
    if unwrapped.by == resolver::MatchBy::Value and isAggregateType(unwrapped.effectiveTy) {
3184
        set val = try emitStackVal(self, unwrapped.effectiveTy, val);
3185
    }
3186
3187
    let mut bindType = unwrapped.effectiveTy;
3188
    if let case resolver::Type::Optional(inner) = unwrapped.effectiveTy {
3189
        set bindType = *inner;
3190
    }
3191
    let ilType = ilType(self.low, unwrapped.effectiveTy);
3192
    let kind = matchSubjectKind(unwrapped.effectiveTy);
3193
3194
    return MatchSubject { val, type: unwrapped.effectiveTy, ilType, bindType, kind, by: unwrapped.by };
3195
}
3196
3197
/// Check whether a case pattern is an unconditional wildcard.
3198
fn isWildcardPattern(pattern: *ast::Node) -> bool {
3199
    match pattern.value {
3200
        case ast::NodeValue::Placeholder => return true,
3201
        else => return false,
3202
    }
3203
}
3204
3205
/// Check whether an AST node is the `undefined` literal.
3206
fn isUndef(node: *ast::Node) -> bool {
3207
    match node.value {
3208
        case ast::NodeValue::Undef => return true,
3209
        else => return false,
3210
    }
3211
}
3212
3213
/// Load the tag byte from a tagged value aggregate (optionals and unions).
3214
unsafe fn tvalTagReg(self: &mut FnLowerer, base: il::Reg) -> il::Reg {
3215
    let tagReg = nextReg(self);
3216
    emitLoadW8At(self, tagReg, base, TVAL_TAG_OFFSET);
3217
    return tagReg;
3218
}
3219
3220
/// Load the tag word from a result aggregate.
3221
unsafe fn resultTagReg(self: &mut FnLowerer, base: il::Reg) -> il::Reg {
3222
    let tagReg = nextReg(self);
3223
    emitLoadW64At(self, tagReg, base, TVAL_TAG_OFFSET);
3224
    return tagReg;
3225
}
3226
3227
/// Get the register to compare against `0` for optional `nil` checking.
3228
/// For null-ptr-optimized types, loads the data pointer, or returns it
3229
/// directly for scalar pointers. For aggregates, returns the tag register.
3230
unsafe fn optionalNilReg(self: &mut FnLowerer, val: il::Val, typ: resolver::Type) -> il::Reg throws (LowerError) {
3231
    let reg = emitValToReg(self, val);
3232
3233
    match typ {
3234
        case resolver::Type::Optional(resolver::Type::Slice { .. }) => {
3235
            let ptrReg = nextReg(self);
3236
            emitLoadW64At(self, ptrReg, reg, SLICE_PTR_OFFSET);
3237
            return ptrReg;
3238
        }
3239
        case resolver::Type::Optional(resolver::Type::Pointer { .. }) => return reg,
3240
        case resolver::Type::Optional(_) => return tvalTagReg(self, reg),
3241
        else => return reg,
3242
    }
3243
}
3244
3245
/// Lower an optional nil check (`opt == nil` or `opt <> nil`).
3246
unsafe fn lowerNilCheck(self: &mut FnLowerer, opt: *ast::Node, isEq: bool) -> il::Val throws (LowerError) {
3247
    let optTy = try typeOf(self, opt);
3248
    // Handle `nil == nil` or `nil <> nil`.
3249
    if optTy == resolver::Type::Nil {
3250
        return il::Val::Imm(1) if isEq else il::Val::Imm(0);
3251
    }
3252
    let val = try lowerExpr(self, opt);
3253
    let cmpReg = try optionalNilReg(self, val, optTy);
3254
3255
    // Null-pointer-optimized types compare a 64-bit pointer against zero.
3256
    // Aggregate optionals compare an 8-bit tag byte against zero.
3257
    let cmpType = il::Type::W64 if resolver::isOptionalPointer(optTy) else il::Type::W8;
3258
3259
    let op = il::BinOp::Eq if isEq else il::BinOp::Ne;
3260
    return emitTypedBinOp(self, op, cmpType, il::Val::Reg(cmpReg), il::Val::Imm(0));
3261
}
3262
3263
/// Load the payload value from a tagged value aggregate at the given offset.
3264
unsafe fn tvalPayloadVal(self: &mut FnLowerer, base: il::Reg, payload: resolver::Type, valOffset: i32) -> il::Val {
3265
    if payload == resolver::Type::Void {
3266
        return il::Val::Undef;
3267
    }
3268
    return emitRead(self, base, valOffset, payload);
3269
}
3270
3271
/// Compute the address of the payload in a tagged value aggregate.
3272
unsafe fn tvalPayloadAddr(self: &mut FnLowerer, base: il::Reg, valOffset: i32) -> il::Val {
3273
    return il::Val::Reg(emitPtrOffset(self, base, valOffset));
3274
}
3275
3276
/// Bind a variable to a tagged value's payload.
3277
unsafe fn bindPayloadVariable(
3278
    self: &mut FnLowerer,
3279
    name: *[u8],
3280
    subjectVal: il::Val,
3281
    bindType: resolver::Type,
3282
    matchBy: resolver::MatchBy,
3283
    valOffset: i32,
3284
    mutable: bool
3285
) -> Var throws (LowerError) {
3286
    let base = emitValToReg(self, subjectVal);
3287
    let mut payload: il::Val = undefined;
3288
3289
    match matchBy {
3290
        case resolver::MatchBy::Value =>
3291
            set payload = tvalPayloadVal(self, base, bindType, valOffset),
3292
        case resolver::MatchBy::Ref, resolver::MatchBy::MutRef =>
3293
            set payload = tvalPayloadAddr(self, base, valOffset),
3294
    };
3295
    return newVar(self, name, ilType(self.low, bindType), mutable, payload);
3296
}
3297
3298
/// Bind an identifier from a matched subject.
3299
unsafe fn bindMatchVariable(
3300
    self: &mut FnLowerer,
3301
    subject: &MatchSubject,
3302
    binding: *ast::Node,
3303
    mutable: bool
3304
) -> ?Var throws (LowerError) {
3305
    // Only bind if the pattern is an identifier.
3306
    let case ast::NodeValue::Ident(name) = binding.value else {
3307
        return nil;
3308
    };
3309
    // For optional aggregates, extract the payload from the tagged value.
3310
    // The tag check already passed, so we know the payload is valid.
3311
    if let case MatchSubjectKind::OptionalAggregate = subject.kind {
3312
        let valOffset = resolver::getOptionalValOffset(subject.bindType) as i32;
3313
        return try bindPayloadVariable(self, name, subject.val, subject.bindType, subject.by, valOffset, mutable);
3314
    }
3315
    // Declare the variable in the current block's scope.
3316
    return newVar(self, name, ilType(self.low, subject.bindType), mutable, subject.val);
3317
}
3318
3319
/// Bind variables from inside case patterns (union variants, records, slices).
3320
/// `failBlock` is passed when nested patterns may require additional tests
3321
/// that branch on mismatch (e.g. nested union variant tests).
3322
unsafe fn bindPatternVariables(self: &mut FnLowerer, subject: &MatchSubject, patterns: &[*ast::Node], failBlock: BlockId) throws (LowerError) {
3323
    for pattern in patterns {
3324
3325
        // Handle simple variant patterns like `Variant(x)`.
3326
        if let arg = resolver::variantPatternBinding(self.low.resolver, pattern) {
3327
            let case MatchSubjectKind::Union(unionInfo) = subject.kind
3328
                else panic "bindPatternVariables: expected union subject";
3329
            let valOffset = unionInfo.valOffset as i32;
3330
3331
            // Get the actual field type from the variant's record info.
3332
            // This preserves the original data layout type (e.g. `*T`) even when
3333
            // the resolver resolved the pattern against a dereferenced type (`T`).
3334
            let variantExtra = resolver::nodeData(self.low.resolver, pattern).extra;
3335
            let case resolver::NodeExtra::UnionVariant { ordinal, .. } = variantExtra
3336
                else panic "bindPatternVariables: expected variant extra";
3337
            let payloadType = unionInfo.variants[ordinal].valueType;
3338
            let payloadRec = resolver::getRecord(payloadType)
3339
                else panic "bindPatternVariables: expected record payload";
3340
            let fieldType = payloadRec.fields[0].fieldType;
3341
3342
            match arg.value {
3343
                case ast::NodeValue::Ident(name) => {
3344
                    try bindPayloadVariable(self, name, subject.val, fieldType, subject.by, valOffset, false);
3345
                }
3346
                case ast::NodeValue::Placeholder => {}
3347
                else => {
3348
                    // Nested pattern inside a variant call, e.g. `Variant(Inner { x, y })`.
3349
                    let base = emitValToReg(self, subject.val);
3350
                    let payloadBase = emitPtrOffset(self, base, valOffset);
3351
                    let fieldInfo = resolver::RecordField {
3352
                        name: nil,
3353
                        fieldType,
3354
                        offset: 0,
3355
                    };
3356
                    try bindFieldVariable(self, arg, payloadBase, fieldInfo, subject.by, failBlock);
3357
                }
3358
            }
3359
        }
3360
        match pattern.value {
3361
            // Compound variant patterns like `Variant { a, b }`.
3362
            case ast::NodeValue::RecordLit(lit) =>
3363
                try bindRecordPatternFields(self, subject, pattern, lit, failBlock),
3364
            // Array patterns like `[a, b, c]`.
3365
            case ast::NodeValue::ArrayLit(items) =>
3366
                try bindArrayPatternElements(self, subject, items, failBlock),
3367
            // Literals, wildcards, identifiers: no bindings needed.
3368
            else => {},
3369
        }
3370
    }
3371
}
3372
3373
/// Bind variables from an array literal pattern (e.g., `[a, 1, c]`).
3374
/// Each element is either bound as a variable, skipped (placeholder), or
3375
/// tested against the subject element, branching to `failBlock` on mismatch.
3376
unsafe fn bindArrayPatternElements(
3377
    self: &mut FnLowerer,
3378
    subject: &MatchSubject,
3379
    items: *[*ast::Node],
3380
    failBlock: BlockId
3381
) throws (LowerError) {
3382
    let case resolver::Type::Array(arrInfo) = subject.type
3383
        else throw LowerError::ExpectedSliceOrArray;
3384
3385
    let elemTy = *arrInfo.item;
3386
    let elemLayout = resolver::getTypeLayout(elemTy);
3387
    let stride = elemLayout.size as i32;
3388
    let base = emitValToReg(self, subject.val);
3389
3390
    for elem, i in items {
3391
        let fieldInfo = resolver::RecordField {
3392
            name: nil,
3393
            fieldType: elemTy,
3394
            offset: (i as i32) * stride,
3395
        };
3396
        try bindFieldVariable(self, elem, base, fieldInfo, subject.by, failBlock);
3397
    }
3398
}
3399
3400
/// Bind fields from a record pattern.
3401
unsafe fn bindRecordPatternFields(self: &mut FnLowerer, subject: &MatchSubject, pattern: *ast::Node, lit: ast::RecordLit, failBlock: BlockId) throws (LowerError) {
3402
    // No fields to bind (e.g., `{ .. }`).
3403
    if lit.fields.len == 0 {
3404
        return;
3405
    }
3406
    // Optional value patterns were already compared structurally by
3407
    // `emitPatternMatch`; unlike union record patterns, they have no payload
3408
    // bindings to extract here.
3409
    if let case MatchSubjectKind::OptionalAggregate = subject.kind {
3410
        return;
3411
    }
3412
    if let recInfo = resolver::getRecord(subject.type) {
3413
        let base = emitValToReg(self, subject.val);
3414
        try bindNestedRecordFields(self, base, lit, recInfo, subject.by, failBlock);
3415
        return;
3416
    }
3417
    // Get the union type info from the subject.
3418
    let case MatchSubjectKind::Union(unionInfo) = subject.kind
3419
        else panic "bindRecordPatternFields: expected union subject";
3420
3421
    // Get the variant index from the pattern node.
3422
    let case resolver::NodeExtra::UnionVariant { ordinal: variantOrdinal, .. } =
3423
        resolver::nodeData(self.low.resolver, pattern).extra
3424
    else throw LowerError::MissingMetadata;
3425
3426
    // Get the record type from the variant's payload type.
3427
    let payloadType = unionInfo.variants[variantOrdinal].valueType;
3428
    let recInfo = resolver::getRecord(payloadType)
3429
        else throw LowerError::ExpectedRecord;
3430
3431
    // Get the payload base pointer which points to the record within the tagged union.
3432
    let base = emitValToReg(self, subject.val);
3433
    let valOffset = unionInfo.valOffset as i32;
3434
    let payloadBase = emitPtrOffset(self, base, valOffset);
3435
3436
    try bindNestedRecordFields(self, payloadBase, lit, recInfo, subject.by, failBlock);
3437
}
3438
3439
/// Bind a single record field to a pattern variable, with support for nested
3440
/// pattern tests that branch to `failBlock` on mismatch.
3441
unsafe fn bindFieldVariable(
3442
    self: &mut FnLowerer,
3443
    binding: *ast::Node,
3444
    base: il::Reg,
3445
    fieldInfo: resolver::RecordField,
3446
    matchBy: resolver::MatchBy,
3447
    failBlock: BlockId
3448
) throws (LowerError) {
3449
    match binding.value {
3450
        case ast::NodeValue::Ident(name) => {
3451
            let val = emitRead(self, base, fieldInfo.offset, fieldInfo.fieldType)
3452
                if matchBy == resolver::MatchBy::Value
3453
                else il::Val::Reg(emitPtrOffset(self, base, fieldInfo.offset));
3454
            newVar(self, name, ilType(self.low, fieldInfo.fieldType), false, val);
3455
        }
3456
        case ast::NodeValue::Placeholder => {}
3457
        case ast::NodeValue::RecordLit(lit) => {
3458
            // Check if this record literal is a union variant pattern.
3459
            if let keyNode = resolver::patternVariantKeyNode(binding) {
3460
                if let case resolver::NodeExtra::UnionVariant { .. } = resolver::nodeData(self.low.resolver, keyNode).extra {
3461
                    try emitNestedFieldTest(self, binding, base, fieldInfo, matchBy, failBlock);
3462
                    return;
3463
                }
3464
            }
3465
            // Plain nested record destructuring pattern.
3466
            // Auto-deref: if the field is a pointer, load it first.
3467
            let mut derefType = fieldInfo.fieldType;
3468
            let mut nestedBase = emitPtrOffset(self, base, fieldInfo.offset);
3469
            if let case resolver::Type::Pointer { target, .. } = fieldInfo.fieldType {
3470
                let ptrReg = nextReg(self);
3471
                emitLoadW64At(self, ptrReg, nestedBase, 0);
3472
                set nestedBase = ptrReg;
3473
                set derefType = *target;
3474
            }
3475
            let recInfo = resolver::getRecord(derefType)
3476
                else throw LowerError::ExpectedRecord;
3477
3478
            try bindNestedRecordFields(self, nestedBase, lit, recInfo, matchBy, failBlock);
3479
        }
3480
        else => {
3481
            // Nested pattern requiring a test (union variant scope access, literal, etc).
3482
            try emitNestedFieldTest(self, binding, base, fieldInfo, matchBy, failBlock);
3483
        }
3484
    }
3485
}
3486
3487
/// Emit a nested pattern test for a record field value, branching to
3488
/// `failBlock` if the pattern does not match. On success, continues in
3489
/// a fresh block and binds any nested variables.
3490
unsafe fn emitNestedFieldTest(
3491
    self: &mut FnLowerer,
3492
    pattern: *ast::Node,
3493
    base: il::Reg,
3494
    fieldInfo: resolver::RecordField,
3495
    matchBy: resolver::MatchBy,
3496
    failBlock: BlockId
3497
) throws (LowerError) {
3498
    let mut fieldType = fieldInfo.fieldType;
3499
    let fieldPtr = emitPtrOffset(self, base, fieldInfo.offset);
3500
3501
    // Auto-deref: when the field is a pointer and the pattern destructures
3502
    // the pointed-to value, load the pointer and use the target type.
3503
    // The loaded pointer becomes the base address for the nested subject.
3504
    let mut derefBase: ?il::Reg = nil;
3505
    if let case resolver::Type::Pointer { target, .. } = fieldType {
3506
        if resolver::isDestructuringPattern(pattern) {
3507
            let ptrReg = nextReg(self);
3508
            emitLoadW64At(self, ptrReg, fieldPtr, 0);
3509
            set derefBase = ptrReg;
3510
            set fieldType = *target;
3511
        }
3512
    }
3513
    // Build a MatchSubject for the nested field.
3514
    let ilTy = ilType(self.low, fieldType);
3515
    let kind = matchSubjectKind(fieldType);
3516
3517
    // Determine the subject value.
3518
    let mut val: il::Val = undefined;
3519
    if let reg = derefBase {
3520
        // Auto-deref: the loaded pointer is the address of the target value.
3521
        set val = il::Val::Reg(reg);
3522
    } else if isAggregateType(fieldType) {
3523
        // Aggregate: use the pointer.
3524
        set val = il::Val::Reg(fieldPtr);
3525
    } else {
3526
        // Scalar: load the value.
3527
        set val = emitRead(self, base, fieldInfo.offset, fieldType);
3528
    }
3529
    let nestedSubject = MatchSubject {
3530
        val,
3531
        type: fieldType,
3532
        ilType: ilTy,
3533
        bindType: fieldType,
3534
        kind,
3535
        by: matchBy,
3536
    };
3537
3538
    // Emit the pattern test: on success jump to `continueBlock`, on fail to `failBlock`.
3539
    let continueBlock = try createBlock(self, "nest");
3540
    try emitPatternMatch(self, &nestedSubject, pattern, continueBlock, failBlock);
3541
    try switchToAndSeal(self, continueBlock);
3542
3543
    // After the test succeeds, bind any nested variables.
3544
    let patterns = [pattern];
3545
    try bindPatternVariables(self, &nestedSubject, &patterns[..], failBlock);
3546
}
3547
3548
/// Bind variables from a nested record literal pattern.
3549
unsafe fn bindNestedRecordFields(
3550
    self: &mut FnLowerer,
3551
    base: il::Reg,
3552
    lit: ast::RecordLit,
3553
    recInfo: resolver::RecordType,
3554
    matchBy: resolver::MatchBy,
3555
    failBlock: BlockId
3556
) throws (LowerError) {
3557
    for fieldNode in lit.fields {
3558
        let case ast::NodeValue::RecordLitField(field) = fieldNode.value else {
3559
            throw LowerError::UnexpectedNodeValue(fieldNode);
3560
        };
3561
        let fieldIdx = resolver::recordFieldIndexFor(self.low.resolver, fieldNode)
3562
            else throw LowerError::MissingMetadata;
3563
        if fieldIdx >= recInfo.fields.len {
3564
            throw LowerError::MissingMetadata;
3565
        }
3566
        let fieldInfo = recInfo.fields[fieldIdx];
3567
3568
        try bindFieldVariable(self, field.value, base, fieldInfo, matchBy, failBlock);
3569
    }
3570
}
3571
3572
/// Lower function body to a list of basic blocks.
3573
unsafe fn lowerFnBody(self: &mut FnLowerer, body: *ast::Node) -> *unsafe [il::Block] throws (LowerError) {
3574
    // Create and switch to entry block.
3575
    let entry = try createBlock(self, "entry");
3576
    set self.entryBlock = entry;
3577
    switchToBlock(self, entry);
3578
3579
    /// Bind parameter registers to variables in the entry block.
3580
    for def in self.params {
3581
        defVar(self, def.var, il::Val::Reg(def.reg));
3582
    }
3583
    /// Lower function body.
3584
    try lowerBlock(self, body);
3585
3586
    // Add implicit return if body doesn't diverge.
3587
    if not blockHasTerminator(self) {
3588
        if *self.fnType.returnType == resolver::Type::Never {
3589
            emit(self, il::Instr::Unreachable);
3590
        } else if self.fnType.throwList.len > 0 {
3591
            if *self.fnType.returnType == resolver::Type::Void {
3592
                // Implicit `void` return in throwing function: wrap in result success.
3593
                let val = try buildResult(self, 0, nil, resolver::Type::Void);
3594
                try emitRetVal(self, val);
3595
            } else {
3596
                // Non-void throwing function without explicit return should
3597
                // not happen.
3598
                panic "lowerFnBody: missing return in non-void function";
3599
            }
3600
        } else {
3601
            emit(self, il::Instr::Ret { val: nil });
3602
        }
3603
    }
3604
    return try finalizeBlocks(self);
3605
}
3606
3607
/// Lower a scalar match as a switch instruction.
3608
unsafe fn lowerMatchSwitch(self: &mut FnLowerer, prongs: *[*ast::Node], subject: &MatchSubject, mergeBlock: &mut ?BlockId) throws (LowerError) {
3609
    let mut blocks: [BlockId; 32] = undefined;
3610
    let mut cases: *unsafe mut [il::SwitchCase] = &mut [];
3611
    let mut defaultIdx: u32 = 0;
3612
    let entry = currentBlock(self);
3613
3614
    for p, i in prongs {
3615
        let case ast::NodeValue::MatchProng(prong) = p.value
3616
            else throw LowerError::UnexpectedNodeValue(p);
3617
3618
        match prong.arm {
3619
            case ast::ProngArm::Binding(_), ast::ProngArm::Else => {
3620
                set blocks[i] = try createBlock(self, "default");
3621
                set defaultIdx = i;
3622
            }
3623
            case ast::ProngArm::Case(pats) => {
3624
                set blocks[i] = try createBlock(self, "case");
3625
                for pat in pats {
3626
                    let cv = resolver::constValueEntry(self.low.resolver, pat)
3627
                        else throw LowerError::MissingConst(pat);
3628
3629
                    cases.append(il::SwitchCase {
3630
                        value: constToScalar(cv),
3631
                        target: *blocks[i],
3632
                        args: &mut []
3633
                    }, self.allocator);
3634
                }
3635
            }
3636
        }
3637
        addPredecessor(self, blocks[i], entry);
3638
    }
3639
    emit(self, il::Instr::Switch {
3640
        val: subject.val,
3641
        defaultTarget: *blocks[defaultIdx],
3642
        defaultArgs: &mut [],
3643
        cases: &mut cases[..]
3644
    });
3645
3646
    for p, i in prongs {
3647
        let case ast::NodeValue::MatchProng(prong) = p.value
3648
            else throw LowerError::UnexpectedNodeValue(p);
3649
3650
        try switchToAndSeal(self, blocks[i]);
3651
        try lowerNode(self, prong.body);
3652
        try emitMergeIfUnterminated(self, mergeBlock);
3653
    }
3654
    if let blk = *mergeBlock {
3655
        try switchToAndSeal(self, blk);
3656
    }
3657
}
3658
3659
/// Lower a match statement.
3660
///
3661
/// Processes prongs sequentially, generating comparison code and branches for each.
3662
/// Prongs are processed in source order, so earlier prongs take precedence.
3663
///
3664
/// Guards are handled by emitting an additional branch after pattern matching
3665
/// but before the body.
3666
///
3667
/// Example:
3668
///
3669
///   match x {
3670
///       case 0 => return 0,
3671
///       case 1 => return 1,
3672
///       else => return 2,
3673
///   }
3674
///
3675
/// Generates:
3676
///
3677
///   arm#0:
3678
///       br.eq w32 %x 0 case#0 arm#1;    // if `x == 0`, jump to case#0, else arm#1
3679
///   case#0:
3680
///       ret 0;                          // `case 0` body
3681
///   arm#1:
3682
///       br.eq w32 %x 1 case#1 arm#2;    // if `x == 1`, jump to case#1, else arm#2
3683
///   case#1:
3684
///       ret 1;                          // `case 1` body
3685
///   arm#2:
3686
///       jmp else#0;                     // fallthrough to `else`
3687
///   else#0:
3688
///       ret 2;                          // `else` body
3689
///
3690
/// Example: Binding with guard
3691
///
3692
///   match x {
3693
///       y if y > 0 => return y,
3694
///       else => return 0,
3695
///   }
3696
///
3697
/// Generates:
3698
///
3699
///   arm#0:
3700
///       jmp guard#0;                    // catch-all binding, jump to guard
3701
///   case#0(w32 %y):
3702
///       ret %y;                         // guarded case body, receives bound var
3703
///   guard#0:
3704
///       sgt w32 %cmp %x 0;              // evaluate guard `y > 0`
3705
///       br.ne w32 %cmp 0 case#0 arm#1;  // if `true`, jump to case body
3706
///   arm#1:
3707
///       jmp else#0;                     // guard failed, fallthrough to `else`
3708
///   else#0:
3709
///       ret 0;                          // `else` body
3710
///
3711
unsafe fn lowerMatch(self: &mut FnLowerer, node: *ast::Node, m: ast::Match) throws (LowerError) {
3712
    assert m.prongs.len > 0;
3713
3714
    let prongs = m.prongs;
3715
    // Lower the subject expression once; reused across all arms.
3716
    let subject = try lowerMatchSubject(self, m.subject);
3717
    // Merge block created lazily if any arm needs it (i.e., doesn't diverge).
3718
    let mut mergeBlock: ?BlockId = nil;
3719
3720
    // Use `switch` instruction for matches with constant patterns.
3721
    if resolver::isMatchConst(self.low.resolver, node) {
3722
        try lowerMatchSwitch(self, prongs, &subject, &mut mergeBlock);
3723
        return;
3724
    }
3725
    // Fallback: chained branches.
3726
    let firstArm = try createBlock(self, "arm");
3727
    try emitJmp(self, firstArm);
3728
    try switchToAndSeal(self, firstArm);
3729
3730
    for prongNode, i in prongs {
3731
        let prongScope = enterVarScope(self);
3732
        let case ast::NodeValue::MatchProng(prong) = prongNode.value
3733
            else panic "lowerMatch: expected match prong";
3734
3735
        let isLastArm = i + 1 == prongs.len;
3736
        let hasGuard = prong.guard <> nil;
3737
        let catchAll = resolver::isProngCatchAll(self.low.resolver, prongNode);
3738
3739
        // Entry block: guard block if present, otherwise the body block.
3740
        // The guard block must be created before the body block so that
3741
        // block indices are in reverse post-order (RPO), which the register
3742
        // allocator requires.
3743
        let mut entryBlock: BlockId = undefined;
3744
        if hasGuard {
3745
            set entryBlock = try createBlock(self, "guard");
3746
        }
3747
        // Body block: where the case body lives.
3748
        let mut bodyLabel = "case";
3749
        if prong.arm == ast::ProngArm::Else {
3750
            set bodyLabel = "else";
3751
        }
3752
        let mut bodyBlock = try createBlock(self, bodyLabel);
3753
        if not hasGuard {
3754
            set entryBlock = bodyBlock;
3755
        }
3756
        // Fallthrough block: jumped to when pattern or guard fails.
3757
        let nextArm = try createBlock(self, "arm");
3758
3759
        // Emit pattern test: branch to entry block on match, next arm on fail.
3760
        match prong.arm {
3761
            case ast::ProngArm::Binding(_) if not catchAll =>
3762
                try emitBindingTest(self, &subject, entryBlock, nextArm),
3763
            case ast::ProngArm::Case(patterns) if not catchAll =>
3764
                try emitPatternMatches(self, &subject, patterns, entryBlock, nextArm),
3765
            else =>
3766
                try emitJmp(self, entryBlock),
3767
        }
3768
        // Switch to entry block, where any variable bindings need to be created.
3769
        try switchToAndSeal(self, entryBlock);
3770
3771
        // Bind pattern variables after successful match. Note that the guard
3772
        // has not been evaluated yet. Nested patterns may emit additional
3773
        // tests that branch to `nextArm` on failure, switching the current
3774
        // block.
3775
        match prong.arm {
3776
            case ast::ProngArm::Binding(pat) =>
3777
                try bindMatchVariable(self, &subject, pat, false),
3778
            case ast::ProngArm::Case(patterns) =>
3779
                try bindPatternVariables(self, &subject, patterns, nextArm),
3780
            else => {},
3781
        }
3782
3783
        // Evaluate guard if present; can still fail to next arm.
3784
        if let g = prong.guard {
3785
            try emitCondBranch(self, g, bodyBlock, nextArm);
3786
        } else if *currentBlock(self) <> *bodyBlock {
3787
            // Nested tests changed the current block. Create a new body block
3788
            // after the nest blocks to maintain RPO ordering, and jump to it.
3789
            set bodyBlock = try createBlock(self, bodyLabel);
3790
            try emitJmp(self, bodyBlock);
3791
        }
3792
        // Lower prong body and jump to merge if unterminated.
3793
        try switchToAndSeal(self, bodyBlock);
3794
        try lowerNode(self, prong.body);
3795
        try emitMergeIfUnterminated(self, &mut mergeBlock);
3796
        exitVarScope(self, prongScope);
3797
3798
        // Switch to next arm, unless last arm without guard.
3799
        if not isLastArm or hasGuard {
3800
            try switchToAndSeal(self, nextArm);
3801
            if isLastArm {
3802
                // Last arm with guard: guard failure jumps to merge.
3803
                try emitMergeIfUnterminated(self, &mut mergeBlock);
3804
            }
3805
        }
3806
    }
3807
    // Continue in merge block if we have one, ie. if at least one arm doesn't
3808
    // diverge.
3809
    if let blk = mergeBlock {
3810
        try switchToAndSeal(self, blk);
3811
    }
3812
}
3813
3814
/// Lower an `if let` statement.
3815
unsafe fn lowerIfLet(self: &mut FnLowerer, cond: ast::IfLet) throws (LowerError) {
3816
    let savedVarsLen = enterVarScope(self);
3817
    let subject = try lowerMatchSubject(self, cond.pattern.scrutinee);
3818
    let mut thenBlock: BlockId = undefined;
3819
    if cond.pattern.guard == nil {
3820
        set thenBlock = try createBlock(self, "then");
3821
    }
3822
    let elseBlock = try createBlock(self, "else");
3823
    let mut mergeBlock: ?BlockId = nil;
3824
3825
    // Pattern match: jump to @then on success, @else on failure.
3826
    try lowerPatternMatch(self, &subject, &cond.pattern, &mut thenBlock, "then", elseBlock);
3827
3828
    // Lower then branch.
3829
    try lowerNode(self, cond.thenBranch);
3830
    try emitMergeIfUnterminated(self, &mut mergeBlock);
3831
    // Pattern bindings are visible only in the success branch. Restore the
3832
    // outer variable scope before lowering `else`, where a same-named outer
3833
    // variable may be referenced.
3834
    exitVarScope(self, savedVarsLen);
3835
3836
    // Lower else branch.
3837
    try switchToAndSeal(self, elseBlock);
3838
    if let elseBranch = cond.elseBranch {
3839
        try lowerNode(self, elseBranch);
3840
    }
3841
    try emitMergeIfUnterminated(self, &mut mergeBlock);
3842
3843
    if let blk = mergeBlock {
3844
        try switchToAndSeal(self, blk);
3845
    }
3846
}
3847
3848
/// Emit pattern match branch with optional guard, and bind variables.
3849
/// Used by `if-let`, `let-else`, and `while-let` lowering.
3850
///
3851
/// When a guard is present, the guard block is created before `successBlock`
3852
/// to ensure block indices are in RPO.
3853
unsafe fn lowerPatternMatch(
3854
    self: &mut FnLowerer,
3855
    subject: &MatchSubject,
3856
    pat: &ast::PatternMatch,
3857
    successBlock: &mut BlockId,
3858
    successLabel: *[u8],
3859
    failBlock: BlockId
3860
) throws (LowerError) {
3861
    // If guard present, pattern match jumps to @guard, then guard evaluation
3862
    // jumps to `successBlock` or `failBlock`. Otherwise, jump directly to
3863
    // `successBlock`.
3864
    let mut targetBlock: BlockId = undefined;
3865
    if pat.guard <> nil {
3866
        set targetBlock = try createBlock(self, "guard");
3867
        set *successBlock = try createBlock(self, successLabel);
3868
    } else {
3869
        set targetBlock = *successBlock;
3870
    }
3871
    match pat.kind {
3872
        case ast::PatternKind::Case => {
3873
            let patterns = [pat.pattern];
3874
            // Jump to `targetBlock` if the pattern matches, `failBlock` otherwise.
3875
            try emitPatternMatches(self, subject, &patterns[..], targetBlock, failBlock);
3876
            try switchToAndSeal(self, targetBlock);
3877
            // Bind any variables inside the pattern. Nested patterns may
3878
            // emit additional tests that branch to `failBlock`, switching
3879
            // the current block.
3880
            try bindPatternVariables(self, subject, &patterns[..], failBlock);
3881
        }
3882
        case ast::PatternKind::Binding => {
3883
            // Jump to `targetBlock` if there is a value present, `failBlock` otherwise.
3884
            try emitBindingTest(self, subject, targetBlock, failBlock);
3885
            try switchToAndSeal(self, targetBlock);
3886
            // Bind the matched value to the pattern variable.
3887
            try bindMatchVariable(self, subject, pat.pattern, pat.mutable);
3888
        }
3889
    }
3890
    // Handle guard: on success jump to `successBlock`, on failure jump to `failBlock`.
3891
    if let g = pat.guard {
3892
        try emitCondBranch(self, g, *successBlock, failBlock);
3893
        try switchToAndSeal(self, *successBlock);
3894
    } else if *currentBlock(self) <> *targetBlock {
3895
        // Nested tests changed the current block. Create a new success block
3896
        // after the nest blocks to maintain RPO ordering, and jump to it.
3897
        set *successBlock = try createBlock(self, successLabel);
3898
3899
        try emitJmp(self, *successBlock);
3900
        try switchToAndSeal(self, *successBlock);
3901
    }
3902
}
3903
3904
/// Lower a `let-else` statement.
3905
unsafe fn lowerLetElse(self: &mut FnLowerer, letElse: ast::LetElse) throws (LowerError) {
3906
    let subject = try lowerMatchSubject(self, letElse.pattern.scrutinee);
3907
    let mut successBlock: BlockId = undefined;
3908
    if letElse.pattern.guard == nil {
3909
        set successBlock = try createBlock(self, "success");
3910
    }
3911
    // The else branch executes when the pattern fails to match.
3912
    let elseBlock = try createBlock(self, "else");
3913
3914
    // Evaluate the pattern and jump to @success or @else.
3915
    try lowerPatternMatch(
3916
        self,
3917
        &subject,
3918
        &letElse.pattern,
3919
        &mut successBlock,
3920
        "success",
3921
        elseBlock,
3922
    );
3923
    let mut bindingVar: ?Var = nil;
3924
    if let case ast::PatternKind::Binding = letElse.pattern.kind {
3925
        set bindingVar = lookupLocalVar(self, letElse.pattern.pattern);
3926
    }
3927
    let mergeBlock = try createBlock(self, "merge");
3928
    try emitJmp(self, mergeBlock);
3929
3930
    try switchToAndSeal(self, elseBlock);
3931
    if try typeOf(self, letElse.elseBranch) == resolver::Type::Never {
3932
        try lowerNode(self, letElse.elseBranch);
3933
    } else {
3934
        let fallback = try lowerExpr(self, letElse.elseBranch);
3935
        if let variable = bindingVar {
3936
            defVar(self, variable, fallback);
3937
        }
3938
        try emitJmp(self, mergeBlock);
3939
    }
3940
3941
    // Continue at @merge after a successful match or value-producing fallback.
3942
    try switchToAndSeal(self, mergeBlock);
3943
}
3944
3945
/// Lower a `while let` loop as a match-driven loop.
3946
unsafe fn lowerWhileLet(self: &mut FnLowerer, w: ast::WhileLet) throws (LowerError) {
3947
    let savedVarsLen = enterVarScope(self);
3948
    // Create control flow blocks: loop header, body (created lazily when
3949
    // there's a guard), and exit.
3950
    let whileBlock = try createBlock(self, "while");
3951
    let mut bodyBlock: BlockId = undefined;
3952
    if w.pattern.guard == nil {
3953
        set bodyBlock = try createBlock(self, "body");
3954
    }
3955
    let endBlock = try createBlock(self, "merge");
3956
3957
    // Enter loop context and jump to loop header.
3958
    enterLoop(self, endBlock, whileBlock);
3959
    try switchAndJumpTo(self, whileBlock);
3960
    let subject = try lowerMatchSubject(self, w.pattern.scrutinee);
3961
3962
    // Evaluate pattern and jump to loop body or loop end.
3963
    try lowerPatternMatch(self, &subject, &w.pattern, &mut bodyBlock, "body", endBlock);
3964
3965
    // Lower loop body, jump back to loop header, and exit loop context.
3966
    try lowerBlock(self, w.body);
3967
    try emitJmpAndSeal(self, whileBlock);
3968
3969
    exitLoop(self);
3970
    try switchToAndSeal(self, endBlock);
3971
    exitVarScope(self, savedVarsLen);
3972
}
3973
3974
///////////////////
3975
// Node Lowering //
3976
///////////////////
3977
3978
/// Lower an AST node.
3979
unsafe fn lowerNode(self: &mut FnLowerer, node: *ast::Node) throws (LowerError) {
3980
    if self.low.options.debug {
3981
        set self.srcLoc.offset = node.span.offset;
3982
    }
3983
    match node.value {
3984
        case ast::NodeValue::Block(_) => {
3985
            try lowerBlock(self, node);
3986
        }
3987
        case ast::NodeValue::Return { value } => {
3988
            try lowerReturnStmt(self, node, value);
3989
        }
3990
        case ast::NodeValue::Throw { expr } => {
3991
            try lowerThrowStmt(self, expr);
3992
        }
3993
        case ast::NodeValue::Let(l) => {
3994
            try lowerLet(self, node, l);
3995
        }
3996
        case ast::NodeValue::ConstDecl(decl) => {
3997
            // Local constants lower to data declarations and emit no runtime code.
3998
            try registerLocalDataDeclName(self, node);
3999
            try lowerDataDecl(self.low, node, decl.value, true);
4000
        }
4001
        case ast::NodeValue::StaticDecl(decl) => {
4002
            // Local statics lower to data declarations and emit no runtime code.
4003
            try registerLocalDataDeclName(self, node);
4004
            try lowerDataDecl(self.low, node, decl.value, false);
4005
        }
4006
        case ast::NodeValue::If(i) => {
4007
            try lowerIf(self, i);
4008
        }
4009
        case ast::NodeValue::IfLet(i) => {
4010
            try lowerIfLet(self, i);
4011
        }
4012
        case ast::NodeValue::Assign(a) => {
4013
            try lowerAssign(self, node, a);
4014
        }
4015
        case ast::NodeValue::Loop { body } => {
4016
            try lowerLoop(self, body);
4017
        }
4018
        case ast::NodeValue::While(w) => {
4019
            try lowerWhile(self, w);
4020
        }
4021
        case ast::NodeValue::WhileLet(w) => {
4022
            try lowerWhileLet(self, w);
4023
        }
4024
        case ast::NodeValue::For(f) => {
4025
            try lowerFor(self, node, f);
4026
        }
4027
        case ast::NodeValue::Break => {
4028
            try lowerBreak(self);
4029
        }
4030
        case ast::NodeValue::Continue => {
4031
            try lowerContinue(self);
4032
        }
4033
        case ast::NodeValue::Match(m) => {
4034
            try lowerMatch(self, node, m);
4035
        }
4036
        case ast::NodeValue::LetElse(letElse) => {
4037
            try lowerLetElse(self, letElse);
4038
        }
4039
        case ast::NodeValue::ExprStmt(expr) => {
4040
            let _ = try lowerExpr(self, expr);
4041
        }
4042
        case ast::NodeValue::Panic { .. } => {
4043
            emit(self, il::Instr::Unreachable);
4044
        }
4045
        case ast::NodeValue::Assert { condition, .. } => {
4046
            // Lower `assert <cond>` as: `if not cond { unreachable; }`.
4047
            let thenBlock = try createBlock(self, "assert.fail");
4048
            let endBlock = try createBlock(self, "assert.ok");
4049
4050
            // Branch: if condition is `true`, go to `endBlock`; if `false`, go to `thenBlock`.
4051
            try emitCondBranch(self, condition, endBlock, thenBlock);
4052
            try sealBlock(self, thenBlock);
4053
4054
            // Emit `unreachable` in the failure block.
4055
            switchToBlock(self, thenBlock);
4056
            emit(self, il::Instr::Unreachable);
4057
4058
            // Continue after the assert.
4059
            try switchToAndSeal(self, endBlock);
4060
        }
4061
        else => {
4062
            // Treat as expression statement, discard result.
4063
            let _ = try lowerExpr(self, node);
4064
        }
4065
    }
4066
}
4067
4068
/// Lower a code block.
4069
unsafe fn lowerBlock(self: &mut FnLowerer, node: *ast::Node) throws (LowerError) {
4070
    let case ast::NodeValue::Block(blk) = node.value else {
4071
        throw LowerError::ExpectedBlock(node);
4072
    };
4073
    let savedVarsLen = enterVarScope(self);
4074
    for stmt in blk.statements {
4075
        try lowerNode(self, stmt);
4076
4077
        // If the statement diverges, further statements are unreachable.
4078
        if blockHasTerminator(self) {
4079
            exitVarScope(self, savedVarsLen);
4080
            return;
4081
        }
4082
    }
4083
    exitVarScope(self, savedVarsLen);
4084
}
4085
4086
///////////////////////////////////////
4087
// Record and Aggregate Type Helpers //
4088
///////////////////////////////////////
4089
4090
/// Extract the nominal record info from a resolver type.
4091
unsafe fn recordInfoFromType(typ: resolver::Type) -> ?resolver::RecordType {
4092
    let case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) = typ
4093
        else return nil;
4094
4095
    return recInfo;
4096
}
4097
4098
/// Extract the nominal union info from a resolver type.
4099
unsafe fn unionInfoFromType(typ: resolver::Type) -> ?resolver::UnionType {
4100
    let case resolver::Type::Nominal(resolver::NominalType::Union(unionInfo)) = typ
4101
        else return nil;
4102
4103
    return unionInfo;
4104
}
4105
4106
/// Return the effective type of a node after any coercion applied by
4107
/// the resolver. `lowerExpr` already materializes the coercion in the
4108
/// IL value, so the lowerer must use the post-coercion type when
4109
/// choosing how to compare or store that value.
4110
unsafe fn effectiveType(self: &mut FnLowerer, node: *ast::Node) -> resolver::Type throws (LowerError) {
4111
    let ty = try typeOf(self, node);
4112
    if let coerce = resolver::coercionFor(self.low.resolver, node) {
4113
        if let case resolver::Coercion::OptionalLift(optTy) = coerce {
4114
            return optTy;
4115
        }
4116
    }
4117
    return ty;
4118
}
4119
4120
/// Check if a resolver type lowers to an aggregate in memory.
4121
unsafe fn isAggregateType(typ: resolver::Type) -> bool {
4122
    match typ {
4123
        case resolver::Type::Slice { .. },
4124
             resolver::Type::TraitObject { .. } => return true,
4125
        case resolver::Type::Optional(resolver::Type::Pointer { .. }) => {
4126
            // Optional pointers are scalar due to NPO.
4127
            return false;
4128
        }
4129
        case resolver::Type::Optional(_) => {
4130
            // All other optionals, including optional slices, are aggregates.
4131
            return true;
4132
        }
4133
        case resolver::Type::Nominal(_) => {
4134
            // Void unions are small enough to pass by value.
4135
            return not resolver::isVoidUnion(typ);
4136
        }
4137
        case resolver::Type::Array(_),
4138
             resolver::Type::Nil => return true,
4139
        else => return false,
4140
    }
4141
}
4142
4143
/// Check if a resolver type is a small aggregate that can be
4144
/// passed or returned by value in a register.
4145
unsafe fn isSmallAggregate(typ: resolver::Type) -> bool {
4146
    match typ {
4147
        case resolver::Type::Nominal(_) => {
4148
            if resolver::isVoidUnion(typ) {
4149
                return false;
4150
            }
4151
            let layout = resolver::getTypeLayout(typ);
4152
            return layout.size <= resolver::PTR_SIZE;
4153
        }
4154
        else => return false,
4155
    }
4156
}
4157
4158
/// Whether a function needs a hidden return parameter.
4159
///
4160
/// This is the case for throwing functions, which return a result aggregate,
4161
/// and for functions returning large aggregates that cannot be passed in
4162
/// registers.
4163
unsafe fn requiresReturnParam(fnType: *resolver::FnType) -> bool {
4164
    return fnType.throwList.len > 0
4165
        or (isAggregateType(*fnType.returnType)
4166
        and not isSmallAggregate(*fnType.returnType));
4167
}
4168
4169
/// Check if a node is a void union variant literal (e.g. `Color::Red`).
4170
/// If so, returns the variant's tag index. This enables optimized comparisons
4171
/// that only check the tag instead of doing full aggregate comparison.
4172
unsafe fn voidVariantIndex(res: &resolver::Resolver, node: *ast::Node) -> ?i64 {
4173
    let data = resolver::nodeData(res, node);
4174
    // Optional equality checks both the presence tag and the union value.
4175
    if let case resolver::Coercion::OptionalLift(_) = data.coercion {
4176
        return nil;
4177
    }
4178
    let sym = data.sym else {
4179
        return nil;
4180
    };
4181
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } = sym.data else {
4182
        return nil;
4183
    };
4184
    // Only void variants can use tag-only comparison.
4185
    if payloadType <> resolver::Type::Void {
4186
        return nil;
4187
    }
4188
    return index as i64;
4189
}
4190
4191
/// Reserve stack storage for a value of the given type.
4192
unsafe fn emitReserve(self: &mut FnLowerer, typ: resolver::Type) -> il::Reg throws (LowerError) {
4193
    let layout = resolver::getTypeLayout(typ);
4194
    return emitReserveLayout(self, layout);
4195
}
4196
4197
/// Reserve stack storage with an explicit layout.
4198
unsafe fn emitReserveLayout(self: &mut FnLowerer, layout: resolver::Layout) -> il::Reg {
4199
    let dst = nextReg(self);
4200
4201
    emit(self, il::Instr::Reserve {
4202
        dst,
4203
        size: il::Val::Imm(layout.size as i64),
4204
        alignment: layout.alignment,
4205
    });
4206
    return dst;
4207
}
4208
4209
/// Store a value into an address.
4210
unsafe fn emitStore(self: &mut FnLowerer, base: il::Reg, offset: i32, typ: resolver::Type, src: il::Val) throws (LowerError) {
4211
    // `undefined` values need no store.
4212
    if let case il::Val::Undef = src {
4213
        return;
4214
    }
4215
    if isAggregateType(typ) {
4216
        let dst = emitPtrOffset(self, base, offset);
4217
        let src = emitValToReg(self, src);
4218
        let layout = resolver::getTypeLayout(typ);
4219
4220
        emit(self, il::Instr::Blit { dst, src, size: il::Val::Imm(layout.size as i64) });
4221
    } else {
4222
        emit(self, il::Instr::Store {
4223
            typ: ilType(self.low, typ),
4224
            src,
4225
            dst: base,
4226
            offset,
4227
        });
4228
    }
4229
}
4230
4231
/// Allocate stack space for a value and store it. Returns a pointer to the value.
4232
unsafe fn emitStackVal(self: &mut FnLowerer, typ: resolver::Type, val: il::Val) -> il::Val throws (LowerError) {
4233
    let ptr = try emitReserve(self, typ);
4234
    try emitStore(self, ptr, 0, typ, val);
4235
    return il::Val::Reg(ptr);
4236
}
4237
4238
/// Generic helper to build any tagged aggregate.
4239
/// Reserves space based on the provided layout, stores the tag, and optionally
4240
/// stores the payload value at `valOffset`.
4241
unsafe fn buildTagged(
4242
    self: &mut FnLowerer,
4243
    layout: resolver::Layout,
4244
    tag: i64,
4245
    payload: ?il::Val,
4246
    payloadType: resolver::Type,
4247
    tagSize: u32,
4248
    valOffset: i32
4249
) -> il::Val throws (LowerError) {
4250
    let dst = nextReg(self);
4251
    emit(self, il::Instr::Reserve {
4252
        dst,
4253
        size: il::Val::Imm(layout.size as i64),
4254
        alignment: layout.alignment,
4255
    });
4256
    if tagSize == 1 {
4257
        emitStoreW8At(self, il::Val::Imm(tag), dst, TVAL_TAG_OFFSET);
4258
    } else {
4259
        emitStoreW64At(self, il::Val::Imm(tag), dst, TVAL_TAG_OFFSET);
4260
    }
4261
4262
    if let val = payload {
4263
        if payloadType <> resolver::Type::Void {
4264
            try emitStore(self, dst, valOffset, payloadType, val);
4265
        }
4266
    }
4267
    return il::Val::Reg(dst);
4268
}
4269
4270
/// Wrap a value in an optional type.
4271
///
4272
/// For optional pointers (`?*T`), the value is returned as-is since pointers
4273
/// use zero to represent `nil`. For other optionals, builds a tagged aggregate.
4274
/// with the tag set to `1`, and the value as payload.
4275
unsafe fn wrapInOptional(self: &mut FnLowerer, val: il::Val, optType: resolver::Type) -> il::Val throws (LowerError) {
4276
    let case resolver::Type::Optional(inner) = optType else {
4277
        throw LowerError::ExpectedOptional;
4278
    };
4279
    // Null-pointer-optimized (NPO) types are used as-is -- valid values are never null.
4280
    if resolver::isNullableType(*inner) {
4281
        return val;
4282
    }
4283
    let layout = resolver::getTypeLayout(optType);
4284
    let valOffset = resolver::getOptionalValOffset(*inner) as i32;
4285
4286
    return try buildTagged(self, layout, 1, val, *inner, 1, valOffset);
4287
}
4288
4289
/// Build a `nil` value for an optional type.
4290
///
4291
/// For optional pointers (`?*T`), returns an immediate `0` (null pointer).
4292
/// For other optionals, builds a tagged aggregate with tag set to `0` (absent).
4293
unsafe fn buildNilOptional(self: &mut FnLowerer, optType: resolver::Type) -> il::Val throws (LowerError) {
4294
    let case resolver::Type::Optional(inner) = optType
4295
        else throw LowerError::ExpectedOptional;
4296
    if let case resolver::Type::Pointer { .. } = *inner {
4297
        return il::Val::Imm(0);
4298
    }
4299
    if let case resolver::Type::Slice { item, mutable, .. } = *inner {
4300
        return try buildSliceValue(
4301
            self, item, mutable, il::Val::Imm(0), il::Val::Imm(0), il::Val::Imm(0)
4302
        );
4303
    }
4304
    let valOffset = resolver::getOptionalValOffset(*inner) as i32;
4305
    return try buildTagged(self, resolver::getTypeLayout(optType), 0, nil, *inner, 1, valOffset);
4306
}
4307
4308
/// Build a result value for throwing functions.
4309
unsafe fn buildResult(
4310
    self: &mut FnLowerer,
4311
    tag: i64,
4312
    payload: ?il::Val,
4313
    payloadType: resolver::Type
4314
) -> il::Val throws (LowerError) {
4315
    let successType = *self.fnType.returnType;
4316
    let layout = resolver::getResultLayout(
4317
        successType, self.fnType.throwList
4318
    );
4319
    return try buildTagged(self, layout, tag, payload, payloadType, resolver::PTR_SIZE as i32, RESULT_VAL_OFFSET);
4320
}
4321
4322
/// Build a slice aggregate from a data pointer, length and capacity.
4323
unsafe fn buildSliceValue(
4324
    self: &mut FnLowerer,
4325
    elemTy: *resolver::Type,
4326
    mutable: bool,
4327
    ptrVal: il::Val,
4328
    lenVal: il::Val,
4329
    capVal: il::Val
4330
) -> il::Val throws (LowerError) {
4331
    let sliceType = resolver::Type::Slice {
4332
        class: types::PointerClass::Unsafe,
4333
        item: elemTy,
4334
        mutable,
4335
    };
4336
    let dst = try emitReserve(self, sliceType);
4337
    let ptrTy = resolver::Type::Pointer {
4338
        class: types::PointerClass::Unsafe,
4339
        target: elemTy,
4340
        mutable,
4341
    };
4342
4343
    try emitStore(self, dst, SLICE_PTR_OFFSET, ptrTy, ptrVal);
4344
    try emitStore(self, dst, SLICE_LEN_OFFSET, resolver::Type::U32, lenVal);
4345
    try emitStore(self, dst, SLICE_CAP_OFFSET, resolver::Type::U32, capVal);
4346
4347
    return il::Val::Reg(dst);
4348
}
4349
4350
/// Build a trait object fat pointer from a data pointer and a v-table.
4351
unsafe fn buildTraitObject(
4352
    self: &mut FnLowerer,
4353
    dataVal: il::Val,
4354
    traitInfo: *unsafe resolver::TraitType,
4355
    inst: &resolver::InstanceEntry
4356
) -> il::Val throws (LowerError) {
4357
    let vName = vtableName(self.low, inst.moduleId, inst.concreteTypeName, traitInfo.name);
4358
4359
    // Reserve space for the trait object on the stack.
4360
    let slot = emitReserveLayout(self, resolver::Layout {
4361
        size: resolver::PTR_SIZE * 2,
4362
        alignment: resolver::PTR_SIZE,
4363
    });
4364
4365
    // Store data pointer.
4366
    emit(self, il::Instr::Store {
4367
        typ: il::Type::W64,
4368
        src: dataVal,
4369
        dst: slot,
4370
        offset: TRAIT_OBJ_DATA_OFFSET,
4371
    });
4372
4373
    // Store v-table address.
4374
    emit(self, il::Instr::Store {
4375
        typ: il::Type::W64,
4376
        src: il::Val::DataSym(vName),
4377
        dst: slot,
4378
        offset: TRAIT_OBJ_VTABLE_OFFSET,
4379
    });
4380
    return il::Val::Reg(slot);
4381
}
4382
4383
/// Compute a field pointer by adding a byte offset to a base address.
4384
unsafe fn emitPtrOffset(self: &mut FnLowerer, base: il::Reg, offset: i32) -> il::Reg {
4385
    if offset == 0 {
4386
        return base;
4387
    }
4388
    let dst = nextReg(self);
4389
4390
    emit(self, il::Instr::BinOp {
4391
        op: il::BinOp::Add,
4392
        typ: il::Type::W64,
4393
        dst,
4394
        a: il::Val::Reg(base),
4395
        b: il::Val::Imm(offset as i64),
4396
    });
4397
    return dst;
4398
}
4399
4400
/// Emit an element address computation for array/slice indexing.
4401
/// Computes: `base + idx * stride`.
4402
unsafe fn emitElem(self: &mut FnLowerer, stride: u32, base: il::Reg, idx: il::Val) -> il::Reg {
4403
    // If index is zero, return base directly.
4404
    if idx == il::Val::Imm(0) {
4405
        return base;
4406
    }
4407
    // If stride is `1`, skip the multiply.
4408
    if stride == 1 {
4409
        let dst = nextReg(self);
4410
4411
        emit(self, il::Instr::BinOp {
4412
            op: il::BinOp::Add,
4413
            typ: il::Type::W64,
4414
            dst,
4415
            a: il::Val::Reg(base),
4416
            b: idx
4417
        });
4418
        return dst;
4419
    }
4420
    // Compute `offset = idx * stride`.
4421
    let offset = nextReg(self);
4422
4423
    emit(self, il::Instr::BinOp {
4424
        op: il::BinOp::Mul,
4425
        typ: il::Type::W64,
4426
        dst: offset,
4427
        a: idx,
4428
        b: il::Val::Imm(stride as i64)
4429
    });
4430
    // Compute `dst = base + offset`.
4431
    let dst = nextReg(self);
4432
    emit(self, il::Instr::BinOp {
4433
        op: il::BinOp::Add,
4434
        typ: il::Type::W64,
4435
        dst,
4436
        a: il::Val::Reg(base),
4437
        b: il::Val::Reg(offset)
4438
    });
4439
    return dst;
4440
}
4441
4442
/// Emit a typed binary operation, returning the result as a value.
4443
unsafe fn emitTypedBinOp(self: &mut FnLowerer, op: il::BinOp, typ: il::Type, a: il::Val, b: il::Val) -> il::Val {
4444
    let dst = nextReg(self);
4445
    emit(self, il::Instr::BinOp { op, typ, dst, a, b });
4446
    return il::Val::Reg(dst);
4447
}
4448
4449
/// Emit a tag comparison for void variant equality/inequality.
4450
unsafe fn emitTagCmp(self: &mut FnLowerer, op: ast::BinaryOp, val: il::Val, tagIdx: i64, valType: resolver::Type) -> il::Val
4451
    throws (LowerError)
4452
{
4453
    let reg = emitValToReg(self, val);
4454
4455
    // For all-void unions, the value *is* the tag, not a pointer.
4456
    let mut tag: il::Val = undefined;
4457
    if resolver::isVoidUnion(valType) {
4458
        set tag = il::Val::Reg(reg);
4459
    } else {
4460
        set tag = loadTag(self, reg, TVAL_TAG_OFFSET, il::Type::W8);
4461
    }
4462
    let binOp = il::BinOp::Eq if op == ast::BinaryOp::Eq else il::BinOp::Ne;
4463
    return emitTypedBinOp(self, binOp, il::Type::W8, tag, il::Val::Imm(tagIdx));
4464
}
4465
4466
/// Logical "and" between two values. Returns the result in a register.
4467
unsafe fn emitLogicalAnd(self: &mut FnLowerer, left: ?il::Val, right: il::Val) -> il::Val {
4468
    let prev = left else {
4469
        return right;
4470
    };
4471
    return emitTypedBinOp(self, il::BinOp::And, il::Type::W32, prev, right);
4472
}
4473
4474
//////////////////////////
4475
// Aggregate Comparison //
4476
//////////////////////////
4477
4478
/// Emit an equality test for values at an offset of the given base registers.
4479
unsafe fn emitEqAtOffset(
4480
    self: &mut FnLowerer,
4481
    left: il::Reg,
4482
    right: il::Reg,
4483
    offset: i32,
4484
    fieldType: resolver::Type
4485
) -> il::Val throws (LowerError) {
4486
    // For aggregate types, pass offset through and compare recursively.
4487
    if isAggregateType(fieldType) {
4488
        return try lowerAggregateEq(self, fieldType, left, right, offset);
4489
    }
4490
    // For scalar types, load and compare directly.
4491
    let a = emitLoad(self, left, offset, fieldType);
4492
    let b = emitLoad(self, right, offset, fieldType);
4493
    let dst = nextReg(self);
4494
    emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ: ilType(self.low, fieldType), dst, a, b });
4495
4496
    return il::Val::Reg(dst);
4497
}
4498
4499
/// Compare two record values for equality.
4500
unsafe fn lowerRecordEq(
4501
    self: &mut FnLowerer,
4502
    recInfo: resolver::RecordType,
4503
    a: il::Reg,
4504
    b: il::Reg,
4505
    offset: i32
4506
) -> il::Val throws (LowerError) {
4507
    let mut result: ?il::Val = nil;
4508
4509
    for field in recInfo.fields {
4510
        let cmp = try emitEqAtOffset(self, a, b, offset + field.offset, field.fieldType);
4511
4512
        set result = emitLogicalAnd(self, result, cmp);
4513
    }
4514
    if let r = result {
4515
        return r;
4516
    }
4517
    return il::Val::Imm(1);
4518
}
4519
4520
/// Compare two slice values for equality.
4521
unsafe fn lowerSliceEq(
4522
    self: &mut FnLowerer,
4523
    elemTy: *resolver::Type,
4524
    mutable: bool,
4525
    a: il::Reg,
4526
    b: il::Reg,
4527
    offset: i32
4528
) -> il::Val throws (LowerError) {
4529
    let ptrTy = resolver::Type::Pointer {
4530
        class: types::PointerClass::Unsafe,
4531
        target: elemTy,
4532
        mutable,
4533
    };
4534
    let ptrEq = try emitEqAtOffset(self, a, b, offset + SLICE_PTR_OFFSET, ptrTy);
4535
    let lenEq = try emitEqAtOffset(self, a, b, offset + SLICE_LEN_OFFSET, resolver::Type::U32);
4536
4537
    return emitTypedBinOp(self, il::BinOp::And, il::Type::W32, ptrEq, lenEq);
4538
}
4539
4540
/// Compare two optional aggregate values for equality.
4541
///
4542
/// Two optionals are equal when their tags match and either both are `nil` or
4543
/// their payloads are equal.
4544
///
4545
/// For inner types that are safe to compare even when uninitialised, we use a
4546
/// branchless formulation: `tagEq AND (tagNil OR payloadEq)`
4547
///
4548
/// For inner types that may contain uninitialized data when `nil` (unions,
4549
/// nested optionals), the payload comparison is guarded behind a branch
4550
/// so that `nil` payloads are never inspected.
4551
unsafe fn lowerOptionalEq(
4552
    self: &mut FnLowerer,
4553
    inner: resolver::Type,
4554
    a: il::Reg,
4555
    b: il::Reg,
4556
    offset: i32
4557
) -> il::Val throws (LowerError) {
4558
    let valOffset = resolver::getOptionalValOffset(inner) as i32;
4559
4560
    // Load tags.
4561
    let tagA = loadTag(self, a, offset + TVAL_TAG_OFFSET, il::Type::W8);
4562
    let tagB = loadTag(self, b, offset + TVAL_TAG_OFFSET, il::Type::W8);
4563
4564
    // For simple inner types (no unions/nested optionals), use branchless comparison.
4565
    // Unions and nested optionals may contain uninitialized payload bytes
4566
    // when nil, so they need a guarded comparison.
4567
    let isUnion = unionInfoFromType(inner) <> nil;
4568
    let mut isOptional = false;
4569
    if let case resolver::Type::Optional(_) = inner {
4570
        set isOptional = true;
4571
    }
4572
    if not isUnion and not isOptional {
4573
        let tagEq = emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, tagA, tagB);
4574
        let tagNil = emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, tagA, il::Val::Imm(0));
4575
        let payloadEq = try emitEqAtOffset(self, a, b, offset + valOffset, inner);
4576
4577
        return emitTypedBinOp(self, il::BinOp::And, il::Type::W32, tagEq,
4578
            emitTypedBinOp(self, il::BinOp::Or, il::Type::W32, tagNil, payloadEq));
4579
    }
4580
4581
    // For complex inner types, use branching comparison to avoid inspecting
4582
    // uninitialized payload bytes.
4583
    let resultReg = nextReg(self);
4584
    let mergeBlock = try createBlockWithParam(self, "opteq#merge", il::Param {
4585
        value: resultReg, type: il::Type::W8
4586
    });
4587
    let nilCheck = try createBlock(self, "opteq#nil");
4588
    let payloadCmp = try createBlock(self, "opteq#payload");
4589
4590
    let falseArgs = try allocVal(self, il::Val::Imm(0));
4591
    let trueArgs = try allocVal(self, il::Val::Imm(1));
4592
4593
    // Check if tags differ.
4594
    emit(self, il::Instr::Br {
4595
        op: il::CmpOp::Eq, typ: il::Type::W8, a: tagA, b: tagB,
4596
        thenTarget: *nilCheck, thenArgs: &mut [],
4597
        elseTarget: *mergeBlock, elseArgs: falseArgs,
4598
    });
4599
    addPredecessor(self, nilCheck, currentBlock(self));
4600
    addPredecessor(self, mergeBlock, currentBlock(self));
4601
4602
    // Check if both are `nil`.
4603
    try switchToAndSeal(self, nilCheck);
4604
    emit(self, il::Instr::Br {
4605
        op: il::CmpOp::Ne, typ: il::Type::W8, a: tagA, b: il::Val::Imm(0),
4606
        thenTarget: *payloadCmp, thenArgs: &mut [],
4607
        elseTarget: *mergeBlock, elseArgs: trueArgs,
4608
    });
4609
    addPredecessor(self, payloadCmp, currentBlock(self));
4610
    addPredecessor(self, mergeBlock, currentBlock(self));
4611
4612
    // Both are non-`nil`, compare payloads.
4613
    try switchToAndSeal(self, payloadCmp);
4614
    let payloadEq = try emitEqAtOffset(self, a, b, offset + valOffset, inner);
4615
    try emitJmpWithArg(self, mergeBlock, payloadEq);
4616
    try switchToAndSeal(self, mergeBlock);
4617
4618
    return il::Val::Reg(resultReg);
4619
}
4620
4621
/// Compare two union values for equality.
4622
///
4623
/// Two unions are equal iff their tags match and, for non-void variants,
4624
/// their payloads are also equal. The comparison proceeds as follows.
4625
///
4626
/// First, compare the tags. If they differ, the unions are not equal, so
4627
/// jump to the merge block with `false`. If they match, jump to the tag
4628
/// block to determine which variant we're dealing with.
4629
///
4630
/// The tag block uses a switch on the tag value to dispatch to the appropriate
4631
/// comparison block. Void variants jump directly to merge with `true`.
4632
/// Non-void variants each have their own payload block that compares the
4633
/// payload and jumps to the merge block with the result.
4634
///
4635
/// The merge block collects results from all paths via a block parameter
4636
/// and returns the final equality result.
4637
///
4638
/// For all-void unions, we skip the control flow entirely and just compare
4639
/// the tags directly.
4640
///
4641
/// TODO: Could be optimized to branchless when all non-void variants share
4642
/// the same payload type: `tagEq AND (isVoidVariant OR payloadEq)`.
4643
unsafe fn lowerUnionEq(
4644
    self: &mut FnLowerer,
4645
    unionInfo: resolver::UnionType,
4646
    a: il::Reg,
4647
    b: il::Reg,
4648
    offset: i32
4649
) -> il::Val throws (LowerError) {
4650
    // Compare tags.
4651
    let tagA = loadTag(self, a, offset + TVAL_TAG_OFFSET, il::Type::W8);
4652
    let tagB = loadTag(self, b, offset + TVAL_TAG_OFFSET, il::Type::W8);
4653
4654
    // Fast path: all-void union just needs tag comparison.
4655
    if unionInfo.isAllVoid {
4656
        return emitTypedBinOp(self, il::BinOp::Eq, il::Type::W8, tagA, tagB);
4657
    }
4658
    // Holds the equality result.
4659
    let resultReg = nextReg(self);
4660
4661
    // Where control flow continues after equality check is done. Receives
4662
    // the result as a parameter.
4663
    let mergeBlock = try createBlockWithParam(self, "eq#merge", il::Param {
4664
        value: resultReg, type: il::Type::W8
4665
    });
4666
    // Where we switch on the tag to compare payloads.
4667
    let tagBlock = try createBlock(self, "eq#tag");
4668
4669
    // Compare tags: if they differ, jump to merge with `false`; otherwise check payloads.
4670
    let falseArgs = try allocVal(self, il::Val::Imm(0));
4671
4672
    assert tagBlock <> mergeBlock;
4673
4674
    // TODO: Use the helper once the compiler supports more than eight function params.
4675
    emit(self, il::Instr::Br {
4676
        op: il::CmpOp::Eq, typ: il::Type::W8, a: tagA, b: tagB,
4677
        thenTarget: *tagBlock, thenArgs: &mut [],
4678
        elseTarget: *mergeBlock, elseArgs: falseArgs,
4679
    });
4680
    addPredecessor(self, tagBlock, currentBlock(self));
4681
    addPredecessor(self, mergeBlock, currentBlock(self));
4682
4683
    // Create comparison blocks for each non-void variant and build switch cases.
4684
    // Void variants jump directly to merge with `true`.
4685
    let trueArgs = try allocVal(self, il::Val::Imm(1));
4686
    let cases = try! alloc::allocRawSlice(
4687
        self.low.fnArena, @sizeOf(il::SwitchCase), @alignOf(il::SwitchCase), unionInfo.variants.len as u32
4688
    ) as *unsafe mut [il::SwitchCase];
4689
4690
    let mut caseBlocks: [?BlockId; resolver::MAX_UNION_VARIANTS] = undefined;
4691
    for variant, i in unionInfo.variants {
4692
        if variant.valueType == resolver::Type::Void {
4693
            set cases[i] = il::SwitchCase {
4694
                value: i as i64,
4695
                target: *mergeBlock,
4696
                args: trueArgs
4697
            };
4698
            set caseBlocks[i] = nil;
4699
        } else {
4700
            let payloadBlock = try createBlock(self, "eq#payload");
4701
            set cases[i] = il::SwitchCase {
4702
                value: i as i64,
4703
                target: *payloadBlock,
4704
                args: &mut []
4705
            };
4706
            set caseBlocks[i] = payloadBlock;
4707
        }
4708
    }
4709
4710
    // Emit switch in @tag block. Default arm is unreachable since we cover all variants.
4711
    let unreachableBlock = try createBlock(self, "eq#unreachable");
4712
    try switchToAndSeal(self, tagBlock);
4713
    emit(self, il::Instr::Switch {
4714
        val: tagA,
4715
        defaultTarget: *unreachableBlock,
4716
        defaultArgs: &mut [],
4717
        cases
4718
    });
4719
4720
    // Add predecessor edges for switch targets.
4721
    addPredecessor(self, unreachableBlock, tagBlock);
4722
    for i in 0..unionInfo.variants.len {
4723
        if let caseBlock = caseBlocks[i] {
4724
            addPredecessor(self, caseBlock, tagBlock);
4725
        } else {
4726
            addPredecessor(self, mergeBlock, tagBlock);
4727
        }
4728
    }
4729
    let valOffset = unionInfo.valOffset as i32;
4730
4731
    // Emit payload comparison blocks for non-void variants.
4732
    for variant, i in unionInfo.variants {
4733
        if let caseBlock = caseBlocks[i] {
4734
            try switchToAndSeal(self, caseBlock);
4735
            let payloadEq = try emitEqAtOffset(
4736
                self, a, b, offset + valOffset, variant.valueType
4737
            );
4738
            try emitJmpWithArg(self, mergeBlock, payloadEq);
4739
        }
4740
    }
4741
    // Emit unreachable block.
4742
    try switchToAndSeal(self, unreachableBlock);
4743
    emit(self, il::Instr::Unreachable);
4744
4745
    try switchToAndSeal(self, mergeBlock);
4746
    return il::Val::Reg(resultReg);
4747
}
4748
4749
/// Compare two array values for equality, element by element.
4750
unsafe fn lowerArrayEq(
4751
    self: &mut FnLowerer,
4752
    arr: resolver::ArrayType,
4753
    a: il::Reg,
4754
    b: il::Reg,
4755
    offset: i32
4756
) -> il::Val throws (LowerError) {
4757
    let elemLayout = resolver::getTypeLayout(*arr.item);
4758
    let stride = elemLayout.size as i32;
4759
    let mut result: ?il::Val = nil;
4760
4761
    for i in 0..arr.length {
4762
        let elemOffset = offset + (i as i32) * stride;
4763
        let cmp = try emitEqAtOffset(self, a, b, elemOffset, *arr.item);
4764
        set result = emitLogicalAnd(self, result, cmp);
4765
    }
4766
    if let r = result {
4767
        return r;
4768
    }
4769
    // Empty arrays are always equal.
4770
    return il::Val::Imm(1);
4771
}
4772
4773
/// Compare two aggregate values for equality.
4774
unsafe fn lowerAggregateEq(
4775
    self: &mut FnLowerer,
4776
    typ: resolver::Type,
4777
    a: il::Reg,
4778
    b: il::Reg,
4779
    offset: i32
4780
) -> il::Val throws (LowerError) {
4781
    match typ {
4782
        case resolver::Type::Slice { item, mutable, .. } =>
4783
            return try lowerSliceEq(self, item, mutable, a, b, offset),
4784
        case resolver::Type::Optional(inner) => {
4785
            if let case resolver::Type::Slice { item, mutable, .. } = *inner {
4786
                // Optional slices use null pointer optimization.
4787
                return try lowerSliceEq(self, item, mutable, a, b, offset);
4788
            }
4789
            return try lowerOptionalEq(self, *inner, a, b, offset);
4790
        }
4791
        case resolver::Type::Array(arr) =>
4792
            return try lowerArrayEq(self, arr, a, b, offset),
4793
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) =>
4794
            return try lowerRecordEq(self, recInfo, a, b, offset),
4795
        case resolver::Type::Nominal(resolver::NominalType::Union(unionInfo)) =>
4796
            return try lowerUnionEq(self, unionInfo, a, b, offset),
4797
        else => {
4798
            let recInfo = recordInfoFromType(typ) else {
4799
                throw LowerError::ExpectedRecord;
4800
            };
4801
            return try lowerRecordEq(self, recInfo, a, b, offset);
4802
        }
4803
    }
4804
}
4805
4806
/// Lower a record literal expression. Handles both plain records and union variant
4807
/// record literals like `Union::Variant { field: value }`.
4808
unsafe fn lowerRecordLit(self: &mut FnLowerer, node: *ast::Node, lit: ast::RecordLit) -> il::Val throws (LowerError) {
4809
    let typ = try typeOf(self, node);
4810
    match typ {
4811
        case resolver::Type::Nominal(resolver::NominalType::Record(recInfo)) => {
4812
            let dst = try emitReserve(self, typ);
4813
            try lowerRecordFields(self, dst, &recInfo, lit.fields, 0);
4814
4815
            return il::Val::Reg(dst);
4816
        }
4817
        case resolver::Type::Nominal(resolver::NominalType::Union(_)) => {
4818
            let typeName = lit.typeName else {
4819
                throw LowerError::ExpectedVariant;
4820
            };
4821
            let sym = try symOf(self, typeName);
4822
            let case resolver::SymbolData::Variant { type: payloadType, index, .. } = sym.data else {
4823
                throw LowerError::ExpectedVariant;
4824
            };
4825
            let recInfo = recordInfoFromType(payloadType) else {
4826
                throw LowerError::ExpectedRecord;
4827
            };
4828
            let unionInfo = unionInfoFromType(typ) else {
4829
                throw LowerError::MissingMetadata;
4830
            };
4831
            let valOffset = unionInfo.valOffset as i32;
4832
            let dst = try emitReserve(self, typ);
4833
4834
            emitStoreW8At(self, il::Val::Imm(index as i64), dst, TVAL_TAG_OFFSET);
4835
            try lowerRecordFields(self, dst, &recInfo, lit.fields, valOffset);
4836
4837
            return il::Val::Reg(dst);
4838
        }
4839
        else => throw LowerError::UnexpectedType(typ),
4840
    }
4841
}
4842
4843
/// Lower fields of a record literal into a destination register.
4844
/// The `offset` is added to each field's offset when storing.
4845
unsafe fn lowerRecordFields(
4846
    self: &mut FnLowerer,
4847
    dst: il::Reg,
4848
    recInfo: &resolver::RecordType,
4849
    fields: *[*ast::Node],
4850
    offset: i32
4851
) throws (LowerError) {
4852
    for fieldNode, i in fields {
4853
        let case ast::NodeValue::RecordLitField(field) = fieldNode.value else {
4854
            throw LowerError::UnexpectedNodeValue(fieldNode);
4855
        };
4856
        let mut fieldIdx: u32 = i;
4857
        if recInfo.labeled {
4858
            let idx = resolver::recordFieldIndexFor(self.low.resolver, fieldNode) else {
4859
                throw LowerError::MissingMetadata;
4860
            };
4861
            set fieldIdx = idx;
4862
        }
4863
        // Skip `undefined` fields, they need no initialization.
4864
        // Emitting a blit from an uninitialised reserve produces a
4865
        // phantom SSA source value that the backend cannot handle.
4866
        if not isUndef(field.value) {
4867
            let fieldTy = recInfo.fields[fieldIdx].fieldType;
4868
            let fieldVal = try lowerExpr(self, field.value);
4869
            try emitStore(self, dst, offset + recInfo.fields[fieldIdx].offset, fieldTy, fieldVal);
4870
        }
4871
    }
4872
}
4873
4874
/// Lower an unlabeled record constructor call.
4875
unsafe fn lowerRecordCtor(self: &mut FnLowerer, nominal: *unsafe resolver::NominalType, args: *[*ast::Node]) -> il::Val throws (LowerError) {
4876
    let case resolver::NominalType::Record(recInfo) = *nominal else {
4877
        throw LowerError::ExpectedRecord;
4878
    };
4879
    let typ = resolver::Type::Nominal(nominal);
4880
    let dst = try emitReserve(self, typ);
4881
4882
    for argNode, i in args {
4883
        // Skip `undefined` arguments.
4884
        if not isUndef(argNode) {
4885
            let fieldTy = recInfo.fields[i].fieldType;
4886
            let argVal = try lowerExpr(self, argNode);
4887
            try emitStore(self, dst, recInfo.fields[i].offset, fieldTy, argVal);
4888
        }
4889
    }
4890
    return il::Val::Reg(dst);
4891
}
4892
4893
/// Lower an array literal expression like `[1, 2, 3]`.
4894
unsafe fn lowerArrayLit(self: &mut FnLowerer, node: *ast::Node, elements: *[*ast::Node]) -> il::Val
4895
    throws (LowerError)
4896
{
4897
    let typ = try typeOf(self, node);
4898
    let case resolver::Type::Array(arrInfo) = typ else {
4899
        throw LowerError::ExpectedArray;
4900
    };
4901
    let elemTy = *arrInfo.item;
4902
    let elemLayout = resolver::getTypeLayout(elemTy);
4903
    let dst = try emitReserve(self, typ);
4904
4905
    for elemNode, i in elements {
4906
        let elemVal = try lowerExpr(self, elemNode);
4907
        let offset = i * elemLayout.size;
4908
4909
        try emitStore(self, dst, offset as i32, elemTy, elemVal);
4910
    }
4911
    return il::Val::Reg(dst);
4912
}
4913
4914
/// Lower an array repeat literal expression like `[42; 3]`.
4915
/// Unrolls the initialization at compile time.
4916
// TODO: Beyond a certain length, lower this to a loop.
4917
unsafe fn lowerArrayRepeatLit(self: &mut FnLowerer, node: *ast::Node, repeat: ast::ArrayRepeatLit) -> il::Val
4918
    throws (LowerError)
4919
{
4920
    let typ = try typeOf(self, node);
4921
    let case resolver::Type::Array(arrInfo) = typ else {
4922
        throw LowerError::ExpectedArray;
4923
    };
4924
    let elemTy = *arrInfo.item;
4925
    let length = arrInfo.length;
4926
    let elemLayout = resolver::getTypeLayout(elemTy);
4927
    let dst = try emitReserve(self, typ);
4928
4929
    // Evaluate the repeated item once.
4930
    let repeatVal = try lowerExpr(self, repeat.item);
4931
4932
    // Unroll: store at each offset.
4933
    for i in 0..length {
4934
        let offset = i * elemLayout.size;
4935
        try emitStore(self, dst, offset as i32, elemTy, repeatVal);
4936
    }
4937
    return il::Val::Reg(dst);
4938
}
4939
4940
/// Lower a union constructor call like `Union::Variant(...)`.
4941
unsafe fn lowerUnionCtor(self: &mut FnLowerer, node: *ast::Node, sym: *unsafe mut resolver::Symbol, call: ast::Call) -> il::Val
4942
    throws (LowerError)
4943
{
4944
    let unionTy = try typeOf(self, node);
4945
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } = sym.data else {
4946
        throw LowerError::ExpectedVariant;
4947
    };
4948
    let unionInfo = unionInfoFromType(unionTy) else {
4949
        throw LowerError::MissingMetadata;
4950
    };
4951
    let valOffset = unionInfo.valOffset as i32;
4952
    let mut payloadVal: ?il::Val = nil;
4953
    if payloadType <> resolver::Type::Void {
4954
        let case resolver::Type::Nominal(payloadNominal) = payloadType else {
4955
            throw LowerError::MissingMetadata;
4956
        };
4957
        set payloadVal = try lowerRecordCtor(self, payloadNominal, call.args);
4958
    }
4959
    return try buildTagged(self, resolver::getTypeLayout(unionTy), index as i64, payloadVal, payloadType, 1, valOffset);
4960
}
4961
4962
/// Lower a field access into a pointer to the field.
4963
unsafe fn lowerFieldRef(self: &mut FnLowerer, access: ast::Access) -> FieldRef throws (LowerError) {
4964
    let parentTy = try typeOf(self, access.parent);
4965
    let subjectTy = resolver::autoDeref(parentTy);
4966
    let fieldIdx = resolver::recordFieldIndexFor(self.low.resolver, access.child) else {
4967
        throw LowerError::MissingMetadata;
4968
    };
4969
    let fieldInfo = resolver::getRecordField(subjectTy, fieldIdx) else {
4970
        throw LowerError::FieldNotFound;
4971
    };
4972
    let baseVal = try lowerExpr(self, access.parent);
4973
    let baseReg = emitValToReg(self, baseVal);
4974
4975
    return FieldRef {
4976
        base: baseReg,
4977
        offset: fieldInfo.offset,
4978
        fieldType: fieldInfo.fieldType,
4979
    };
4980
}
4981
4982
/// Lower a field access expression.
4983
unsafe fn lowerFieldAccess(self: &mut FnLowerer, access: ast::Access) -> il::Val throws (LowerError) {
4984
    let fieldRef = try lowerFieldRef(self, access);
4985
    return emitRead(self, fieldRef.base, fieldRef.offset, fieldRef.fieldType);
4986
}
4987
4988
/// Compute data pointer and element count for a range into a container.
4989
/// Used by both slice range expressions (`&a[start..end]`) and slice
4990
/// assignments (`a[start..end] = value`).
4991
unsafe fn resolveSliceRangePtr(
4992
    self: &mut FnLowerer,
4993
    container: *ast::Node,
4994
    range: ast::Range,
4995
    info: resolver::SliceRangeInfo
4996
) -> SliceRangeResult throws (LowerError) {
4997
    let baseVal = try lowerExpr(self, container);
4998
    let baseReg = emitValToReg(self, baseVal);
4999
5000
    // Extract data pointer and container length.
5001
    let mut dataReg = baseReg;
5002
    let mut containerLen: il::Val = undefined;
5003
    if let cap = info.capacity { // Slice from array.
5004
        set containerLen = il::Val::Imm(cap as i64);
5005
    } else { // Slice from slice.
5006
        set dataReg = loadSlicePtr(self, baseReg);
5007
        set containerLen = loadSliceLen(self, baseReg);
5008
    }
5009
5010
    // Compute range bounds.
5011
    let mut startVal: il::Val = il::Val::Imm(0);
5012
    if let start = range.start {
5013
        set startVal = try lowerExpr(self, start);
5014
    }
5015
    let mut endVal = containerLen;
5016
    if let end = range.end {
5017
        set endVal = try lowerExpr(self, end);
5018
    }
5019
5020
    // Runtime slice bounds checks for dynamic range expressions.
5021
    if not isLtEq(startVal, containerLen) {
5022
        try emitTrapIfLt(self, il::Type::W32, containerLen, startVal);
5023
    }
5024
    if not isLtEq(endVal, containerLen) {
5025
        try emitTrapIfLt(self, il::Type::W32, containerLen, endVal);
5026
    }
5027
    if startVal <> il::Val::Imm(0) and endVal <> containerLen and not isLtEq(startVal, endVal) {
5028
        try emitTrapIfLt(self, il::Type::W32, endVal, startVal);
5029
    }
5030
5031
    // If the start value is known to be zero, the count is just the end
5032
    // value. Otherwise, we have to compute it.
5033
    let mut count = endVal;
5034
5035
    // Only compute range offset and count if the start value is not
5036
    // statically known to be zero.
5037
    if startVal <> il::Val::Imm(0) {
5038
        // Offset the data pointer by the start value.
5039
        set dataReg = emitElem(
5040
            self, resolver::getTypeLayout(*info.itemType).size, dataReg, startVal
5041
        );
5042
        // Compute the count as `end - start`.
5043
        let lenReg = nextReg(self);
5044
        emit(self, il::Instr::BinOp {
5045
            op: il::BinOp::Sub,
5046
            typ: il::Type::W32,
5047
            dst: lenReg,
5048
            a: endVal,
5049
            b: startVal,
5050
        });
5051
        set count = il::Val::Reg(lenReg);
5052
    }
5053
    return SliceRangeResult { dataReg, count };
5054
}
5055
5056
/// Lower a slice range expression into a slice header value.
5057
unsafe fn lowerSliceRange(
5058
    self: &mut FnLowerer,
5059
    container: *ast::Node,
5060
    range: ast::Range,
5061
    sliceNode: *ast::Node
5062
) -> il::Val throws (LowerError) {
5063
    let info = resolver::sliceRangeInfoFor(self.low.resolver, sliceNode) else {
5064
        throw LowerError::MissingMetadata;
5065
    };
5066
    let r = try resolveSliceRangePtr(self, container, range, info);
5067
    return try buildSliceValue(
5068
        self, info.itemType, info.mutable, il::Val::Reg(r.dataReg), r.count, r.count
5069
    );
5070
}
5071
5072
/// Lower an address-of (`&x`) expression.
5073
unsafe fn lowerAddressOf(self: &mut FnLowerer, node: *ast::Node, addr: ast::AddressOf) -> il::Val throws (LowerError) {
5074
    // Handle subscript: `&ary[i]` or `&ary[start..end]`.
5075
    if let case ast::NodeValue::Subscript { container, index } = addr.target.value {
5076
        if let case ast::NodeValue::Range(range) = index.value {
5077
            return try lowerSliceRange(self, container, range, node);
5078
        }
5079
        let result = try lowerElemPtr(self, container, index);
5080
5081
        return il::Val::Reg(result.elemReg);
5082
    }
5083
    // Handle field address: `&x.field`.
5084
    if let case ast::NodeValue::FieldAccess(access) = addr.target.value {
5085
        let fieldRef = try lowerFieldRef(self, access);
5086
        let ptr = emitPtrOffset(self, fieldRef.base, fieldRef.offset);
5087
5088
        return il::Val::Reg(ptr);
5089
    }
5090
    // Handle variable address: `&x`
5091
    if let case ast::NodeValue::Ident(_) = addr.target.value {
5092
        if let v = lookupLocalVar(self, addr.target) {
5093
            let val = try useVar(self, v);
5094
            let typ = try typeOf(self, addr.target);
5095
            // For aggregates, the value is already a pointer.
5096
            if isAggregateType(typ) {
5097
                return val;
5098
            }
5099
            // For scalars, if we've already materialized a stack slot for this
5100
            // variable, the SSA value is that slot pointer.
5101
            if self.vars[*v].addressTaken {
5102
                // Already address-taken; return existing stack pointer.
5103
                return val;
5104
            }
5105
            // Materialize a stack slot using the declaration's resolved
5106
            // layout so `align(N)` on locals is honored.
5107
            let layout = resolver::getLayout(self.low.resolver, addr.target, typ);
5108
            let slot = emitReserveLayout(self, layout);
5109
            try emitStore(self, slot, 0, typ, val);
5110
            let stackVal = il::Val::Reg(slot);
5111
5112
            set self.vars[*v].addressTaken = true;
5113
            defVar(self, v, stackVal);
5114
5115
            return stackVal;
5116
        }
5117
        // Fall back to symbol lookup for constants/statics.
5118
        if let sym = resolver::nodeData(self.low.resolver, addr.target).sym {
5119
            return il::Val::Reg(emitDataAddr(self, sym));
5120
        } else {
5121
            throw LowerError::MissingSymbol(node);
5122
        }
5123
    }
5124
    // Handle dereference address: `&(*ptr) = ptr`.
5125
    if let case ast::NodeValue::Deref(target) = addr.target.value {
5126
        return try lowerExpr(self, target);
5127
    }
5128
    // Array literals become slices when their address is taken.
5129
    match addr.target.value {
5130
        case ast::NodeValue::ArrayLit(_),
5131
             ast::NodeValue::ArrayRepeatLit(_) =>
5132
        {
5133
            return try lowerArrayLiteralSlice(self, node, addr.target);
5134
        }
5135
        else => {}
5136
    }
5137
    throw LowerError::UnexpectedNodeValue(addr.target);
5138
}
5139
5140
/// Lower an addressed array literal as a slice.
5141
unsafe fn lowerArrayLiteralSlice(
5142
    self: &mut FnLowerer,
5143
    sliceNode: *ast::Node,
5144
    arrayNode: *ast::Node
5145
) -> il::Val throws (LowerError) {
5146
    let sliceTy = try typeOf(self, sliceNode);
5147
    let case resolver::Type::Slice { item, mutable, .. } = sliceTy else {
5148
        throw LowerError::UnexpectedType(sliceTy);
5149
    };
5150
    let arrayTy = try typeOf(self, arrayNode);
5151
    let case resolver::Type::Array(arrayInfo) = arrayTy else {
5152
        throw LowerError::ExpectedArray;
5153
    };
5154
    let length = arrayInfo.length;
5155
    if length == 0 {
5156
        return try buildSliceValue(
5157
            self, item, mutable, il::Val::Imm(0), il::Val::Imm(0), il::Val::Imm(0)
5158
        );
5159
    }
5160
    if resolver::isConstExpr(self.low.resolver, arrayNode) {
5161
        let fnName = self.fnName;
5162
        let mut b = dataBuilder(self.low.allocator);
5163
        match arrayNode.value {
5164
            case ast::NodeValue::ArrayLit(elements) =>
5165
                try lowerConstArrayLitInto(self.low, elements, arrayTy, fnName, &mut b),
5166
            case ast::NodeValue::ArrayRepeatLit(repeat) =>
5167
                try lowerConstArrayRepeatInto(self.low, repeat, arrayTy, fnName, &mut b),
5168
            else => throw LowerError::UnexpectedNodeValue(arrayNode),
5169
        }
5170
        let result = dataBuilderFinish(b);
5171
        let alignment = resolver::getTypeLayout(*item).alignment;
5172
        return try lowerConstDataAsSlice(
5173
            self, &result, alignment, not mutable,
5174
            item, mutable, length
5175
        );
5176
    }
5177
    let data = try lowerExpr(self, arrayNode);
5178
    let count = il::Val::Imm(length as i64);
5179
    return try buildSliceValue(self, item, mutable, data, count, count);
5180
}
5181
5182
/// Lower the common element pointer computation for subscript operations.
5183
/// Handles both arrays and slices by resolving the container type, extracting
5184
/// the data pointer (for slices), and emitting an [`il::Instr::Elem`] to compute
5185
/// the element address.
5186
unsafe fn lowerElemPtr(
5187
    self: &mut FnLowerer, container: *ast::Node, index: *ast::Node
5188
) -> ElemPtrResult throws (LowerError) {
5189
    let containerTy = try typeOf(self, container);
5190
    let subjectTy = resolver::autoDeref(containerTy);
5191
    let baseVal = try lowerExpr(self, container);
5192
    let indexVal = try lowerExpr(self, index);
5193
    let baseReg = emitValToReg(self, baseVal);
5194
5195
    let mut dataReg = baseReg;
5196
    let mut elemType: resolver::Type = undefined;
5197
5198
    match subjectTy {
5199
        case resolver::Type::Slice { item, .. } => {
5200
            set elemType = *item;
5201
            let sliceLen = loadSliceLen(self, baseReg);
5202
            // Runtime safety check: index must be strictly less than slice length.
5203
            try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, indexVal, sliceLen);
5204
5205
            set dataReg = loadSlicePtr(self, baseReg);
5206
        }
5207
        case resolver::Type::Array(arrInfo) => {
5208
            set elemType = *arrInfo.item;
5209
            // Runtime safety check: index must be strictly less than array length.
5210
            // Skip when the index is a compile-time constant, since we check
5211
            // that in the resolver.
5212
            if not resolver::isConstExpr(self.low.resolver, index) {
5213
                let arrLen = il::Val::Imm(arrInfo.length as i64);
5214
                try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, indexVal, arrLen);
5215
            }
5216
        }
5217
        else => throw LowerError::ExpectedSliceOrArray,
5218
    }
5219
    let elemLayout = resolver::getTypeLayout(elemType);
5220
    let elemReg = emitElem(self, elemLayout.size, dataReg, indexVal);
5221
5222
    return ElemPtrResult { elemReg, elemType };
5223
}
5224
5225
/// Lower a dereference expression.
5226
/// Handles both pointer deref (`*ptr`) and record deref (`*r` on single-field
5227
/// unlabeled record). Both read at offset 0 using the resolver-assigned type.
5228
unsafe fn lowerDeref(self: &mut FnLowerer, node: *ast::Node, target: *ast::Node) -> il::Val throws (LowerError) {
5229
    let type = try typeOf(self, node);
5230
    let ptrVal = try lowerExpr(self, target);
5231
    let ptrReg = emitValToReg(self, ptrVal);
5232
5233
    return emitRead(self, ptrReg, 0, type);
5234
}
5235
5236
/// Lower a subscript expression.
5237
unsafe fn lowerSubscript(self: &mut FnLowerer, node: *ast::Node, container: *ast::Node, index: *ast::Node) -> il::Val
5238
    throws (LowerError)
5239
{
5240
    if let case ast::NodeValue::Range(_) = index.value {
5241
        panic "lowerSubscript: range subscript must use address-of (&)";
5242
    }
5243
    let result = try lowerElemPtr(self, container, index);
5244
5245
    return emitRead(self, result.elemReg, 0, result.elemType);
5246
}
5247
5248
/// Lower a let binding.
5249
unsafe fn lowerLet(self: &mut FnLowerer, node: *ast::Node, l: ast::Let) throws (LowerError) {
5250
    // Evaluate value.
5251
    let val = try lowerExpr(self, l.value);
5252
    if blockHasTerminator(self) {
5253
        return;
5254
    }
5255
    // Handle placeholder pattern: `let _ = expr;`
5256
    if let case ast::NodeValue::Placeholder = l.ident.value {
5257
        return;
5258
    }
5259
    let case ast::NodeValue::Ident(name) = l.ident.value else {
5260
        throw LowerError::ExpectedIdentifier;
5261
    };
5262
    let typ = try typeOf(self, l.value);
5263
    let ilType = ilType(self.low, typ);
5264
    let mut varVal = val;
5265
5266
    // Aggregates with persistent storage need a local copy to avoid aliasing.
5267
    // Temporaries such as literals or call results can be adopted directly.
5268
    // This is because aggregates are represented as memory addresses
5269
    // internally, even though they have value semantics, so without an explicit
5270
    // copy, only the address is is written. Function calls on the other hand
5271
    // reserve their own local stack space, so copying would be redundant.
5272
    // Void variant literals (e.g. `Option::None`) use scope access syntax and
5273
    // are flagged as place expressions, but they are freshly constructed
5274
    // temporaries with no persistent storage.
5275
    if isAggregateType(typ) and
5276
        ast::isPlaceExpr(l.value) and
5277
        voidVariantIndex(self.low.resolver, l.value) == nil {
5278
        set varVal = try emitStackVal(self, typ, val);
5279
    }
5280
5281
    // If the resolver determined that this variable's address is taken
5282
    // anywhere in the function, allocate a stack slot immediately so the
5283
    // SSA value is always a pointer. This avoids mixing integer and pointer
5284
    // values in loop phis when `&var` or `&mut var` appears inside a loop.
5285
    if not isAggregateType(typ) {
5286
        if let sym = resolver::nodeData(self.low.resolver, node).sym {
5287
            if let case resolver::SymbolData::Value { addressTaken, .. } = sym.data; addressTaken {
5288
                let layout = resolver::getLayout(self.low.resolver, node, typ);
5289
                let slot = emitReserveLayout(self, layout);
5290
                try emitStore(self, slot, 0, typ, varVal);
5291
5292
                let v = newVar(self, name, ilType, l.mutable, il::Val::Reg(slot));
5293
                set self.vars[*v].addressTaken = true;
5294
5295
                return;
5296
            }
5297
        }
5298
    }
5299
    let _ = newVar(self, name, ilType, l.mutable, varVal);
5300
}
5301
5302
/// Lower an if statement: `if <cond> { <then> } else { <else> }`.
5303
///
5304
/// With else branch:
5305
///
5306
///     @entry -> (true)  @then ---> @merge <--.
5307
///         |                                   )
5308
///         `---> (false) @else ---------------'
5309
///
5310
/// Without else branch:
5311
///
5312
///     @entry -> (true)  @then ---> @end <--.
5313
///         |                                 )
5314
///         `---- (false) -------------------'
5315
///
5316
unsafe fn lowerIf(self: &mut FnLowerer, i: ast::If) throws (LowerError) {
5317
    let thenBlock = try createBlock(self, "then");
5318
5319
    if let elseNode = i.elseBranch { // If-else case.
5320
        let elseBlock = try createBlock(self, "else");
5321
        try emitCondBranch(self, i.condition, thenBlock, elseBlock);
5322
5323
        // Both @then and @else have exactly one predecessor (@entry), so we can
5324
        // seal them immediately.
5325
        try sealBlock(self, thenBlock);
5326
        try sealBlock(self, elseBlock);
5327
5328
        // The merge block is created lazily by [`emitMergeIfUnterminated`]. We
5329
        // only need it if at least one branch doesn't diverge (i.e., needs to
5330
        // continue execution after the `if`). If both branches diverge (eg.
5331
        // both `return`), no merge block is created and control flow
5332
        // doesn't continue past the `if` statement.
5333
        let mut mergeBlock: ?BlockId = nil;
5334
5335
        // Lower the @then block: switch to it, emit its code, then jump to
5336
        // merge if the block doesn't diverge.
5337
        switchToBlock(self, thenBlock);
5338
        try lowerBlock(self, i.thenBranch);
5339
        try emitMergeIfUnterminated(self, &mut mergeBlock);
5340
5341
        // Lower the @else block similarly.
5342
        switchToBlock(self, elseBlock);
5343
        try lowerBlock(self, elseNode);
5344
        try emitMergeIfUnterminated(self, &mut mergeBlock);
5345
5346
        // If a merge block was created (at least one branch flows into it),
5347
        // switch to it for subsequent code. The merge block's predecessors
5348
        // are the branches that jumped to it, so we seal it now.
5349
        // If the merge block is `nil`, both branches diverged and there's no
5350
        // continuation point.
5351
        if let blk = mergeBlock {
5352
            try switchToAndSeal(self, blk);
5353
        }
5354
    } else { // If without `else`.
5355
        // The false branch goes directly to @end, which also serves as the
5356
        // merge point after @then completes.
5357
        let endBlock = try createBlock(self, "merge");
5358
5359
        try emitCondBranch(self, i.condition, thenBlock, endBlock);
5360
5361
        // @then has one predecessor (@entry), seal it immediately.
5362
        // @end is not sealed yet because @then might also jump to it.
5363
        try sealBlock(self, thenBlock);
5364
5365
        // Lower the @then block, then jump to @end and seal it.
5366
        // Unlike the if-else case, @end is always created because there is no
5367
        // else branch that can diverge.
5368
        switchToBlock(self, thenBlock);
5369
        try lowerBlock(self, i.thenBranch);
5370
        try emitJmpAndSeal(self, endBlock);
5371
5372
        // Continue execution at @end.
5373
        try switchToAndSeal(self, endBlock);
5374
    }
5375
}
5376
5377
/// Lower an assignment target that designates a memory location, and return
5378
/// the address to store through. Returns `nil` without emitting anything for
5379
/// targets that aren't memory-backed, such as locals tracked in SSA.
5380
unsafe fn lowerPlace(self: &mut FnLowerer, target: *ast::Node) -> ?FieldRef throws (LowerError) {
5381
    match target.value {
5382
        case ast::NodeValue::ScopeAccess(_) => {
5383
            let sym = try symOf(self, target);
5384
            let case resolver::SymbolData::Value { type, .. } = sym.data else {
5385
                throw LowerError::ImmutableAssignment;
5386
            };
5387
            return FieldRef { base: emitDataAddr(self, sym), offset: 0, fieldType: type };
5388
        }
5389
        case ast::NodeValue::FieldAccess(access) => {
5390
            return try lowerFieldRef(self, access);
5391
        }
5392
        case ast::NodeValue::Deref(pointer) => {
5393
            // Dereference: `*ptr` or `*r` on a single-field unlabeled record.
5394
            // Both address offset 0 using the resolver-assigned type.
5395
            let base = emitValToReg(self, try lowerExpr(self, pointer));
5396
            return FieldRef { base, offset: 0, fieldType: try typeOf(self, target) };
5397
        }
5398
        case ast::NodeValue::Subscript { container, index } => {
5399
            // Array or slice element: `arr[i]`.
5400
            let elem = try lowerElemPtr(self, container, index);
5401
            return FieldRef { base: elem.elemReg, offset: 0, fieldType: elem.elemType };
5402
        }
5403
        else => return nil,
5404
    }
5405
}
5406
5407
/// Lower a compound assignment whose target is memory-backed, and report
5408
/// whether it was handled. Nothing is emitted when it isn't.
5409
///
5410
/// Compound assignments share their target node with the left operand of the
5411
/// desugared binary expression. Resolve that place once so side effects in a
5412
/// dereference, field parent, or subscript index are not repeated for the store.
5413
unsafe fn lowerCompoundAssign(
5414
    self: &mut FnLowerer, expr: *ast::Node, binop: ast::BinOp
5415
) -> bool throws (LowerError) {
5416
    let place = try lowerPlace(self, binop.left) else return false;
5417
    let current = emitRead(self, place.base, place.offset, place.fieldType);
5418
    let left = try applyCoercion(self, binop.left, current);
5419
    let right = try lowerExpr(self, binop.right);
5420
    let exprType = try typeOf(self, expr);
5421
    let result = emitScalarBinOp(
5422
        self, binop.op, ilType(self.low, exprType), left, right, isUnsignedType(exprType)
5423
    );
5424
    let assigned = try applyCoercion(self, expr, result);
5425
    try emitStore(self, place.base, place.offset, place.fieldType, assigned);
5426
5427
    return true;
5428
}
5429
5430
/// Lower an assignment statement.
5431
unsafe fn lowerAssign(self: &mut FnLowerer, node: *ast::Node, a: ast::Assign) throws (LowerError) {
5432
    // Slice assignment: `slice[range] = value`.
5433
    if let info = resolver::sliceRangeInfoFor(self.low.resolver, node) {
5434
        let case ast::NodeValue::Subscript { container, index } = a.left.value
5435
            else panic "lowerAssign: slice assign without subscript";
5436
        let case ast::NodeValue::Range(range) = index.value
5437
            else panic "lowerAssign: slice assign without range";
5438
        try lowerSliceAssign(self, a.right, container, range, info);
5439
5440
        return;
5441
    }
5442
    // Compound assignments are represented as `target = target op rhs`, with
5443
    // the exact same target node used in both places. Memory-backed targets
5444
    // must be resolved once so calls in the target are evaluated once.
5445
    if let case ast::NodeValue::BinOp(binop) = a.right.value {
5446
        if binop.left == a.left and try lowerCompoundAssign(self, a.right, binop) {
5447
            return;
5448
        }
5449
    }
5450
    // Evaluate assignment value.
5451
    let rhs = try lowerExpr(self, a.right);
5452
5453
    match a.left.value {
5454
        case ast::NodeValue::Ident(_) => {
5455
            // First try local variable lookup.
5456
            if let v = lookupLocalVar(self, a.left) {
5457
                if not getVar(self, v).mutable {
5458
                    throw LowerError::ImmutableAssignment;
5459
                }
5460
                let leftTy = try typeOf(self, a.left);
5461
                if isAggregateType(leftTy) or getVar(self, v).addressTaken {
5462
                    // Aggregates and address-taken scalars are represented as
5463
                    // pointers to stack memory. Store through the pointer.
5464
                    let val = try useVar(self, v);
5465
                    let dst = emitValToReg(self, val);
5466
5467
                    try emitStore(self, dst, 0, leftTy, rhs);
5468
                } else {
5469
                    // Scalars are tracked directly in SSA. Each assignment
5470
                    // records a new SSA value.
5471
                    defVar(self, v, rhs);
5472
                }
5473
            } else {
5474
                // Fall back to static variable assignment.
5475
                try lowerStaticAssign(self, a.left, rhs);
5476
            }
5477
        }
5478
        else => {
5479
            let place = try lowerPlace(self, a.left) else {
5480
                throw LowerError::UnexpectedNodeValue(a.left);
5481
            };
5482
            try emitStore(self, place.base, place.offset, place.fieldType, rhs);
5483
        }
5484
    }
5485
}
5486
5487
/// Lower `slice[range] = value`.
5488
unsafe fn lowerSliceAssign(
5489
    self: &mut FnLowerer,
5490
    rhs: *ast::Node,
5491
    container: *ast::Node,
5492
    range: ast::Range,
5493
    info: resolver::SliceRangeInfo
5494
) throws (LowerError) {
5495
    let r = try resolveSliceRangePtr(self, container, range, info);
5496
    let elemSize = resolver::getTypeLayout(*info.itemType).size;
5497
    let rhsTy = try typeOf(self, rhs);
5498
5499
    if let case resolver::Type::Slice { .. } = rhsTy {
5500
        // Copy from source slice.
5501
        let srcReg = emitValToReg(self, try lowerExpr(self, rhs));
5502
        let srcData = loadSlicePtr(self, srcReg);
5503
        let srcLen = loadSliceLen(self, srcReg);
5504
5505
        // Trap if source and destination lengths differ.
5506
        try emitTrapUnlessCmp(self, il::CmpOp::Eq, il::Type::W32, r.count, srcLen);
5507
5508
        let bytes = emitTypedBinOp(
5509
            self, il::BinOp::Mul, il::Type::W32, r.count, il::Val::Imm(elemSize as i64)
5510
        );
5511
        try emitByteCopyLoop(self, r.dataReg, srcData, bytes, "copy");
5512
    } else {
5513
        // Fill with scalar value.
5514
        let fillVal = try lowerExpr(self, rhs);
5515
        try emitFillLoop(self, r.dataReg, fillVal, r.count, *info.itemType, elemSize);
5516
    }
5517
}
5518
5519
/// Emit a typed fill loop: `for i in 0..count { dst[i * stride] = value; }`.
5520
unsafe fn emitFillLoop(
5521
    self: &mut FnLowerer,
5522
    dst: il::Reg,
5523
    value: il::Val,
5524
    count: il::Val,
5525
    elemType: resolver::Type,
5526
    elemSize: u32
5527
) throws (LowerError) {
5528
    let iReg = nextReg(self);
5529
    let header = try createBlockWithParam(
5530
        self, "fill", il::Param { value: iReg, type: il::Type::W32 }
5531
    );
5532
    let body = try createBlock(self, "fill");
5533
    let done = try createBlock(self, "fill");
5534
5535
    try emitJmpWithArg(self, header, il::Val::Imm(0));
5536
    switchToBlock(self, header);
5537
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, il::Val::Reg(iReg), count, body, done);
5538
5539
    try switchToAndSeal(self, body);
5540
    let dstElem = emitElem(self, elemSize, dst, il::Val::Reg(iReg));
5541
    try emitStore(self, dstElem, 0, elemType, value);
5542
5543
    let nextI = emitTypedBinOp(
5544
        self, il::BinOp::Add, il::Type::W32, il::Val::Reg(iReg), il::Val::Imm(1)
5545
    );
5546
    try emitJmpWithArg(self, header, nextI);
5547
    try sealBlock(self, header);
5548
    try switchToAndSeal(self, done);
5549
}
5550
5551
///////////////////
5552
// Loop Lowering //
5553
///////////////////
5554
5555
// All loop forms are lowered to a common structure:
5556
//
5557
// - Loop header block: evaluates condition if any, branches to body or exit.
5558
// - Body block: executes loop body, may contain break/continue.
5559
// - Step block (for `for` loops): increments counter, jumps back to header.
5560
// - Exit block: target for break statements and normal loop exit.
5561
//
5562
// The loop stack tracks break/continue targets for nested loops.
5563
5564
/// Lower an infinite loop: `loop { <body> }`.
5565
///
5566
///   @entry -> @loop -> @loop
5567
///               |
5568
///               `----> @end
5569
///
5570
unsafe fn lowerLoop(self: &mut FnLowerer, body: *ast::Node) throws (LowerError) {
5571
    let loopBlock = try createBlock(self, "loop");
5572
    let endBlock = try createBlock(self, "merge");
5573
5574
    // Enter the loop with the given break and continue targets.
5575
    // `break` jumps to `endBlock`,
5576
    // `continue` jumps to `loopBlock`.
5577
    enterLoop(self, endBlock, loopBlock);
5578
    // Switch to and jump to the loop block, then lower all loop body statements into it.
5579
    try switchAndJumpTo(self, loopBlock);
5580
    try lowerBlock(self, body);
5581
5582
    // If the loop body doesn't diverge, jump back to the start.
5583
    // This creates the infinite loop.
5584
    // All predecessors are known, we can seal the loop block.
5585
    try emitJmpAndSeal(self, loopBlock);
5586
    // Exit the loop.
5587
    exitLoop(self);
5588
5589
    // Only seal end block if it's actually reachable (ie. has predecessors).
5590
    // If the loop has no breaks and only exits via return, the end block
5591
    // remains unreachable and isn't added to the CFG.
5592
    if getBlock(self, endBlock).preds.len > 0 {
5593
        try switchToAndSeal(self, endBlock);
5594
    }
5595
}
5596
5597
/// Lower a while loop: `while <cond> { <body> }`.
5598
///
5599
///   @entry -> @loop -> (true)  @body -> @loop
5600
///               |
5601
///               `----> (false) @end
5602
///
5603
unsafe fn lowerWhile(self: &mut FnLowerer, w: ast::While) throws (LowerError) {
5604
    let whileBlock = try createBlock(self, "while");
5605
    let bodyBlock = try createBlock(self, "body");
5606
    let endBlock = try createBlock(self, "merge");
5607
5608
    enterLoop(self, endBlock, whileBlock);
5609
5610
    // Loop condition.
5611
    try switchAndJumpTo(self, whileBlock);
5612
5613
    // Based on the condition, either jump to the body,
5614
    // or to the end of the loop.
5615
    try emitCondBranch(self, w.condition, bodyBlock, endBlock);
5616
5617
    // Lower loop body and jump back to loop condition check.
5618
    try switchToAndSeal(self, bodyBlock);
5619
    try lowerBlock(self, w.body);
5620
    try emitJmpAndSeal(self, whileBlock);
5621
5622
    try switchToAndSeal(self, endBlock);
5623
    exitLoop(self);
5624
}
5625
5626
/// Emit an increment of a variable by `1`.
5627
unsafe fn emitIncrement(self: &mut FnLowerer, v: Var, typ: il::Type) throws (LowerError) {
5628
    let cur = try useVar(self, v);
5629
    let next = nextReg(self);
5630
5631
    emit(self, il::Instr::BinOp { op: il::BinOp::Add, typ, dst: next, a: cur, b: il::Val::Imm(1) });
5632
    defVar(self, v, il::Val::Reg(next));
5633
}
5634
5635
/// Common for-loop lowering for both range and collection iterators.
5636
///
5637
/// The step block is created lazily (after the loop body) so that it gets
5638
/// a block index higher than all body blocks. This ensures the register
5639
/// allocator processes definitions before uses in forward block order,
5640
/// avoiding stale assignments when a value defined deep in the body flows
5641
/// through the step block as a block argument.
5642
unsafe fn lowerForLoop(self: &mut FnLowerer, iter: &ForIter, body: *ast::Node) throws (LowerError) {
5643
    let loopBlock = try createBlock(self, "loop");
5644
    let bodyBlock = try createBlock(self, "body");
5645
    let endBlock = try createBlock(self, "merge");
5646
5647
    enterLoop(self, endBlock, nil);
5648
    try switchAndJumpTo(self, loopBlock);
5649
5650
    // Emit condition check.
5651
    match *iter {
5652
        case ForIter::Range { valVar, endVal, valType, unsigned, .. } => {
5653
            let curVal = try useVar(self, valVar);
5654
            let cmp = il::CmpOp::Ult if unsigned else il::CmpOp::Slt;
5655
            try emitBrCmp(self, cmp, valType, curVal, endVal, bodyBlock, endBlock);
5656
        }
5657
        case ForIter::Collection { idxVar, lengthVal, .. } => {
5658
            let curIdx = try useVar(self, idxVar);
5659
            try emitBrCmp(self, il::CmpOp::Slt, il::Type::W32, curIdx, lengthVal, bodyBlock, endBlock);
5660
        }
5661
    }
5662
    // Switch to loop body.
5663
    try switchToAndSeal(self, bodyBlock);
5664
5665
    // Emit element binding, only for collections.
5666
    // Reads the element at the current index.
5667
    if let case ForIter::Collection { valVar, idxVar, dataReg, elemType, .. } = *iter {
5668
        if let v = valVar {
5669
            let curIdx = try useVar(self, idxVar);
5670
            let elemReg = emitElem(self, resolver::getTypeLayout(*elemType).size, dataReg, curIdx);
5671
            let val = emitRead(self, elemReg, 0, *elemType);
5672
5673
            defVar(self, v, val);
5674
        }
5675
    }
5676
    // Lower the loop body.
5677
    try lowerBlock(self, body);
5678
5679
    // Check if a `continue` statement created a step block.
5680
    let ctx = currentLoop(self) else panic;
5681
    if let stepBlock = ctx.continueTarget {
5682
        // Body has `continue` statements: jump to step block, emit increment there.
5683
        try emitJmpAndSeal(self, stepBlock);
5684
        switchToBlock(self, stepBlock);
5685
    }
5686
    // Otherwise, emit increment directly in the current block,
5687
    // saving the jump to a separate step block.
5688
    if not blockHasTerminator(self) {
5689
        match *iter {
5690
            case ForIter::Range { valVar, valType, indexVar, .. } => {
5691
                try emitIncrement(self, valVar, valType);
5692
                if let idxVar = indexVar {
5693
                    try emitIncrement(self, idxVar, il::Type::W32);
5694
                }
5695
            }
5696
            case ForIter::Collection { idxVar, .. } => {
5697
                try emitIncrement(self, idxVar, il::Type::W32);
5698
            }
5699
        }
5700
        try emitJmp(self, loopBlock);
5701
    }
5702
    exitLoop(self);
5703
5704
    try sealBlock(self, loopBlock);
5705
    try sealBlock(self, endBlock);
5706
5707
    switchToBlock(self, endBlock);
5708
}
5709
5710
/// Lower a `for` loop over a range, array, or slice.
5711
unsafe fn lowerFor(self: &mut FnLowerer, node: *ast::Node, f: ast::For) throws (LowerError) {
5712
    let savedVarsLen = enterVarScope(self);
5713
    let info = resolver::forLoopInfoFor(self.low.resolver, node) else {
5714
        throw LowerError::MissingMetadata;
5715
    };
5716
    match info {
5717
        case resolver::ForLoopInfo::Range { valType, range, bindingName, indexName } => {
5718
            let endExpr = range.end else {
5719
                throw LowerError::MissingMetadata;
5720
            };
5721
            let mut startVal = il::Val::Imm(0);
5722
            if let start = range.start {
5723
                set startVal = try lowerExpr(self, start);
5724
            }
5725
            let endVal = try lowerExpr(self, endExpr);
5726
            let iterType = ilType(self.low, *valType);
5727
            let valVar = newVar(self, bindingName, iterType, false, startVal);
5728
5729
            let mut indexVar: ?Var = nil;
5730
            if indexName <> nil { // Optional index always starts at zero.
5731
                set indexVar = newVar(self, indexName, il::Type::W32, false, il::Val::Imm(0));
5732
            }
5733
            let iter = ForIter::Range {
5734
                valVar, indexVar, endVal, valType: iterType,
5735
                unsigned: isUnsignedType(*valType),
5736
            };
5737
5738
            try lowerForLoop(self, &iter, f.body);
5739
        }
5740
        case resolver::ForLoopInfo::Collection { elemType, length, bindingName, indexName } => {
5741
            let containerVal = try lowerExpr(self, f.iterable);
5742
            let containerReg = emitValToReg(self, containerVal);
5743
5744
            let mut dataReg = containerReg;
5745
            let mut lengthVal: il::Val = undefined;
5746
            if let len = length { // Array (length is known).
5747
                set lengthVal = il::Val::Imm(len as i64);
5748
            } else { // Slice (length must be loaded).
5749
                set lengthVal = loadSliceLen(self, containerReg);
5750
                set dataReg = loadSlicePtr(self, containerReg);
5751
            }
5752
            // Declare index value binidng.
5753
            let idxVar = newVar(self, indexName, il::Type::W32, false, il::Val::Imm(0));
5754
5755
            // Declare element value binding.
5756
            let mut valVar: ?Var = nil;
5757
            if bindingName <> nil {
5758
                set valVar = newVar(
5759
                    self,
5760
                    bindingName,
5761
                    ilType(self.low, *elemType),
5762
                    false,
5763
                    il::Val::Undef
5764
                );
5765
            }
5766
            let iter = ForIter::Collection { valVar, idxVar, dataReg, lengthVal, elemType };
5767
5768
            try lowerForLoop(self, &iter, f.body);
5769
        }
5770
    }
5771
    exitVarScope(self, savedVarsLen);
5772
}
5773
5774
/// Lower a break statement.
5775
unsafe fn lowerBreak(self: &mut FnLowerer) throws (LowerError) {
5776
    let ctx = currentLoop(self) else {
5777
        throw LowerError::OutsideOfLoop;
5778
    };
5779
    try emitJmp(self, ctx.breakTarget);
5780
}
5781
5782
/// Lower a continue statement.
5783
unsafe fn lowerContinue(self: &mut FnLowerer) throws (LowerError) {
5784
    let block = try getOrCreateContinueBlock(self);
5785
    try emitJmp(self, block);
5786
}
5787
5788
/// Emit a return, blitting into the caller's return buffer if needed.
5789
///
5790
/// When the function has a return buffer parameter, the value is blitted
5791
/// into the buffer and the buffer pointer is returned. Otherwise, the value is
5792
/// returned directly.
5793
unsafe fn emitRetVal(self: &mut FnLowerer, val: il::Val) throws (LowerError) {
5794
    if let retReg = self.returnReg {
5795
        let src = emitValToReg(self, val);
5796
        let size = resolver::getResultLayout(*self.fnType.returnType, self.fnType.throwList).size
5797
            if self.fnType.throwList.len > 0
5798
            else resolver::getTypeLayout(*self.fnType.returnType).size;
5799
5800
        emit(self, il::Instr::Blit { dst: retReg, src, size: il::Val::Imm(size as i64) });
5801
        emit(self, il::Instr::Ret { val: il::Val::Reg(retReg) });
5802
    } else if isSmallAggregate(*self.fnType.returnType) {
5803
        let src = emitValToReg(self, val);
5804
        let dst = nextReg(self);
5805
5806
        emit(self, il::Instr::Load { typ: il::Type::W64, dst, src, offset: 0 });
5807
        emit(self, il::Instr::Ret { val: il::Val::Reg(dst) });
5808
    } else {
5809
        emit(self, il::Instr::Ret { val });
5810
    }
5811
}
5812
5813
/// Lower a return statement.
5814
unsafe fn lowerReturnStmt(self: &mut FnLowerer, node: *ast::Node, value: ?*ast::Node) throws (LowerError) {
5815
    let mut val = il::Val::Undef;
5816
    if let expr = value {
5817
        set val = try lowerExpr(self, expr);
5818
    }
5819
    if blockHasTerminator(self) {
5820
        return;
5821
    }
5822
    set val = try applyCoercion(self, node, val);
5823
    try emitRetVal(self, val);
5824
}
5825
5826
/// Lower a throw statement.
5827
unsafe fn lowerThrowStmt(self: &mut FnLowerer, expr: *ast::Node) throws (LowerError) {
5828
    assert self.fnType.throwList.len > 0;
5829
5830
    let errType = *self.fnType.throwList[0] if self.fnType.throwList.len == 1
5831
        else try typeOf(self, expr);
5832
    let tag = getOrAssignErrorTag(self.low, errType) as i64;
5833
    let errVal = try lowerExpr(self, expr);
5834
    let resultVal = try buildResult(self, tag, errVal, errType);
5835
5836
    try emitRetVal(self, resultVal);
5837
}
5838
5839
/// Ensure a value is in a register (eg. for branch conditions).
5840
unsafe fn emitValToReg(self: &mut FnLowerer, val: il::Val) -> il::Reg {
5841
    match val {
5842
        case il::Val::Reg(r) => return r,
5843
        case il::Val::Imm(_), il::Val::DataSym(_), il::Val::FnAddr(_) => {
5844
            let dst = nextReg(self);
5845
            emit(self, il::Instr::Copy { dst, val });
5846
            return dst;
5847
        }
5848
        case il::Val::Undef => {
5849
            // TODO: We shouldn't hit this case, right? A register shouldn't be needed
5850
            // if the value is undefined.
5851
            return nextReg(self);
5852
        }
5853
    }
5854
}
5855
5856
/// Lower a logical `and`/`or` with short-circuit evaluation.
5857
///
5858
/// Short-circuit evaluation skips evaluating the right operand when the left
5859
/// operand already determines the result:
5860
///
5861
/// - In `a and b`, if `a` is false, result is false without evaluating `b`.
5862
/// - In `a or b`, if `a` is true, result is true without evaluating `b`.
5863
///
5864
/// This matters when `b` has side effects, or is expensive to evaluate.
5865
///
5866
/// Example: `a and b`
5867
///
5868
///     @entry
5869
///       br %a @then @else;
5870
///     @then
5871
///       // Evaluate b into %b
5872
///       // ...
5873
///       jmp @end(%b);
5874
///     @else
5875
///       jmp @end(0);                  // Skip evaluating b, result is false
5876
///     @end(w8 %result)
5877
///       ret %result;
5878
///
5879
/// Example: `a or b`
5880
///
5881
///     @entry
5882
///       br %a @then @else;
5883
///     @then
5884
///       jmp @end(1);                  // Skip evaluating b, result is true
5885
///     @else
5886
///       // Evaluate b into %b
5887
///       // ...
5888
///       jmp @end(%b);
5889
///     @end(w8 %result)
5890
///       ret %result;
5891
///
5892
unsafe fn lowerLogicalOp(
5893
    self: &mut FnLowerer,
5894
    binop: ast::BinOp,
5895
    thenLabel: *[u8],
5896
    elseLabel: *[u8],
5897
    mergeLabel: *[u8],
5898
    op: LogicalOp
5899
) -> il::Val throws (LowerError) {
5900
    let thenBlock = try createBlock(self, thenLabel);
5901
    let elseBlock = try createBlock(self, elseLabel);
5902
5903
    let resultReg = nextReg(self);
5904
    let mergeBlock = try createBlockWithParam(
5905
        self, mergeLabel, il::Param { value: resultReg, type: il::Type::W8 }
5906
    );
5907
    // Evaluate left operand and branch.
5908
    try emitCondBranch(self, binop.left, thenBlock, elseBlock);
5909
5910
    // Block that skips evaluating `b`.
5911
    let mut shortCircuitBlock: BlockId = undefined;
5912
    // Block that evaluates `b`.
5913
    let mut evalBlock: BlockId = undefined;
5914
    // Result when short-circuiting (`0` or `1`).
5915
    let mut shortCircuitVal: i64 = undefined;
5916
5917
    match op {
5918
        case LogicalOp::And => {
5919
            set shortCircuitBlock = elseBlock;
5920
            set evalBlock = thenBlock;
5921
            set shortCircuitVal = 0;
5922
        }
5923
        case LogicalOp::Or => {
5924
            set shortCircuitBlock = thenBlock;
5925
            set evalBlock = elseBlock;
5926
            set shortCircuitVal = 1;
5927
        }
5928
    }
5929
    // Emit short-circuit branch: jump to merge with constant result.
5930
    try switchToAndSeal(self, shortCircuitBlock);
5931
    try emitJmpWithArg(self, mergeBlock, il::Val::Imm(shortCircuitVal));
5932
5933
    // Emit evaluation branch: evaluate right operand and jump to merge.
5934
    try switchToAndSeal(self, evalBlock);
5935
    try emitJmpWithArg(self, mergeBlock, try lowerExpr(self, binop.right));
5936
5937
    try switchToAndSeal(self, mergeBlock);
5938
    return il::Val::Reg(resultReg);
5939
}
5940
5941
/// Lower a conditional expression (`thenExpr if condition else elseExpr`).
5942
unsafe fn lowerCondExpr(self: &mut FnLowerer, node: *ast::Node, cond: ast::CondExpr) -> il::Val
5943
    throws (LowerError)
5944
{
5945
    let typ = try typeOf(self, node);
5946
    let thenBlock = try createBlock(self, "cond#then");
5947
    let elseBlock = try createBlock(self, "cond#else");
5948
5949
    if isAggregateType(typ) {
5950
        let dst = try emitReserve(self, typ);
5951
        let layout = resolver::getTypeLayout(typ);
5952
        try emitCondBranch(self, cond.condition, thenBlock, elseBlock);
5953
5954
        let mergeBlock = try createBlock(self, "cond#merge");
5955
        try switchToAndSeal(self, thenBlock);
5956
5957
        let thenVal = emitValToReg(self, try lowerExpr(self, cond.thenExpr));
5958
        emit(self, il::Instr::Blit { dst, src: thenVal, size: il::Val::Imm(layout.size as i64) });
5959
5960
        try emitJmp(self, mergeBlock);
5961
        try switchToAndSeal(self, elseBlock);
5962
5963
        let elseVal = emitValToReg(self, try lowerExpr(self, cond.elseExpr));
5964
        emit(self, il::Instr::Blit { dst, src: elseVal, size: il::Val::Imm(layout.size as i64) });
5965
5966
        try emitJmp(self, mergeBlock);
5967
        try switchToAndSeal(self, mergeBlock);
5968
5969
        return il::Val::Reg(dst);
5970
    } else {
5971
        try emitCondBranch(self, cond.condition, thenBlock, elseBlock);
5972
5973
        let resultType = ilType(self.low, typ);
5974
        let resultReg = nextReg(self);
5975
        let mergeBlock = try createBlockWithParam(
5976
            self, "cond#merge", il::Param { value: resultReg, type: resultType }
5977
        );
5978
        try switchToAndSeal(self, thenBlock);
5979
        try emitJmpWithArg(self, mergeBlock, try lowerExpr(self, cond.thenExpr));
5980
        try switchToAndSeal(self, elseBlock);
5981
        try emitJmpWithArg(self, mergeBlock, try lowerExpr(self, cond.elseExpr));
5982
        try switchToAndSeal(self, mergeBlock);
5983
5984
        return il::Val::Reg(resultReg);
5985
    }
5986
}
5987
5988
/// Select the concrete operand type for a scalar comparison.
5989
fn scalarComparisonType(left: resolver::Type, right: resolver::Type) -> resolver::Type {
5990
    return right if left == resolver::Type::Int else left;
5991
}
5992
5993
/// Convert a binary operator to a comparison op, if applicable.
5994
/// For `Gt`, caller must swap operands: `a > b = b < a`.
5995
/// For `Gte`/`Lte`, caller must swap branch labels: `a >= b = !(a < b)`.
5996
/// For `Lte`, caller must also swap operands: `a <= b = !(b < a)`.
5997
fn cmpOpFrom(op: ast::BinaryOp, unsigned: bool) -> ?il::CmpOp {
5998
    match op {
5999
        case ast::BinaryOp::Eq => return il::CmpOp::Eq,
6000
        case ast::BinaryOp::Ne => return il::CmpOp::Ne,
6001
        case ast::BinaryOp::Lt, ast::BinaryOp::Gt,
6002
             ast::BinaryOp::Gte, ast::BinaryOp::Lte =>
6003
            return il::CmpOp::Ult if unsigned else il::CmpOp::Slt,
6004
        else => return nil,
6005
    }
6006
}
6007
6008
/// Lower a binary operation.
6009
unsafe fn lowerBinOp(self: &mut FnLowerer, node: *ast::Node, binop: ast::BinOp) -> il::Val throws (LowerError) {
6010
    // Short-circuit logical operators don't evaluate both operands eagerly.
6011
    if binop.op == ast::BinaryOp::And {
6012
        return try lowerLogicalOp(self, binop, "and#then", "and#else", "and#end", LogicalOp::And);
6013
    } else if binop.op == ast::BinaryOp::Or {
6014
        return try lowerLogicalOp(self, binop, "or#then", "or#else", "or#end", LogicalOp::Or);
6015
    }
6016
6017
    // Handle comparison with a `nil` literal: just check the tag/pointer instead of
6018
    // building a `nil` aggregate and doing full comparison.
6019
    if binop.op == ast::BinaryOp::Eq or binop.op == ast::BinaryOp::Ne {
6020
        let isEq = binop.op == ast::BinaryOp::Eq;
6021
        let leftIsNil = binop.left.value == ast::NodeValue::Nil;
6022
        let rightIsNil = binop.right.value == ast::NodeValue::Nil;
6023
6024
        if leftIsNil {
6025
            return try lowerNilCheck(self, binop.right, isEq);
6026
        } else if rightIsNil {
6027
            return try lowerNilCheck(self, binop.left, isEq);
6028
        }
6029
    }
6030
    // Lower operands.
6031
    let a = try lowerExpr(self, binop.left);
6032
    let b = try lowerExpr(self, binop.right);
6033
    let isComparison = cmpOpFrom(binop.op, false) <> nil;
6034
6035
    // The result type for comparisons is always `bool`, while for arithmetic
6036
    // operations, it's the operand type. We set this appropriately here.
6037
    let nodeTy = try typeOf(self, node);
6038
    let mut resultTy = nodeTy;
6039
6040
    if isComparison {
6041
        let leftTy = try effectiveType(self, binop.left);
6042
        let rightTy = try effectiveType(self, binop.right);
6043
        // Optimize: comparing with a void variant just needs tag comparison.
6044
        if let idx = voidVariantIndex(self.low.resolver, binop.left) {
6045
            return try emitTagCmp(self, binop.op, b, idx, rightTy);
6046
        } else if let idx = voidVariantIndex(self.low.resolver, binop.right) {
6047
            return try emitTagCmp(self, binop.op, a, idx, leftTy);
6048
        }
6049
        // Aggregate types require element-wise comparison.
6050
        // When comparing `?T` with `T`, wrap the scalar side.
6051
        if isAggregateType(leftTy) {
6052
            let mut rhs = b;
6053
            if not isAggregateType(rightTy) {
6054
                set rhs = try wrapInOptional(self, rhs, leftTy);
6055
            }
6056
            return try emitAggregateEqOp(self, binop.op, leftTy, a, rhs);
6057
        }
6058
        if isAggregateType(rightTy) {
6059
            let lhs = try wrapInOptional(self, a, rightTy);
6060
            return try emitAggregateEqOp(self, binop.op, rightTy, lhs, b);
6061
        }
6062
        set resultTy = scalarComparisonType(leftTy, rightTy);
6063
    }
6064
    return emitScalarBinOp(self, binop.op, ilType(self.low, resultTy), a, b, isUnsignedType(resultTy));
6065
}
6066
6067
/// Emit an aggregate equality or inequality comparison.
6068
unsafe fn emitAggregateEqOp(
6069
    self: &mut FnLowerer,
6070
    op: ast::BinaryOp,
6071
    typ: resolver::Type,
6072
    a: il::Val,
6073
    b: il::Val
6074
) -> il::Val throws (LowerError) {
6075
    let regA = emitValToReg(self, a);
6076
    let regB = emitValToReg(self, b);
6077
    let result = try lowerAggregateEq(self, typ, regA, regB, 0);
6078
6079
    if op == ast::BinaryOp::Ne {
6080
        return emitTypedBinOp(self, il::BinOp::Eq, il::Type::W32, result, il::Val::Imm(0));
6081
    }
6082
    return result;
6083
}
6084
6085
/// Emit a scalar binary operation instruction.
6086
unsafe fn emitScalarBinOp(
6087
    self: &mut FnLowerer,
6088
    op: ast::BinaryOp,
6089
    typ: il::Type,
6090
    a: il::Val,
6091
    b: il::Val,
6092
    unsigned: bool
6093
) -> il::Val {
6094
    let dst = nextReg(self);
6095
    let mut needsExt: bool = false;
6096
    match op {
6097
        case ast::BinaryOp::Add => {
6098
            emit(self, il::Instr::BinOp { op: il::BinOp::Add, typ, dst, a, b });
6099
            set needsExt = true;
6100
        }
6101
        case ast::BinaryOp::Sub => {
6102
            emit(self, il::Instr::BinOp { op: il::BinOp::Sub, typ, dst, a, b });
6103
            set needsExt = true;
6104
        }
6105
        case ast::BinaryOp::Mul => {
6106
            emit(self, il::Instr::BinOp { op: il::BinOp::Mul, typ, dst, a, b });
6107
            set needsExt = true;
6108
        }
6109
        case ast::BinaryOp::Div => {
6110
            let op = il::BinOp::Udiv if unsigned else il::BinOp::Sdiv;
6111
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6112
            set needsExt = true;
6113
        }
6114
        case ast::BinaryOp::Mod => {
6115
            let op = il::BinOp::Urem if unsigned else il::BinOp::Srem;
6116
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6117
            set needsExt = true;
6118
        }
6119
        case ast::BinaryOp::BitAnd => emit(self, il::Instr::BinOp { op: il::BinOp::And, typ, dst, a, b }),
6120
        case ast::BinaryOp::BitOr => emit(self, il::Instr::BinOp { op: il::BinOp::Or, typ, dst, a, b }),
6121
        case ast::BinaryOp::BitXor => emit(self, il::Instr::BinOp { op: il::BinOp::Xor, typ, dst, a, b }),
6122
        case ast::BinaryOp::Shl => {
6123
            emit(self, il::Instr::BinOp { op: il::BinOp::Shl, typ, dst, a, b });
6124
            set needsExt = true;
6125
        }
6126
        case ast::BinaryOp::Shr => {
6127
            let op = il::BinOp::Ushr if unsigned else il::BinOp::Sshr;
6128
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6129
        }
6130
        case ast::BinaryOp::Eq => emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ, dst, a, b }),
6131
        case ast::BinaryOp::Ne => emit(self, il::Instr::BinOp { op: il::BinOp::Ne, typ, dst, a, b }),
6132
        case ast::BinaryOp::Lt => {
6133
            let op = il::BinOp::Ult if unsigned else il::BinOp::Slt;
6134
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6135
        }
6136
        case ast::BinaryOp::Gt => { // `a > b` = `b < a`
6137
            let op = il::BinOp::Ult if unsigned else il::BinOp::Slt;
6138
            emit(self, il::Instr::BinOp { op, typ, dst, a: b, b: a });
6139
        }
6140
        case ast::BinaryOp::Lte => { // `a <= b` = `b >= a`
6141
            let op = il::BinOp::Uge if unsigned else il::BinOp::Sge;
6142
            emit(self, il::Instr::BinOp { op, typ, dst, a: b, b: a });
6143
        }
6144
        case ast::BinaryOp::Gte => {
6145
            let op = il::BinOp::Uge if unsigned else il::BinOp::Sge;
6146
            emit(self, il::Instr::BinOp { op, typ, dst, a, b });
6147
        }
6148
        // Logical xor on booleans is equivalent to not equal.
6149
        case ast::BinaryOp::Xor => emit(self, il::Instr::BinOp { op: il::BinOp::Ne, typ, dst, a, b }),
6150
        // Short-circuit ops are handled elsewhere.
6151
        case ast::BinaryOp::And, ast::BinaryOp::Or => panic,
6152
    }
6153
    // Normalize sub-word arithmetic results so high bits are well-defined.
6154
    // The lowering knows signedness, so it can pick the right extension.
6155
    // [`il::Type::W32`] is handled in the backend via 32-bit instructions.
6156
    if needsExt {
6157
        return normalizeSubword(self, typ, unsigned, il::Val::Reg(dst));
6158
    }
6159
    return il::Val::Reg(dst);
6160
}
6161
6162
/// Normalize sub-word values to well-defined high bits.
6163
unsafe fn normalizeSubword(self: &mut FnLowerer, typ: il::Type, unsigned: bool, val: il::Val) -> il::Val {
6164
    if typ == il::Type::W8 or typ == il::Type::W16 {
6165
        let extDst: il::Reg = nextReg(self);
6166
        if unsigned {
6167
            emit(self, il::Instr::Zext { typ, dst: extDst, val });
6168
        } else {
6169
            emit(self, il::Instr::Sext { typ, dst: extDst, val });
6170
        }
6171
        return il::Val::Reg(extDst);
6172
    }
6173
    return val;
6174
}
6175
6176
/// Lower a unary operation.
6177
unsafe fn lowerUnOp(self: &mut FnLowerer, node: *ast::Node, unop: ast::UnOp) -> il::Val throws (LowerError) {
6178
    if unop.op == ast::UnaryOp::Neg {
6179
        if let case ast::NodeValue::Number(lit) = unop.value.value {
6180
            return il::Val::Imm((0 - lit.magnitude) as i64);
6181
        }
6182
    }
6183
    let val = try lowerExpr(self, unop.value);
6184
    let t = try typeOf(self, node);
6185
    let typ = ilType(self.low, t);
6186
    let dst = nextReg(self);
6187
    let mut needsExt: bool = false;
6188
6189
    match unop.op {
6190
        case ast::UnaryOp::Not => {
6191
            emit(self, il::Instr::BinOp { op: il::BinOp::Eq, typ, dst, a: val, b: il::Val::Imm(0) });
6192
        }
6193
        case ast::UnaryOp::Neg => {
6194
            emit(self, il::Instr::UnOp { op: il::UnOp::Neg, typ, dst, a: val });
6195
            set needsExt = true;
6196
        }
6197
        case ast::UnaryOp::BitNot => {
6198
            emit(self, il::Instr::UnOp { op: il::UnOp::Not, typ, dst, a: val });
6199
            set needsExt = true;
6200
        }
6201
    }
6202
    if needsExt {
6203
        return normalizeSubword(self, typ, isUnsignedType(t), il::Val::Reg(dst));
6204
    }
6205
    return il::Val::Reg(dst);
6206
}
6207
6208
/// Lower a cast expression (`x as T`).
6209
unsafe fn lowerCast(self: &mut FnLowerer, node: *ast::Node, cast: ast::As) -> il::Val throws (LowerError) {
6210
    let val = try lowerExpr(self, cast.value);
6211
6212
    let srcType = try typeOf(self, cast.value);
6213
    let dstType = try typeOf(self, node);
6214
    if resolver::typesEqual(srcType, dstType) {
6215
        return val;
6216
    }
6217
    return lowerNumericCast(self, val, srcType, dstType);
6218
}
6219
6220
/// Check whether a resolver type is a signed integer type.
6221
fn isSignedType(t: resolver::Type) -> bool {
6222
    match t {
6223
        case resolver::Type::I8, resolver::Type::I16, resolver::Type::I32, resolver::Type::I64,
6224
             resolver::Type::Int => return true,
6225
        else => return false,
6226
    }
6227
}
6228
6229
/// Check whether a resolver type is an unsigned integer type.
6230
fn isUnsignedType(t: resolver::Type) -> bool {
6231
    match t {
6232
        case resolver::Type::U8, resolver::Type::U16, resolver::Type::U32, resolver::Type::U64 => return true,
6233
        else => return false,
6234
    }
6235
}
6236
6237
/// Lower a string literal to a slice value.
6238
///
6239
/// String literals are stored as global data and the result is a slice
6240
/// pointing to the data with the appropriate length.
6241
unsafe fn lowerStringLit(self: &mut FnLowerer, node: *ast::Node, s: *[u8]) -> il::Val throws (LowerError) {
6242
    // Get the slice type from the node.
6243
    let sliceTy = try typeOf(self, node);
6244
    let case resolver::Type::Slice { item, mutable, .. } = sliceTy
6245
        else throw LowerError::ExpectedSliceOrArray;
6246
    // Build the string data value.
6247
    let ptr = try! alloc::alloc(
6248
        self.low.arena, @sizeOf(il::DataValue), @alignOf(il::DataValue)
6249
    ) as *mut il::DataValue;
6250
6251
    set *ptr = il::DataValue { item: il::DataItem::Str(s), count: 1 };
6252
    let result = ConstDataResult { values: @sliceOf(ptr, 1), zeroInit: false };
6253
6254
    return try lowerConstDataAsSlice(
6255
        self, &result, 1, true, item, mutable, s.len
6256
    );
6257
}
6258
6259
/// Lower a builtin call expression.
6260
unsafe fn lowerBuiltinCall(self: &mut FnLowerer, node: *ast::Node, kind: ast::Builtin, args: *[*ast::Node]) -> il::Val throws (LowerError) {
6261
    match kind {
6262
        case ast::Builtin::SliceOf => return try lowerSliceOf(self, node, args),
6263
        case ast::Builtin::SizeOf, ast::Builtin::AlignOf => {
6264
            let constVal = resolver::constValueEntry(self.low.resolver, node) else {
6265
                throw LowerError::MissingConst(node);
6266
            };
6267
            return try constValueToVal(self, constVal, node);
6268
        }
6269
    }
6270
}
6271
6272
/// Lower a `@sliceOf(ptr, len)` or `@sliceOf(ptr, len, cap)` builtin call.
6273
unsafe fn lowerSliceOf(self: &mut FnLowerer, node: *ast::Node, args: *[*ast::Node]) -> il::Val throws (LowerError) {
6274
    if args.len <> 2 and args.len <> 3 {
6275
        throw LowerError::InvalidArgCount;
6276
    }
6277
    let sliceTy = try typeOf(self, node);
6278
    let case resolver::Type::Slice { item, mutable, .. } = sliceTy
6279
        else throw LowerError::ExpectedSliceOrArray;
6280
    let ptrVal = try lowerExpr(self, args[0]);
6281
    let lenVal = try lowerExpr(self, args[1]);
6282
    let mut capVal = lenVal;
6283
    if args.len == 3 {
6284
        set capVal = try lowerExpr(self, args[2]);
6285
    }
6286
    if not isLtEq(lenVal, capVal) {
6287
        try emitTrapIfLt(self, il::Type::W32, capVal, lenVal);
6288
    }
6289
    return try buildSliceValue(self, item, mutable, ptrVal, lenVal, capVal);
6290
}
6291
6292
/// Lower a `try` expression.
6293
unsafe fn lowerTry(self: &mut FnLowerer, node: *ast::Node, t: ast::Try) -> il::Val throws (LowerError) {
6294
    let case ast::NodeValue::Call(callExpr) = t.expr.value else {
6295
        throw LowerError::ExpectedCall;
6296
    };
6297
    let calleeTy = try typeOf(self, callExpr.callee);
6298
    let case resolver::Type::Fn(calleeInfo) = calleeTy else {
6299
        throw LowerError::ExpectedFunction;
6300
    };
6301
    let okValueTy = *calleeInfo.returnType; // The type of the success payload.
6302
6303
    // Type of the try expression, which is either the return type of the function
6304
    // if successful, or an optional of it, if using `try?`.
6305
    let tryExprTy = try typeOf(self, node);
6306
    // Check for trait method dispatch or standalone method call.
6307
    let mut resVal: il::Val = undefined;
6308
    let callNodeExtra = resolver::nodeData(self.low.resolver, t.expr).extra;
6309
    if let case resolver::NodeExtra::TraitMethodCall {
6310
        traitInfo, methodIndex
6311
    } = callNodeExtra {
6312
        set resVal = try lowerTraitMethodCall(self, t.expr, callExpr, traitInfo, methodIndex);
6313
    } else if let case resolver::NodeExtra::MethodCall { method } = callNodeExtra {
6314
        set resVal = try lowerMethodCall(self, t.expr, callExpr, method);
6315
    } else {
6316
        set resVal = try lowerCall(self, t.expr, callExpr);
6317
    }
6318
    let base = emitValToReg(self, resVal); // The result value.
6319
    let tagReg = resultTagReg(self, base); // The result tag.
6320
6321
    let okBlock = try createBlock(self, "ok"); // Block if success.
6322
    let errBlock = try createBlock(self, "err"); // Block if failure.
6323
6324
    let mut mergeBlock: ?BlockId = nil;
6325
    let mut resultSlot: ?il::Reg = nil; // `try` result value will be stored here.
6326
6327
    // Check if the `try` returns a success value or not. If so, reserve
6328
    // space for it.
6329
    let isVoid = tryExprTy == resolver::Type::Void or tryExprTy == resolver::Type::Never;
6330
    if not isVoid {
6331
        set resultSlot = try emitReserve(self, tryExprTy);
6332
    }
6333
    // Branch on tag: zero means ok, non-zero means error.
6334
    try emitBr(self, tagReg, errBlock, okBlock);
6335
6336
    // We can now seal the blocks since all predecessors are known.
6337
    try sealBlock(self, okBlock);
6338
    try sealBlock(self, errBlock);
6339
6340
    // Success path: extract the successful value from the result and store it
6341
    // in the result slot for later use after the merge point.
6342
    switchToBlock(self, okBlock);
6343
6344
    if okValueTy == resolver::Type::Never {
6345
        emit(self, il::Instr::Unreachable);
6346
    } else if let slot = resultSlot {
6347
        // Extract the success payload. If the result type differs from the payload
6348
        // type (e.g. `try?` wrapping `T` into `?T`), wrap the value.
6349
        let payloadVal = tvalPayloadVal(self, base, okValueTy, RESULT_VAL_OFFSET);
6350
        let mut okVal = payloadVal;
6351
6352
        if t.returnsOptional and tryExprTy <> okValueTy {
6353
            set okVal = try wrapInOptional(self, payloadVal, tryExprTy);
6354
        }
6355
        try emitStore(self, slot, 0, tryExprTy, okVal);
6356
    }
6357
    // Jump to merge block if unterminated.
6358
    try emitMergeIfUnterminated(self, &mut mergeBlock);
6359
6360
    // Error path: handle the failure case based on the try expression variant.
6361
    switchToBlock(self, errBlock);
6362
6363
    if t.returnsOptional {
6364
        // `try?` converts errors to `nil` -- store the `nil` and continue.
6365
        if let slot = resultSlot {
6366
            let errVal = try buildNilOptional(self, tryExprTy);
6367
            try emitStore(self, slot, 0, tryExprTy, errVal);
6368
        }
6369
        try emitMergeIfUnterminated(self, &mut mergeBlock);
6370
    } else if t.catches.len > 0 {
6371
        // `try ... catch` -- handle the error.
6372
        let firstNode = t.catches[0];
6373
        let case ast::NodeValue::CatchClause(first) = firstNode.value
6374
            else panic "lowerTry: expected CatchClause";
6375
6376
        if first.typeNode <> nil or t.catches.len > 1 {
6377
            // Typed multi-catch: switch on global error tag.
6378
            try lowerMultiCatch(self, t.catches, calleeInfo, base, tagReg, &mut mergeBlock);
6379
        } else {
6380
            // Single untyped catch clause.
6381
            let savedVarsLen = enterVarScope(self);
6382
            if let binding = first.binding {
6383
                let case ast::NodeValue::Ident(name) = binding.value else {
6384
                    throw LowerError::ExpectedIdentifier;
6385
                };
6386
                let errTy = *calleeInfo.throwList[0];
6387
                let errVal = tvalPayloadVal(self, base, errTy, RESULT_VAL_OFFSET);
6388
                let _ = newVar(self, name, ilType(self.low, errTy), false, errVal);
6389
            }
6390
            try lowerBlock(self, first.body);
6391
            try emitMergeIfUnterminated(self, &mut mergeBlock);
6392
            exitVarScope(self, savedVarsLen);
6393
        }
6394
    } else if t.shouldPanic {
6395
        // `try!` -- panic on error, emit unreachable since control won't continue.
6396
        // TODO: We should have some kind of `panic` instruction?
6397
        emit(self, il::Instr::Unreachable);
6398
    } else {
6399
        // Plain `try` -- propagate the error to the caller by returning early.
6400
        // Forward the callee's global error tag and payload directly.
6401
        let callerLayout = resolver::getResultLayout(
6402
            *self.fnType.returnType, self.fnType.throwList
6403
        );
6404
        let calleeErrSize = maxErrSize(calleeInfo.throwList);
6405
        let dst = emitReserveLayout(self, callerLayout);
6406
6407
        emitStoreW64At(self, il::Val::Reg(tagReg), dst, TVAL_TAG_OFFSET);
6408
        let srcPayload = emitPtrOffset(self, base, RESULT_VAL_OFFSET);
6409
        let dstPayload = emitPtrOffset(self, dst, RESULT_VAL_OFFSET);
6410
        emit(self, il::Instr::Blit { dst: dstPayload, src: srcPayload, size: il::Val::Imm(calleeErrSize as i64) });
6411
6412
        try emitRetVal(self, il::Val::Reg(dst));
6413
    }
6414
6415
    // Switch to the merge block if one was created. If all paths diverged
6416
    // (e.g both success and error returned), there's no merge block.
6417
    if let blk = mergeBlock {
6418
        try switchToAndSeal(self, blk);
6419
    } else {
6420
        return il::Val::Undef;
6421
    }
6422
    // Return the result value. For `void` expressions, return undefined.
6423
    // For aggregates, return the slot pointer; for scalars, load the value.
6424
    if let slot = resultSlot {
6425
        if isAggregateType(tryExprTy) {
6426
            return il::Val::Reg(slot);
6427
        }
6428
        return emitLoad(self, slot, 0, tryExprTy);
6429
    } else { // Void return.
6430
        return il::Val::Undef;
6431
    }
6432
}
6433
6434
/// Lower typed multi-catch clauses.
6435
///
6436
/// Emits a switch on the global error tag to dispatch to the correct catch
6437
/// clause. Each typed clause extracts the error payload for its specific type
6438
/// and binds it to the clause's identifier.
6439
unsafe fn lowerMultiCatch(
6440
    self: &mut FnLowerer,
6441
    catches: *[*ast::Node],
6442
    calleeInfo: *resolver::FnType,
6443
    base: il::Reg,
6444
    tagReg: il::Reg,
6445
    mergeBlock: &mut ?BlockId
6446
) throws (LowerError) {
6447
    let entry = currentBlock(self);
6448
6449
    // First pass: create blocks, resolve error types, and build switch cases.
6450
    let mut blocks: [BlockId; MAX_CATCH_CLAUSES] = undefined;
6451
    let mut errTypes: [?resolver::Type; MAX_CATCH_CLAUSES] = undefined;
6452
    let mut cases: *unsafe mut [il::SwitchCase] = &mut [];
6453
    let mut defaultIdx: ?u32 = nil;
6454
6455
    for clauseNode, i in catches {
6456
        let case ast::NodeValue::CatchClause(clause) = clauseNode.value
6457
            else panic "lowerMultiCatch: expected CatchClause";
6458
6459
        set blocks[i] = try createBlock(self, "catch");
6460
        addPredecessor(self, blocks[i], entry);
6461
6462
        if let typeNode = clause.typeNode {
6463
            let errTy = try typeOf(self, typeNode);
6464
            set errTypes[i] = errTy;
6465
6466
            cases.append(il::SwitchCase {
6467
                value: getOrAssignErrorTag(self.low, errTy) as i64,
6468
                target: *blocks[i],
6469
                args: &mut []
6470
            }, self.allocator);
6471
        } else {
6472
            set errTypes[i] = nil;
6473
            set defaultIdx = i;
6474
        }
6475
    }
6476
6477
    // Emit switch. Default target is the catch-all block, or an unreachable block.
6478
    let mut defaultTarget: BlockId = undefined;
6479
    if let idx = defaultIdx {
6480
        set defaultTarget = blocks[idx];
6481
    } else {
6482
        set defaultTarget = try createBlock(self, "unreachable");
6483
        addPredecessor(self, defaultTarget, entry);
6484
    }
6485
    emit(self, il::Instr::Switch {
6486
        val: il::Val::Reg(tagReg),
6487
        defaultTarget: *defaultTarget,
6488
        defaultArgs: &mut [],
6489
        cases
6490
    });
6491
6492
    // Second pass: emit each catch clause body.
6493
    for clauseNode, i in catches {
6494
        let case ast::NodeValue::CatchClause(clause) = clauseNode.value
6495
            else panic "lowerMultiCatch: expected CatchClause";
6496
6497
        try switchToAndSeal(self, blocks[i]);
6498
        let savedVarsLen = enterVarScope(self);
6499
6500
        if let binding = clause.binding {
6501
            let case ast::NodeValue::Ident(name) = binding.value else {
6502
                throw LowerError::ExpectedIdentifier;
6503
            };
6504
            let errTy = errTypes[i] else panic "lowerMultiCatch: catch-all with binding";
6505
            let errVal = tvalPayloadVal(self, base, errTy, RESULT_VAL_OFFSET);
6506
6507
            newVar(self, name, ilType(self.low, errTy), false, errVal);
6508
        }
6509
        try lowerBlock(self, clause.body);
6510
        try emitMergeIfUnterminated(self, mergeBlock);
6511
6512
        exitVarScope(self, savedVarsLen);
6513
    }
6514
6515
    // Emit unreachable block if no catch-all.
6516
    if defaultIdx == nil {
6517
        try switchToAndSeal(self, defaultTarget);
6518
        emit(self, il::Instr::Unreachable);
6519
    }
6520
}
6521
6522
/// Emit a byte-copy loop: `for i in 0..size { dst[i] = src[i]; }`.
6523
///
6524
/// Used when `blit` cannot be used because the copy size is dynamic.
6525
/// Terminates the current block and leaves the builder positioned
6526
/// after the loop.
6527
unsafe fn emitByteCopyLoop(
6528
    self: &mut FnLowerer,
6529
    dst: il::Reg,
6530
    src: il::Reg,
6531
    size: il::Val,
6532
    label: *[u8]
6533
) throws (LowerError) {
6534
    let iReg = nextReg(self);
6535
    let header = try createBlockWithParam(
6536
        self, label, il::Param { value: iReg, type: il::Type::W32 }
6537
    );
6538
    let body = try createBlock(self, label);
6539
    let done = try createBlock(self, label);
6540
6541
    // Jump to header with initial counter is zero.
6542
    try emitJmpWithArg(self, header, il::Val::Imm(0));
6543
6544
    // Don't seal header yet -- the body will add another predecessor.
6545
    switchToBlock(self, header);
6546
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, il::Val::Reg(iReg), size, body, done);
6547
6548
    // Body: load byte from source, store to destination, increment counter.
6549
    try switchToAndSeal(self, body);
6550
6551
    let srcElem = emitElem(self, 1, src, il::Val::Reg(iReg));
6552
    let byteReg = nextReg(self);
6553
    emit(self, il::Instr::Load { typ: il::Type::W8, dst: byteReg, src: srcElem, offset: 0 });
6554
6555
    let dstElem = emitElem(self, 1, dst, il::Val::Reg(iReg));
6556
    emit(self, il::Instr::Store { typ: il::Type::W8, src: il::Val::Reg(byteReg), dst: dstElem, offset: 0 });
6557
6558
    let nextI = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, il::Val::Reg(iReg), il::Val::Imm(1));
6559
    // Jump back to header -- this adds body as a predecessor.
6560
    try emitJmpWithArg(self, header, nextI);
6561
6562
    // Now all predecessors of header are known, seal it.
6563
    try sealBlock(self, header);
6564
    try switchToAndSeal(self, done);
6565
}
6566
6567
/// Lower `slice.append(val, allocator)`.
6568
///
6569
/// Emits inline grow-if-needed logic:
6570
///
6571
///     load len, cap from slice header
6572
///     if len < cap: jmp @store
6573
///     else:         jmp @grow
6574
///
6575
///     @grow:
6576
///       newCap = max(cap * 2, 1)
6577
///       call allocator.func(allocator.ctx, newCap * stride, alignment)
6578
///       copy old data to new pointer
6579
///       update slice ptr and cap
6580
///       jmp @store
6581
///
6582
///     @store:
6583
///       store element at ptr + len * stride
6584
///       increment len
6585
///
6586
unsafe fn lowerSliceAppend(self: &mut FnLowerer, call: ast::Call, elemType: *resolver::Type) -> il::Val throws (LowerError) {
6587
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6588
        else throw LowerError::MissingMetadata;
6589
6590
    // Get the address of the slice header.
6591
    let sliceVal = try lowerExpr(self, access.parent);
6592
    let sliceReg = emitValToReg(self, sliceVal);
6593
6594
    // Lower the value to append and the allocator.
6595
    let elemVal = try lowerExpr(self, call.args[0]);
6596
    let allocVal = try lowerExpr(self, call.args[1]);
6597
    let allocReg = emitValToReg(self, allocVal);
6598
6599
    let elemLayout = resolver::getTypeLayout(*elemType);
6600
    let stride = elemLayout.size;
6601
    let alignment = elemLayout.alignment;
6602
6603
    // Load current length and capacity.
6604
    let lenVal = loadSliceLen(self, sliceReg);
6605
    let capVal = loadSliceCap(self, sliceReg);
6606
6607
    // Branch: if length is smaller than capacity, go to @store else @grow.
6608
    let storeBlock = try createBlock(self, "append.store");
6609
    let growBlock = try createBlock(self, "append.grow");
6610
    try emitBrCmp(self, il::CmpOp::Ult, il::Type::W32, lenVal, capVal, storeBlock, growBlock);
6611
    try switchToAndSeal(self, growBlock);
6612
6613
    // -- @grow block ----------------------------------------------------------
6614
6615
    // `newCap = max(cap * 2, 1)`.
6616
    // We are only here when at capacity, so we use `or` with `1` to ensure at least capacity `1`.
6617
    let doubledVal = emitTypedBinOp(self, il::BinOp::Shl, il::Type::W32, capVal, il::Val::Imm(1));
6618
    let newCapVal = emitTypedBinOp(self, il::BinOp::Or, il::Type::W32, doubledVal, il::Val::Imm(1));
6619
6620
    // Call allocator: `a.func(a.ctx, newCap * stride, alignment)`.
6621
    let allocFnReg = nextReg(self);
6622
    emitLoadW64At(self, allocFnReg, allocReg, 0);
6623
6624
    let allocCtxReg = nextReg(self);
6625
    emitLoadW64At(self, allocCtxReg, allocReg, 8);
6626
6627
    let byteSize = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, newCapVal, il::Val::Imm(stride as i64));
6628
    let args = try allocVals(self, 3);
6629
6630
    set args[0] = il::Val::Reg(allocCtxReg);
6631
    set args[1] = byteSize;
6632
    set args[2] = il::Val::Imm(alignment as i64);
6633
6634
    let newPtrReg = nextReg(self);
6635
    emit(self, il::Instr::Call {
6636
        retTy: il::Type::W64,
6637
        dst: newPtrReg,
6638
        func: il::Val::Reg(allocFnReg),
6639
        args,
6640
    });
6641
6642
    // Copy old data byte-by-byte.
6643
    let oldPtrReg = loadSlicePtr(self, sliceReg);
6644
    let copyBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, lenVal, il::Val::Imm(stride as i64));
6645
    try emitByteCopyLoop(self, newPtrReg, oldPtrReg, copyBytes, "append");
6646
6647
    // Update slice header.
6648
    emitStoreW64At(self, il::Val::Reg(newPtrReg), sliceReg, SLICE_PTR_OFFSET);
6649
    emitStoreW32At(self, newCapVal, sliceReg, SLICE_CAP_OFFSET);
6650
6651
    try emitJmp(self, storeBlock);
6652
    try switchToAndSeal(self, storeBlock);
6653
6654
    // -- @store block ---------------------------------------------------------
6655
6656
    // Store element at `ptr + len * stride`.
6657
    let ptrReg = loadSlicePtr(self, sliceReg);
6658
    let elemDst = emitElem(self, stride, ptrReg, lenVal);
6659
    try emitStore(self, elemDst, 0, *elemType, elemVal);
6660
6661
    // Increment len.
6662
    let newLen = emitTypedBinOp(self, il::BinOp::Add, il::Type::W32, lenVal, il::Val::Imm(1));
6663
    emitStoreW32At(self, newLen, sliceReg, SLICE_LEN_OFFSET);
6664
6665
    return il::Val::Reg(sliceReg);
6666
}
6667
6668
/// Lower `slice.delete(index)`.
6669
///
6670
/// Bounds-check the index, shift elements after it by one stride
6671
/// via a byte-copy loop, and decrement `len`.
6672
unsafe fn lowerSliceDelete(self: &mut FnLowerer, call: ast::Call, elemType: *resolver::Type) throws (LowerError) {
6673
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6674
        else throw LowerError::MissingMetadata;
6675
6676
    let elemLayout = resolver::getTypeLayout(*elemType);
6677
    let stride = elemLayout.size;
6678
6679
    // Get slice header address.
6680
    let sliceVal = try lowerExpr(self, access.parent);
6681
    let sliceReg = emitValToReg(self, sliceVal);
6682
6683
    // Lower the index argument.
6684
    let indexVal = try lowerExpr(self, call.args[0]);
6685
6686
    // Load len and bounds-check: index must be smaller than length.
6687
    let lenVal = loadSliceLen(self, sliceReg);
6688
    try emitTrapUnlessCmp(self, il::CmpOp::Ult, il::Type::W32, indexVal, lenVal);
6689
6690
    // Compute the destination and source for the shift.
6691
    let ptrReg = loadSlicePtr(self, sliceReg);
6692
    let dst = emitElem(self, stride, ptrReg, indexVal);
6693
6694
    // `src = dst + stride`.
6695
    let src = emitPtrOffset(self, dst, stride as i32);
6696
6697
    // Move `(len - index - 1) * stride`.
6698
    let tailLen = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, lenVal, indexVal);
6699
    let tailLenMinusOne = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, tailLen, il::Val::Imm(1));
6700
    let moveBytes = emitTypedBinOp(self, il::BinOp::Mul, il::Type::W32, tailLenMinusOne, il::Val::Imm(stride as i64));
6701
6702
    // Shift elements left via byte-copy loop.
6703
    // When deleting the last element, the loop is a no-op.
6704
    try emitByteCopyLoop(self, dst, src, moveBytes, "delete");
6705
    // Decrement length.
6706
    let newLen = emitTypedBinOp(self, il::BinOp::Sub, il::Type::W32, lenVal, il::Val::Imm(1));
6707
6708
    emitStoreW32At(self, newLen, sliceReg, SLICE_LEN_OFFSET);
6709
}
6710
6711
/// Lower a call expression, which may be a function call or type constructor.
6712
unsafe fn lowerCallOrCtor(self: &mut FnLowerer, node: *ast::Node, call: ast::Call) -> il::Val throws (LowerError) {
6713
    let nodeData = resolver::nodeData(self.low.resolver, node).extra;
6714
6715
    // Check for slice method dispatch.
6716
    if let case resolver::NodeExtra::SliceAppend { elemType } = nodeData {
6717
        return try lowerSliceAppend(self, call, elemType);
6718
    }
6719
    if let case resolver::NodeExtra::SliceDelete { elemType } = nodeData {
6720
        try lowerSliceDelete(self, call, elemType);
6721
        return il::Val::Undef;
6722
    }
6723
    // Check for trait method dispatch.
6724
    if let case resolver::NodeExtra::TraitMethodCall { traitInfo, methodIndex } = nodeData {
6725
        return try lowerTraitMethodCall(self, node, call, traitInfo, methodIndex);
6726
    }
6727
    // Check for standalone method call.
6728
    if let case resolver::NodeExtra::MethodCall { method } = nodeData {
6729
        return try lowerMethodCall(self, node, call, method);
6730
    }
6731
    if let sym = resolver::nodeData(self.low.resolver, call.callee).sym {
6732
        if let case resolver::SymbolData::Type(nominal) = sym.data {
6733
            let case resolver::NominalType::Record(_) = *nominal else {
6734
                throw LowerError::ExpectedRecord;
6735
            };
6736
            return try lowerRecordCtor(self, nominal, call.args);
6737
        }
6738
        if let case resolver::SymbolData::Variant { .. } = sym.data {
6739
            return try lowerUnionCtor(self, node, sym, call);
6740
        }
6741
    }
6742
    return try lowerCall(self, node, call);
6743
}
6744
6745
/// Lower a trait method call through v-table dispatch.
6746
///
6747
/// Given `obj.method(args)` where `obj` is a trait object, emits:
6748
///
6749
///     load w64 %data %obj 0          // data pointer
6750
///     load w64 %vtable %obj 8        // v-table pointer
6751
///     load w64 %fn %vtable <slot>    // function pointer
6752
///     call <retTy> %ret %fn(%data, args...)
6753
///
6754
unsafe fn lowerTraitMethodCall(
6755
    self: &mut FnLowerer,
6756
    node: *ast::Node,
6757
    call: ast::Call,
6758
    traitInfo: *unsafe resolver::TraitType,
6759
    methodIndex: u32
6760
) -> il::Val throws (LowerError) {
6761
    // Method calls look like field accesses.
6762
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6763
        else throw LowerError::MissingMetadata;
6764
6765
    // Lower the trait object expression.
6766
    let traitObjVal = try lowerExpr(self, access.parent);
6767
    let traitObjReg = emitValToReg(self, traitObjVal);
6768
6769
    // Load data pointer from trait object.
6770
    let dataReg = nextReg(self);
6771
    emit(self, il::Instr::Load {
6772
        typ: il::Type::W64,
6773
        dst: dataReg,
6774
        src: traitObjReg,
6775
        offset: TRAIT_OBJ_DATA_OFFSET,
6776
    });
6777
6778
    // Load v-table pointer from trait object.
6779
    let vtableReg = nextReg(self);
6780
    emit(self, il::Instr::Load {
6781
        typ: il::Type::W64,
6782
        dst: vtableReg,
6783
        src: traitObjReg,
6784
        offset: TRAIT_OBJ_VTABLE_OFFSET,
6785
    });
6786
6787
    // Load function pointer from v-table at the method's slot offset.
6788
    let fnPtrReg = nextReg(self);
6789
    let slotOffset = (methodIndex * resolver::PTR_SIZE) as i32;
6790
6791
    emit(self, il::Instr::Load {
6792
        typ: il::Type::W64,
6793
        dst: fnPtrReg,
6794
        src: vtableReg,
6795
        offset: slotOffset,
6796
    });
6797
    let methodFnType = traitInfo.methods[methodIndex].fnType;
6798
6799
    // Build args: optional return param slot + data pointer (receiver) + user args.
6800
    let argOffset: u32 = 1 if requiresReturnParam(methodFnType) else 0;
6801
    let args = try allocVals(self, call.args.len + 1 + argOffset);
6802
    set args[argOffset] = il::Val::Reg(dataReg);
6803
6804
    for arg, i in call.args {
6805
        set args[i + 1 + argOffset] = try lowerCallArg(
6806
            self, arg, i + 1 < call.args.len
6807
        );
6808
    }
6809
    return try emitCallValue(self, il::Val::Reg(fnPtrReg), methodFnType, args);
6810
}
6811
6812
/// Lower a call argument, snapshotting aggregate place expressions before
6813
/// evaluating later arguments. Aggregates are represented by addresses in the
6814
/// IL, so retaining the original address would let a later argument mutation
6815
/// change the value already supplied for this argument.
6816
unsafe fn lowerCallArg(self: &mut FnLowerer, arg: *ast::Node, hasLater: bool) -> il::Val
6817
    throws (LowerError)
6818
{
6819
    let val = try lowerExpr(self, arg);
6820
6821
    if hasLater and ast::isPlaceExpr(arg) {
6822
        let argType = try effectiveType(self, arg);
6823
        if isAggregateType(argType) {
6824
            return try emitStackVal(self, argType, val);
6825
        }
6826
    }
6827
    return val;
6828
}
6829
6830
/// Emit a function call with return-parameter and small-aggregate handling.
6831
///
6832
/// All call lowering paths (regular, trait method, standalone method) converge
6833
/// here after preparing the callee value, function type, and argument array.
6834
/// The `args` slice must already include a slot at index zero for the hidden
6835
/// return parameter; that slot is filled by this function.
6836
unsafe fn emitCallValue(
6837
    self: &mut FnLowerer,
6838
    callee: il::Val,
6839
    fnInfo: *resolver::FnType,
6840
    args: *unsafe mut [il::Val],
6841
) -> il::Val throws (LowerError) {
6842
    let retTy = *fnInfo.returnType;
6843
6844
    if requiresReturnParam(fnInfo) {
6845
        if fnInfo.throwList.len > 0 {
6846
            let layout = resolver::getResultLayout(retTy, fnInfo.throwList);
6847
            set args[0] = il::Val::Reg(emitReserveLayout(self, layout));
6848
        } else {
6849
            set args[0] = il::Val::Reg(try emitReserve(self, retTy));
6850
        }
6851
        let dst = nextReg(self);
6852
6853
        emit(self, il::Instr::Call {
6854
            retTy: il::Type::W64,
6855
            dst,
6856
            func: callee,
6857
            args,
6858
        });
6859
        return il::Val::Reg(dst);
6860
    }
6861
    let mut dst: ?il::Reg = nil;
6862
    if retTy <> resolver::Type::Void and retTy <> resolver::Type::Never {
6863
        set dst = nextReg(self);
6864
    }
6865
    emit(self, il::Instr::Call {
6866
        retTy: ilType(self.low, retTy),
6867
        dst,
6868
        func: callee,
6869
        args,
6870
    });
6871
6872
    if retTy == resolver::Type::Never {
6873
        emit(self, il::Instr::Unreachable);
6874
    }
6875
    if let d = dst {
6876
        if isSmallAggregate(retTy) {
6877
            let slot = emitReserveLayout(self, resolver::Layout {
6878
                size: resolver::PTR_SIZE,
6879
                alignment: resolver::PTR_SIZE,
6880
            });
6881
            emit(self, il::Instr::Store {
6882
                typ: il::Type::W64,
6883
                src: il::Val::Reg(d),
6884
                dst: slot,
6885
                offset: 0,
6886
            });
6887
            return il::Val::Reg(slot);
6888
        }
6889
        return il::Val::Reg(d);
6890
    }
6891
    return il::Val::Undef;
6892
}
6893
6894
/// Lower a method receiver expression to a pointer value.
6895
///
6896
/// If the parent is already a pointer type, the value is used directly.
6897
/// If the parent is a value type (eg. a local record), its address is taken.
6898
unsafe fn lowerReceiver(self: &mut FnLowerer, parent: *ast::Node, parentTy: resolver::Type) -> il::Val
6899
    throws (LowerError)
6900
{
6901
    if let case resolver::Type::Pointer { .. } = parentTy {
6902
        // Already a pointer: lower and use directly.
6903
        return try lowerExpr(self, parent);
6904
    }
6905
    // Value type: take its address by lowering it and returning the slot pointer.
6906
    // Aggregate types are already lowered as pointers to stack slots.
6907
    let val = try lowerExpr(self, parent);
6908
    if isAggregateType(parentTy) {
6909
        return val;
6910
    }
6911
    // Scalar value: store to a stack slot and return the slot pointer.
6912
    let layout = resolver::getLayout(self.low.resolver, parent, parentTy);
6913
    let slot = emitReserveLayout(self, layout);
6914
    try emitStore(self, slot, 0, parentTy, val);
6915
6916
    return il::Val::Reg(slot);
6917
}
6918
6919
/// Lower a standalone method call via direct dispatch.
6920
///
6921
/// Given `obj.method(args)` where `method` is a standalone method on a concrete type,
6922
/// emits a direct call with the receiver address as the first argument:
6923
///
6924
///     call <retTy> %ret @Type::method(&obj, args...)
6925
///
6926
unsafe fn lowerMethodCall(
6927
    self: &mut FnLowerer,
6928
    node: *ast::Node,
6929
    call: ast::Call,
6930
    method: &resolver::MethodEntry,
6931
) -> il::Val throws (LowerError) {
6932
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
6933
        else throw LowerError::MissingMetadata;
6934
6935
    // Get the receiver as a pointer.
6936
    let parentTy = try typeOf(self, access.parent);
6937
    let receiverVal = try lowerReceiver(self, access.parent, parentTy);
6938
6939
    let qualName = instanceMethodName(self.low, nil, method.concreteTypeName, method.name);
6940
    let case resolver::SymbolData::Value { type: resolver::Type::Fn(fnInfo), .. } = method.symbol.data
6941
        else panic "lowerMethodCall: expected Fn type on method symbol";
6942
6943
    // Build args: optional return param slot + receiver + user args.
6944
    let argOffset: u32 = 1 if requiresReturnParam(fnInfo) else 0;
6945
    let args = try allocVals(self, call.args.len + 1 + argOffset);
6946
    set args[argOffset] = receiverVal;
6947
    for arg, i in call.args {
6948
        set args[i + 1 + argOffset] = try lowerCallArg(
6949
            self, arg, i + 1 < call.args.len
6950
        );
6951
    }
6952
    return try emitCallValue(self, il::Val::FnAddr(qualName), fnInfo, args);
6953
}
6954
6955
/// Check if a call is to a compiler intrinsic and lower it directly.
6956
unsafe fn lowerIntrinsicCall(self: &mut FnLowerer, call: ast::Call) -> ?il::Val throws (LowerError) {
6957
    // Get the callee symbol and check if it's marked as an intrinsic.
6958
    let sym = resolver::nodeData(self.low.resolver, call.callee).sym else {
6959
        // Expressions or function pointers may not have an associated symbol.
6960
        return nil;
6961
    };
6962
    if not ast::hasAttribute(sym.attrs, ast::Attribute::Intrinsic) {
6963
        return nil;
6964
    }
6965
    // Check for known intrinsic names.
6966
    if mem::eq(sym.name, "ecall") {
6967
        return try lowerEcall(self, call);
6968
    } else if mem::eq(sym.name, "ebreak") {
6969
        return try lowerEbreak(self, call);
6970
    } else if mem::eq(sym.name, "memoryFence") {
6971
        return try lowerMemoryFence(self, call);
6972
    } else {
6973
        throw LowerError::UnknownIntrinsic;
6974
    }
6975
}
6976
6977
/// Lower an ecall intrinsic: `ecall(num, a0, a1, a2, a3) -> i32`.
6978
unsafe fn lowerEcall(self: &mut FnLowerer, call: ast::Call) -> il::Val throws (LowerError) {
6979
    if call.args.len <> 5 {
6980
        throw LowerError::InvalidArgCount;
6981
    }
6982
    let num = try lowerExpr(self, call.args[0]);
6983
    let a0 = try lowerExpr(self, call.args[1]);
6984
    let a1 = try lowerExpr(self, call.args[2]);
6985
    let a2 = try lowerExpr(self, call.args[3]);
6986
    let a3 = try lowerExpr(self, call.args[4]);
6987
    let dst = nextReg(self);
6988
6989
    emit(self, il::Instr::Ecall { dst, num, a0, a1, a2, a3 });
6990
6991
    return il::Val::Reg(dst);
6992
}
6993
6994
/// Lower an ebreak intrinsic: `ebreak()`.
6995
unsafe fn lowerEbreak(self: &mut FnLowerer, call: ast::Call) -> il::Val throws (LowerError) {
6996
    if call.args.len <> 0 {
6997
        throw LowerError::InvalidArgCount;
6998
    }
6999
    emit(self, il::Instr::Ebreak);
7000
7001
    return il::Val::Undef;
7002
}
7003
7004
/// Lower `memoryFence()`.
7005
unsafe fn lowerMemoryFence(self: &mut FnLowerer, call: ast::Call) -> il::Val throws (LowerError) {
7006
    if call.args.len <> 0 {
7007
        throw LowerError::InvalidArgCount;
7008
    }
7009
    emit(self, il::Instr::MemoryFence);
7010
    return il::Val::Undef;
7011
}
7012
7013
/// Resolve callee to an IL value. For direct function calls, use the symbol name.
7014
/// For variables holding function pointers or complex expressions (eg. `array[i]()`),
7015
/// lower the callee expression.
7016
unsafe fn lowerCallee(self: &mut FnLowerer, callee: *ast::Node) -> il::Val throws (LowerError) {
7017
    if let sym = resolver::nodeData(self.low.resolver, callee).sym {
7018
        if let case ast::NodeValue::FnDecl(_) = sym.node.value {
7019
            // First try to look up the symbol in our registered functions.
7020
            // This handles cross-package calls correctly, since packages are
7021
            // lowered in dependency order.
7022
            if let qualName = lookupFnSym(self.low, sym) {
7023
                return il::Val::FnAddr(qualName);
7024
            }
7025
            // Fall back to computing the qualified name from the module graph.
7026
            // This works for functions in the current package.
7027
            let modId = resolver::moduleIdForSymbol(self.low.resolver, sym) else {
7028
                throw LowerError::MissingMetadata;
7029
            };
7030
            return il::Val::FnAddr(qualifyName(self.low, modId, sym.name));
7031
        }
7032
    }
7033
    return try lowerExpr(self, callee);
7034
}
7035
7036
/// Lower a function call expression.
7037
unsafe fn lowerCall(self: &mut FnLowerer, node: *ast::Node, call: ast::Call) -> il::Val throws (LowerError) {
7038
    // Check for intrinsic calls before normal call lowering.
7039
    if let intrinsicVal = try lowerIntrinsicCall(self, call) {
7040
        return intrinsicVal;
7041
    }
7042
    let calleeTy = try typeOf(self, call.callee);
7043
    let case resolver::Type::Fn(fnInfo) = calleeTy else {
7044
        throw LowerError::ExpectedFunction;
7045
    };
7046
    let callee = try lowerCallee(self, call.callee);
7047
    let offset: u32 = 1 if requiresReturnParam(fnInfo) else 0;
7048
    let args = try allocVals(self, call.args.len + offset);
7049
    for arg, i in call.args {
7050
        set args[i + offset] = try lowerCallArg(
7051
            self, arg, i + 1 < call.args.len
7052
        );
7053
    }
7054
7055
    return try emitCallValue(self, callee, fnInfo, args);
7056
}
7057
7058
/// Apply coercions requested by the resolver.
7059
unsafe fn applyCoercion(self: &mut FnLowerer, node: *ast::Node, val: il::Val) -> il::Val throws (LowerError) {
7060
    let coerce = resolver::coercionFor(self.low.resolver, node) else {
7061
        return val;
7062
    };
7063
    match coerce {
7064
        case resolver::Coercion::OptionalLift(optType) => {
7065
            if let case ast::NodeValue::Nil = node.value {
7066
                return try buildNilOptional(self, optType);
7067
            }
7068
            return try wrapInOptional(self, val, optType);
7069
        }
7070
        case resolver::Coercion::NumericCast { from, to } => {
7071
            return lowerNumericCast(self, val, from, to);
7072
        }
7073
        case resolver::Coercion::ResultWrap => {
7074
            let payloadType = *self.fnType.returnType;
7075
            return try buildResult(self, 0, val, payloadType);
7076
        }
7077
        case resolver::Coercion::TraitObject { traitInfo, inst } => {
7078
            return try buildTraitObject(self, val, traitInfo, inst);
7079
        }
7080
        case resolver::Coercion::Identity => return val,
7081
    }
7082
}
7083
7084
/// Lower an implicit numeric cast coercion.
7085
///
7086
/// Handles widening conversions between integer types. Uses sign-extension
7087
/// for signed source types and zero-extension for unsigned source types.
7088
unsafe fn lowerNumericCast(self: &mut FnLowerer, val: il::Val, srcType: resolver::Type, dstType: resolver::Type) -> il::Val {
7089
    let srcLayout = resolver::getTypeLayout(srcType);
7090
    let dstLayout = resolver::getTypeLayout(dstType);
7091
7092
    if srcLayout.size == dstLayout.size {
7093
        // Same size: bit pattern is unchanged, value is returned as-is.
7094
        return val;
7095
    }
7096
    // Widening: extend based on source signedness.
7097
    // Narrowing: truncate and normalize to destination width.
7098
    let widening = srcLayout.size < dstLayout.size;
7099
    let extType = ilType(self.low, srcType) if widening else ilType(self.low, dstType);
7100
    let signed = isSignedType(srcType) if widening else isSignedType(dstType);
7101
    let dst = nextReg(self);
7102
7103
    if signed {
7104
        emit(self, il::Instr::Sext { typ: extType, dst, val });
7105
    } else {
7106
        emit(self, il::Instr::Zext { typ: extType, dst, val });
7107
    }
7108
    return il::Val::Reg(dst);
7109
}
7110
7111
/// Lower a global value symbol.
7112
unsafe fn lowerGlobalValue(self: &mut FnLowerer, sym: *unsafe resolver::Symbol, ty: resolver::Type) -> il::Val {
7113
    // Function pointer reference: return the function's address directly.
7114
    // Functions have no separate storage cell in the data section.
7115
    if let case resolver::Type::Fn(_) = ty {
7116
        return il::Val::Reg(emitFnAddr(self, sym));
7117
    }
7118
    let src = emitDataAddr(self, sym);
7119
7120
    return emitRead(self, src, 0, ty);
7121
}
7122
7123
/// Lower an identifier that refers to a global symbol.
7124
unsafe fn lowerGlobalSymbol(self: &mut FnLowerer, node: *ast::Node) -> il::Val throws (LowerError) {
7125
    // First try to get a compile-time constant value.
7126
    if let constVal = resolver::constValueEntry(self.low.resolver, node) {
7127
        return try constValueToVal(self, constVal, node);
7128
    }
7129
    // Otherwise get the symbol.
7130
    let sym = try symOf(self, node);
7131
7132
    match sym.data {
7133
        case resolver::SymbolData::Constant { type, .. } => {
7134
            let src = emitDataAddr(self, sym);
7135
7136
            return emitRead(self, src, 0, type);
7137
        }
7138
        case resolver::SymbolData::Value { type, .. } =>
7139
            return lowerGlobalValue(self, sym, type),
7140
        else => throw LowerError::UnexpectedNodeValue(node),
7141
    }
7142
}
7143
7144
/// Lower an assignment to a static variable.
7145
unsafe fn lowerStaticAssign(self: &mut FnLowerer, target: *ast::Node, val: il::Val) throws (LowerError) {
7146
    let sym = try symOf(self, target);
7147
    let case resolver::SymbolData::Value { type, .. } = sym.data else {
7148
        throw LowerError::ImmutableAssignment;
7149
    };
7150
    let dst = emitDataAddr(self, sym);
7151
7152
    try emitStore(self, dst, 0, type, val);
7153
}
7154
7155
/// Lower a scope access expression like `Module::Const` or `Union::Variant`.
7156
/// This doesn't handle record literal variants.
7157
unsafe fn lowerScopeAccess(self: &mut FnLowerer, node: *ast::Node) -> il::Val throws (LowerError) {
7158
    // First try to get a compile-time constant value.
7159
    if let constVal = resolver::constValueEntry(self.low.resolver, node) {
7160
        return try constValueToVal(self, constVal, node);
7161
    }
7162
    // Otherwise get the associated symbol.
7163
    let data = resolver::nodeData(self.low.resolver, node);
7164
    let sym = data.sym else {
7165
        throw LowerError::MissingSymbol(node);
7166
    };
7167
    match sym.data {
7168
        case resolver::SymbolData::Variant { index, .. } => {
7169
            let mut indexValue = index as i64;
7170
            if let idx = voidVariantIndex(self.low.resolver, node) {
7171
                set indexValue = idx;
7172
            }
7173
            // Void union variant like `Option::None`.
7174
            if data.ty == resolver::Type::Unknown {
7175
                throw LowerError::MissingType(node);
7176
            }
7177
            // All-void unions are passed as scalars (the tag byte).
7178
            // Return an immediate instead of building a tagged aggregate.
7179
            if resolver::isVoidUnion(data.ty) {
7180
                return il::Val::Imm(indexValue);
7181
            }
7182
            let unionInfo = unionInfoFromType(data.ty) else {
7183
                throw LowerError::MissingMetadata;
7184
            };
7185
            let valOffset = unionInfo.valOffset as i32;
7186
            return try buildTagged(self, resolver::getTypeLayout(data.ty), indexValue, nil, resolver::Type::Void, 1, valOffset);
7187
        }
7188
        case resolver::SymbolData::Constant { type, .. } => {
7189
            // Constant without compile-time value (e.g. record constant);
7190
            // load from data section.
7191
            let src = emitDataAddr(self, sym);
7192
7193
            // Aggregate constants live in read-only memory.  Return a
7194
            // mutable copy so that callers that assign through the
7195
            // resulting pointer do not fault.
7196
            if isAggregateType(type) {
7197
                let layout = resolver::getTypeLayout(type);
7198
                let dst = emitReserveLayout(self, layout);
7199
                emit(self, il::Instr::Blit { dst, src, size: il::Val::Imm(layout.size as i64) });
7200
7201
                return il::Val::Reg(dst);
7202
            }
7203
            return emitRead(self, src, 0, type);
7204
        }
7205
        case resolver::SymbolData::Value { type, .. } =>
7206
            return lowerGlobalValue(self, sym, type),
7207
        else =>
7208
            throw LowerError::UnexpectedNodeValue(node),
7209
    }
7210
}
7211
7212
/// Lower an expression AST node to an IL value.
7213
/// This is the main expression dispatch, all expression nodes go through here.
7214
unsafe fn lowerExpr(self: &mut FnLowerer, node: *ast::Node) -> il::Val throws (LowerError) {
7215
    if self.low.options.debug {
7216
        set self.srcLoc.offset = node.span.offset;
7217
    }
7218
    let mut val: il::Val = undefined;
7219
7220
    match node.value {
7221
        case ast::NodeValue::Ident(_) => {
7222
            // First try local variable lookup.
7223
            // Otherwise fall back to global symbol lookup.
7224
            if let v = lookupLocalVar(self, node) {
7225
                set val = try useVar(self, v);
7226
                if self.vars[*v].addressTaken {
7227
                    let typ = try typeOf(self, node);
7228
                    let ptr = emitValToReg(self, val);
7229
                    set val = emitRead(self, ptr, 0, typ);
7230
                }
7231
            } else {
7232
                set val = try lowerGlobalSymbol(self, node);
7233
            }
7234
        }
7235
        case ast::NodeValue::ScopeAccess(_) => {
7236
            set val = try lowerScopeAccess(self, node);
7237
        }
7238
        case ast::NodeValue::Number(lit) => {
7239
            set val = il::Val::Imm(lit.magnitude as i64);
7240
        }
7241
        case ast::NodeValue::Bool(b) => {
7242
            set val = il::Val::Imm(1) if b else il::Val::Imm(0);
7243
        }
7244
        case ast::NodeValue::Char(c) => {
7245
            set val = il::Val::Imm(c as i64);
7246
        }
7247
        case ast::NodeValue::Nil => {
7248
            let typ = try typeOf(self, node);
7249
            if let case resolver::Type::Optional(_) = typ {
7250
                set val = try buildNilOptional(self, typ);
7251
            } else if let case resolver::Type::Nil = typ {
7252
                // Standalone `nil` without a concrete optional type. We can't
7253
                // generate a proper value representation.
7254
                throw LowerError::MissingType(node);
7255
            } else {
7256
                throw LowerError::NilInNonOptional;
7257
            }
7258
        }
7259
        case ast::NodeValue::RecordLit(lit) => {
7260
            set val = try lowerRecordLit(self, node, lit);
7261
        }
7262
        case ast::NodeValue::AddressOf(addr) => {
7263
            set val = try lowerAddressOf(self, node, addr);
7264
        }
7265
        case ast::NodeValue::Deref(target) => {
7266
            set val = try lowerDeref(self, node, target);
7267
        }
7268
        case ast::NodeValue::BinOp(binop) => {
7269
            set val = try lowerBinOp(self, node, binop);
7270
        }
7271
        case ast::NodeValue::UnOp(unop) => {
7272
            set val = try lowerUnOp(self, node, unop);
7273
        }
7274
        case ast::NodeValue::Subscript { container, index } => {
7275
            set val = try lowerSubscript(self, node, container, index);
7276
        }
7277
        case ast::NodeValue::BuiltinCall { kind, args } => {
7278
            set val = try lowerBuiltinCall(self, node, kind, args);
7279
        }
7280
        case ast::NodeValue::Call(call) => {
7281
            set val = try lowerCallOrCtor(self, node, call);
7282
        }
7283
        case ast::NodeValue::Try(t) => {
7284
            set val = try lowerTry(self, node, t);
7285
        }
7286
        case ast::NodeValue::FieldAccess(access) => {
7287
            // Check for compile-time constant (e.g., `arr.len` on fixed-size arrays).
7288
            if let constVal = resolver::constValueEntry(self.low.resolver, node) {
7289
                match constVal {
7290
                    // TODO: Handle `u32` values that don't fit in an `i32`.
7291
                    //       Perhaps just store the `ConstInt`.
7292
                    case resolver::ConstValue::Int(i) => set val = il::Val::Imm(constIntToI64(i)),
7293
                    else => set val = try lowerFieldAccess(self, access),
7294
                }
7295
            } else {
7296
                set val = try lowerFieldAccess(self, access);
7297
            }
7298
        }
7299
        case ast::NodeValue::ArrayLit(elements) => {
7300
            set val = try lowerArrayLit(self, node, elements);
7301
        }
7302
        case ast::NodeValue::ArrayRepeatLit(repeat) => {
7303
            set val = try lowerArrayRepeatLit(self, node, repeat);
7304
        }
7305
        case ast::NodeValue::As(cast) => {
7306
            set val = try lowerCast(self, node, cast);
7307
        }
7308
        case ast::NodeValue::CondExpr(cond) => {
7309
            set val = try lowerCondExpr(self, node, cond);
7310
        }
7311
        case ast::NodeValue::String(s) => {
7312
            set val = try lowerStringLit(self, node, s);
7313
        }
7314
        case ast::NodeValue::Undef => {
7315
            let typ = try typeOf(self, node);
7316
            if isAggregateType(typ) {
7317
                // When `undefined` appears as a stand-alone expression,
7318
                /// we need a stack slot for reads and writes.
7319
                let slot = try emitReserve(self, typ);
7320
                set val = il::Val::Reg(slot);
7321
            } else {
7322
                set val = il::Val::Undef;
7323
            }
7324
        }
7325
        case ast::NodeValue::Panic { .. } => {
7326
            // Panic in expression context (e.g. match arm). Emit unreachable
7327
            // and return a dummy value since control won't continue.
7328
            emit(self, il::Instr::Unreachable);
7329
            set val = il::Val::Undef;
7330
        }
7331
        case ast::NodeValue::Assert { .. } => {
7332
            // Assert in expression context. Lower as statement, return `void`.
7333
            try lowerNode(self, node);
7334
            set val = il::Val::Undef;
7335
        }
7336
        case ast::NodeValue::Block(_) => {
7337
            try lowerBlock(self, node);
7338
            set val = il::Val::Undef;
7339
        }
7340
        case ast::NodeValue::ExprStmt(expr) => {
7341
            let _ = expr;
7342
            set val = il::Val::Undef;
7343
        }
7344
        // Lower these as statements.
7345
        case ast::NodeValue::ConstDecl(decl) => {
7346
            try registerLocalDataDeclName(self, node);
7347
            try lowerDataDecl(self.low, node, decl.value, true);
7348
            set val = il::Val::Undef;
7349
        }
7350
        case ast::NodeValue::StaticDecl(decl) => {
7351
            try registerLocalDataDeclName(self, node);
7352
            try lowerDataDecl(self.low, node, decl.value, false);
7353
            set val = il::Val::Undef;
7354
        }
7355
        case ast::NodeValue::Throw { .. },
7356
             ast::NodeValue::Return { .. },
7357
             ast::NodeValue::Continue,
7358
             ast::NodeValue::Break => {
7359
            try lowerNode(self, node);
7360
            set val = il::Val::Undef;
7361
        }
7362
        else => {
7363
            panic "lowerExpr: node is not an expression";
7364
        }
7365
    }
7366
    return try applyCoercion(self, node, val);
7367
}
7368
7369
/// Translate a Radiance type to an IL type.
7370
///
7371
/// The IL type system is much simpler than Radiance's, only primitive types
7372
/// are used. If a Radiance type doesn't fit in a machine word, it is passed
7373
/// by reference.
7374
///
7375
/// The IL doesn't track signedness - that's encoded in the instructions
7376
/// (e.g., Slt vs Ult).
7377
unsafe fn ilType(self: &mut Lowerer, typ: resolver::Type) -> il::Type {
7378
    match typ {
7379
        case resolver::Type::Bool,
7380
             resolver::Type::I8,
7381
             resolver::Type::U8 => return il::Type::W8,
7382
        case resolver::Type::I16,
7383
             resolver::Type::U16 => return il::Type::W16,
7384
        case resolver::Type::I32,
7385
             resolver::Type::U32 => return il::Type::W32,
7386
        case resolver::Type::I64,
7387
             resolver::Type::U64,
7388
             resolver::Type::Pointer { .. },
7389
             resolver::Type::Slice { .. },
7390
             resolver::Type::TraitObject { .. },
7391
             resolver::Type::Array(_),
7392
             resolver::Type::Optional(_),
7393
             resolver::Type::Fn(_) => return il::Type::W64,
7394
        case resolver::Type::Nominal(_) => {
7395
            if resolver::isVoidUnion(typ) {
7396
                return il::Type::W8;
7397
            }
7398
            return il::Type::W64;
7399
        }
7400
        case resolver::Type::Void, resolver::Type::Never => return il::Type::W64,
7401
        // [`Type::Int`] is the type of unsuffixed integer literals and their
7402
        // compound expressions (e.g. `1 + 2`). It defaults to W64 (i64) here,
7403
        // matching the native word size on RV64. It cannot be resolved earlier
7404
        // because the resolver uses [`Type::Int`] to distinguish unsuffixed
7405
        // expressions from explicitly typed ones, which affects coercion
7406
        // behavior (e.g. implicit narrowing).
7407
        case resolver::Type::Int => return il::Type::W64,
7408
        case resolver::Type::Opaque => panic "ilType: opaque type must be behind a pointer",
7409
        else => panic "ilType: type cannot be lowered",
7410
    }
7411
}