vj-codegen 0.1.0

LLVM code generator of the vj SystemVerilog simulator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! The bit-level system functions (LRM 1800-2023 §20.5, §20.8, §20.9):
//! `$signed`/`$unsigned`, `$clog2`, `$countbits`/`$countones`, `$onehot`/
//! `$onehot0` and `$isunknown`. A call with constant arguments folds
//! through slang; otherwise it is computed from the argument's value and
//! unknown lanes (an X bit has val 0 / unk 1, a Z bit val 1 / unk 1).

use inkwell::IntPredicate;
use inkwell::values::IntValue;
use sv_lang::KnownSystemName;

use crate::error::LoweringError;
use crate::expr::{LowerCtx, LoweredValue, lower_expr, lower_expr_h};
use crate::ops::OpBuilder;
use crate::types::TypeWidth;
use crate::value::{PackedValue, RealValue};

/// Lowers `e`, a call to the system function `name`, when it is one of
/// this module's; `None` otherwise.
pub(crate) fn lower_bit_sysfunc<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    name: KnownSystemName,
    e: sv_lang::Expression<'d>,
) -> Option<Result<LoweredValue<'ctx>, LoweringError>> {
    if !is_bit_sysfunc_name(name) {
        return None;
    }
    Some(lower(cx, name, e))
}

/// Whether `name` is one of this module's bit-level system functions.
pub(crate) fn is_bit_sysfunc_name(name: KnownSystemName) -> bool {
    use KnownSystemName as K;
    matches!(
        name,
        K::Signed
            | K::Unsigned
            | K::Clog2
            | K::CountBits
            | K::CountOnes
            | K::OneHot
            | K::OneHot0
            | K::IsUnknown
    )
}

/// Whether `e` contains a `==?`/`!=?` (LRM 11.4.6). slang's constant fold of
/// one (`condWildcardEqual`) answers `x` as soon as the left operand has an
/// unknown bit under a non-wildcard position, even when another position
/// definitely mismatches -- which LRM 11.4.6 says is false (`1'b0`), as the
/// run-time lowering answers. `$signed(3'bz11 ==? 3'b00x)` is `0`, not `x`.
fn has_wildcard_compare(e: sv_lang::Expression<'_>) -> bool {
    use sv_lang::BinaryOp;
    (e.kind() == sv_lang::kinds::ExpressionKind::BinaryOp
        && matches!(
            e.binary_op(),
            Some(BinaryOp::WildcardEquality | BinaryOp::WildcardInequality)
        ))
        || e.operands().into_iter().any(has_wildcard_compare)
}

fn lower<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    name: KnownSystemName,
    e: sv_lang::Expression<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    use KnownSystemName as K;
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    // Constant arguments: slang has already evaluated the call -- except over
    // a wildcard comparison, whose slang fold is wrong (see
    // `has_wildcard_compare`); that lowers at run time instead.
    if !has_wildcard_compare(e)
        && let Some(iv) = e.constant_value().as_ref().and_then(|c| c.as_integer())
    {
        return crate::expr::lower_constant(cx, iv, Some(e));
    }
    let args = e.operands();
    let arg0 = *args.first().ok_or_else(|| {
        LoweringError::unsupported_at("system function with no argument", &cx.fn_sym)
    })?;
    let arg = lower_expr_h(cx, arg0)?;
    if let LoweredValue::Huge(h) = arg {
        return crate::huge::sysfunc(cx, name, e, h);
    }
    let x = arg.into_packed(
        "a bit-level system function of a real or >128-bit value",
        &cx.fn_sym,
    )?;
    let ret = e.expr_type().ok_or_else(|| {
        LoweringError::unsupported_at("system function call has no type", &cx.fn_sym)
    })?;
    let ret_width = ret.value_width();
    let val = op.lane_val(x);
    let unk = op.lane_unk(x);
    let ty = op.i_n(x.width);
    // Result helpers: a known value of the call's type, or all-X.
    let known = |v: IntValue<'ctx>| {
        let v = fit(cx, v, ret_width);
        op.pack(
            v,
            op.i_n(ret_width).const_zero(),
            ret_width,
            cx.repr,
            ret.is_signed(),
        )
    };
    let popcount = |bits: IntValue<'ctx>| -> IntValue<'ctx> {
        let f = inkwell::intrinsics::Intrinsic::find("llvm.ctpop")
            .and_then(|i| i.get_declaration(cx.module, &[ty.into()]))
            .expect("llvm.ctpop");
        cx.b.build_call(f, &[bits.into()], "popcount")
            .unwrap()
            .try_as_basic_value()
            .basic()
            .expect("ctpop returns a value")
            .into_int_value()
    };
    let ones = cx.b.build_and(val, op.not(unk), "ones").unwrap();
    let v = match name {
        // Same bits, the other signedness.
        K::Signed | K::Unsigned => PackedValue {
            signed: name == K::Signed,
            ..x
        },
        K::CountOnes => known(popcount(ones)),
        K::OneHot | K::OneHot0 => {
            let n = popcount(ones);
            let pred = if name == K::OneHot {
                IntPredicate::EQ
            } else {
                IntPredicate::ULE
            };
            let bit =
                cx.b.build_int_compare(pred, n, ty.const_int(1, false), "onehot")
                    .unwrap();
            known(bit)
        }
        K::IsUnknown => {
            let bit =
                cx.b.build_int_compare(IntPredicate::NE, unk, ty.const_zero(), "isunknown")
                    .unwrap();
            known(bit)
        }
        K::CountBits => {
            // The bit values counted: each control argument's value.
            let mut mask = ty.const_zero();
            for c in args.iter().skip(1) {
                let const_bit = c
                    .constant_value()
                    .as_ref()
                    .and_then(|cv| cv.as_integer())
                    .and_then(|i| i.bit(0));
                let zeros = cx.b.build_and(op.not(val), op.not(unk), "zeros").unwrap();
                let xs = cx.b.build_and(op.not(val), unk, "xs").unwrap();
                let zs = cx.b.build_and(val, unk, "zs").unwrap();
                let lanes = if let Some(bit) = const_bit {
                    if bit == sv_lang::Bit::One {
                        ones
                    } else if bit == sv_lang::Bit::Zero {
                        zeros
                    } else if bit == sv_lang::Bit::X {
                        xs
                    } else {
                        zs
                    }
                } else {
                    // Run-time control bit (LRM 20.9): bit 0 of the argument
                    // picks the lane set, unknown bits select X (val 0) or Z.
                    let cv = lower_expr_h(cx, *c)?.into_packed(
                        "a $countbits control bit of a real or >128-bit value",
                        &cx.fn_sym,
                    )?;
                    let i1 = cx.ctx.bool_type();
                    let cval =
                        cx.b.build_int_truncate(op.lane_val(cv), i1, "cb_v")
                            .unwrap();
                    let cunk =
                        cx.b.build_int_truncate(op.lane_unk(cv), i1, "cb_u")
                            .unwrap();
                    let known_pick =
                        cx.b.build_select(cval, ones, zeros, "cb_k")
                            .unwrap()
                            .into_int_value();
                    let unk_pick =
                        cx.b.build_select(cval, zs, xs, "cb_x")
                            .unwrap()
                            .into_int_value();
                    cx.b.build_select(cunk, unk_pick, known_pick, "cb_lanes")
                        .unwrap()
                        .into_int_value()
                };
                mask = cx.b.build_or(mask, lanes, "countbits_mask").unwrap();
            }
            known(popcount(mask))
        }
        K::Clog2 => {
            // ceil(log2(x)): 0 for x <= 1, else width - clz(x - 1); any
            // unknown bit gives X.
            let f = inkwell::intrinsics::Intrinsic::find("llvm.ctlz")
                .and_then(|i| i.get_declaration(cx.module, &[ty.into()]))
                .expect("llvm.ctlz");
            let one = ty.const_int(1, false);
            let xm1 = cx.b.build_int_sub(val, one, "clog2_xm1").unwrap();
            let clz =
                cx.b.build_call(
                    f,
                    &[xm1.into(), cx.ctx.bool_type().const_zero().into()],
                    "clz",
                )
                .unwrap()
                .try_as_basic_value()
                .basic()
                .expect("ctlz returns a value")
                .into_int_value();
            let bits =
                cx.b.build_int_sub(ty.const_int(u64::from(x.width), false), clz, "clog2_bits")
                    .unwrap();
            let small =
                cx.b.build_int_compare(IntPredicate::ULE, val, one, "clog2_small")
                    .unwrap();
            let r =
                cx.b.build_select(small, ty.const_zero(), bits, "clog2")
                    .unwrap()
                    .into_int_value();
            let any_unk =
                cx.b.build_int_compare(IntPredicate::NE, unk, ty.const_zero(), "clog2_unk")
                    .unwrap();
            let rw = op.i_n(ret_width);
            let unk_lane =
                cx.b.build_select(any_unk, rw.const_all_ones(), rw.const_zero(), "clog2_x")
                    .unwrap()
                    .into_int_value();
            let r = fit(cx, r, ret_width);
            let r =
                cx.b.build_select(any_unk, rw.const_zero(), r, "clog2_v")
                    .unwrap()
                    .into_int_value();
            op.pack(r, unk_lane, ret_width, cx.repr, ret.is_signed())
        }
        _ => unreachable!("filtered by lower_bit_sysfunc"),
    };
    Ok(LoweredValue::Packed(v))
}

/// `$cast(dest, src)` (LRM 1800-2023 §6.24.2, §8.16): when `src` is a legal
/// value of `dest`'s type -- for an enum, one of its members; for a class
/// handle, null or a handle whose object's DYNAMIC class is the destination
/// class or derives from / implements it; any other integral or real type
/// takes every value -- assigns it (converted) and yields 1, else leaves
/// `dest` alone and yields 0. The expression (function) form.
pub(crate) fn lower_cast<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    lower_cast_with(cx, e, false)
}

/// The task form (`$cast(dest, src);`, LRM 6.24.2): a failed cast is a
/// run-time error -- reported like `$fatal`, after which the process ends --
/// instead of a result of 0.
pub(crate) fn lower_cast_stmt<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
) -> Result<(), LoweringError> {
    lower_cast_with(cx, e, true)?;
    Ok(())
}

fn lower_cast_with<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    e: sv_lang::Expression<'d>,
    task_form: bool,
) -> Result<LoweredValue<'ctx>, LoweringError> {
    let ops = e.operands();
    let (Some(&dest), Some(&src)) = (ops.first(), ops.get(1)) else {
        return Err(LoweringError::unsupported_at(
            "$cast needs two arguments",
            &cx.fn_sym,
        ));
    };
    let dest = if dest.kind() == sv_lang::kinds::ExpressionKind::Assignment {
        dest.left().unwrap_or(dest)
    } else {
        dest
    };
    let dty = dest
        .expr_type()
        .ok_or_else(|| LoweringError::unsupported_at("$cast target has no type", &cx.fn_sym))?;
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    let width = dty.value_width();
    // LRM 6.24.2: a singular `$cast` is an assignment, so a real source into
    // an integral destination rounds (6.12.1) and an integral source into a
    // real destination converts by value; the storage bits are never
    // reinterpreted.
    let sty_floating = src.expr_type().is_some_and(|t| t.is_floating());
    let srcv = lower_expr(cx, src)?;
    let srcv = match srcv {
        LoweredValue::Real(r) if !dty.is_floating() && dty.is_integral() && width <= 64 => {
            let fty = r.llvm.get_type();
            let diff = cx.b.build_float_sub(r.llvm, r.llvm, "cast_vmv").unwrap();
            let bad =
                cx.b.build_float_compare(inkwell::FloatPredicate::UNO, diff, diff, "cast_bad")
                    .unwrap();
            let safe =
                cx.b.build_select(bad, fty.const_zero(), r.llvm, "cast_safe")
                    .unwrap()
                    .into_float_value();
            let rounded = op.round_real_to_int(RealValue { llvm: safe }, width, dty.is_signed());
            let wty = op.i_n(width);
            let unk = if dty.is_four_state() {
                cx.b.build_select(bad, wty.const_all_ones(), wty.const_zero(), "cast_unk")
                    .unwrap()
                    .into_int_value()
            } else {
                wty.const_zero()
            };
            LoweredValue::Packed(op.pack(rounded, unk, width, cx.repr, dty.is_signed()))
        }
        LoweredValue::Packed(pv) if dty.is_floating() && !sty_floating => {
            match crate::real::packed_to_real(cx, pv) {
                Some(r) => LoweredValue::Real(r),
                None => LoweredValue::Packed(pv),
            }
        }
        other => other,
    };
    let v = crate::real::to_storage(cx, srcv, width, "a >128-bit $cast")?;
    let v = crate::select::fit_width(&op, v, width);
    let v = PackedValue {
        signed: dty.is_signed(),
        ..v
    };
    let bool_ty = cx.ctx.bool_type();
    let is_class = dty.is_class();
    // A class handle is checked against the object's dynamic class at run
    // time (`ObjOp::IsA`); null always casts (LRM 8.16).
    let ok = if is_class {
        // LRM 8.16: a class `$cast` succeeds only when the source type is
        // assignment compatible with the destination (same class or a
        // superclass/implemented interface), cast compatible (the source is
        // a superclass of the destination, or an interface class: both need
        // the run-time check), or the source is the literal `null`. Any other
        // pair of static types fails "even if the source expression
        // evaluates to null", so it is decided here, before the null
        // shortcut below. An interface-class DESTINATION is always left to
        // the run-time check: 8.26.5 makes a cast from any object handle to
        // an interface class legal when the actual object implements it (an
        // unrelated static class may have an implementing subclass).
        let related = match src.expr_type() {
            Some(sty) if sty.is_null() => true,
            Some(sty) if sty.is_class() => {
                dty.is_assignment_compatible(&sty)
                    || dty.is_derived_from(&sty)
                    || sty.class_is_interface()
                    || dty.class_is_interface()
            }
            // slang rejects a non-class source for a class destination.
            Some(_) | None => {
                return Err(LoweringError::unsupported_at(
                    "$cast to a class from a non-class source",
                    &cx.fn_sym,
                ));
            }
        };
        if !related {
            bool_ty.const_zero()
        } else {
            let h = op.lane_val(v);
            let is_null =
                cx.b.build_int_compare(IntPredicate::EQ, h, h.get_type().const_zero(), "cast_null")
                    .unwrap();
            let is_a = crate::classes::is_a_call(cx, h, dty);
            cx.b.build_or(is_null, is_a, "cast_legal").unwrap()
        }
    } else if dty.is_enum() {
        let mut any = bool_ty.const_zero();
        for m in dty.enum_members() {
            let cv = m.constant_value();
            let iv = cv.as_ref().and_then(|c| c.as_integer()).ok_or_else(|| {
                LoweringError::unsupported_at("an enum member with no constant value", &cx.fn_sym)
            })?;
            let mv = crate::expr::lower_constant(cx, iv, None)?
                .into_packed("a wide enum member", &cx.fn_sym)?;
            let mv = crate::select::fit_width(&op, mv, width);
            let eq = crate::ops::is_definitely_true(cx.ctx, &cx.b, op.caseeq4(v, mv));
            any = cx.b.build_or(any, eq, "cast_member").unwrap();
        }
        any
    } else {
        bool_ty.const_all_ones()
    };
    let f =
        cx.b.get_insert_block()
            .and_then(|bb| bb.get_parent())
            .expect("lowering happens inside a function");
    let then_bb = cx.ctx.append_basic_block(f, "cast_ok");
    let fail_bb = cx.ctx.append_basic_block(f, "cast_fail");
    let done_bb = cx.ctx.append_basic_block(f, "cast_done");
    cx.b.build_conditional_branch(ok, then_bb, fail_bb).unwrap();
    cx.b.position_at_end(then_bb);
    let stored = if dty.is_floating() {
        LoweredValue::Real(crate::real::bits_to_real(cx, v))
    } else {
        LoweredValue::Packed(v)
    };
    // A source that builds a new handle (`new`, a function result) hands the
    // destination its one reference; any other source still holds its own, so
    // the destination retains one (LRM 8.4) BEFORE releasing the old value --
    // they may name one object.
    let fresh_src = is_class && crate::collections::fresh(&src);
    if is_class {
        if !fresh_src {
            crate::classes::retain_handle(cx, op.lane_val(v));
        }
        if sv_sim_sim::symid::is_value_name(dest.kind()) {
            crate::collections::release_old(cx, dest)?;
            crate::expr::store_to(cx, dest, stored)?;
        } else {
            crate::collections::store_releasing(cx, dest, stored)?;
        }
    } else {
        crate::expr::store_to(cx, dest, stored)?;
    }
    cx.b.build_unconditional_branch(done_bb).unwrap();
    cx.b.position_at_end(fail_bb);
    // The destination is left alone; a new handle nobody took is dropped.
    if fresh_src {
        crate::classes::release_handle(cx, op.lane_val(v));
    }
    if task_form {
        let what = if is_class {
            format!(
                "the source object is not an instance of class {}",
                dty.as_symbol().name()
            )
        } else {
            "the source value is not a legal value of the destination type".to_string()
        };
        crate::stmt_shared::fatal_if(
            cx,
            bool_ty.const_all_ones(),
            e.source_range().start,
            &format!("$cast failed: {what}"),
        )?;
    }
    cx.b.build_unconditional_branch(done_bb).unwrap();
    cx.b.position_at_end(done_bb);
    let i32t = cx.ctx.i32_type();
    let r = cx.b.build_int_z_extend(ok, i32t, "cast_result").unwrap();
    Ok(LoweredValue::Packed(op.pack(
        r,
        i32t.const_zero(),
        32,
        cx.repr,
        true,
    )))
}

/// An enum method call (`e.first()`, `e.last()`, `e.next(n)`, `e.prev(n)`,
/// `e.num()`, `e.name()`; LRM 1800-2023 §6.19.5); `None` for anything else.
/// The members are known at compile time, so `next`/`prev` map the current
/// value to its member index (a value that is no member gives the enum's
/// default: X for a 4-state base, else 0), step with wraparound, and map
/// back; `name` yields the member's name, or `""`.
pub(crate) fn lower_enum_method<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    name: KnownSystemName,
    e: sv_lang::Expression<'d>,
) -> Option<Result<LoweredValue<'ctx>, LoweringError>> {
    use KnownSystemName as K;
    if !matches!(
        name,
        K::First | K::Last | K::Next | K::Prev | K::Num | K::Name
    ) {
        return None;
    }
    let args = e.operands();
    let this = *args.first()?;
    let ty = this.expr_type()?;
    if !ty.is_enum() {
        return None;
    }
    Some(lower_enum(cx, name, e, this, ty, &args[1..]))
}

/// An enum value `cur` of type `ty` (at most 64 bits) as the text `%p`
/// prints it (LRM 1800-2023 21.2.1.7): the member's name when the value is a
/// member, else the value printed as its base type. `None` when `ty` is no
/// such enum (the caller prints it as any integral value).
pub(crate) fn enum_pattern_text<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    ty: &sv_lang::Type<'_>,
    cur: PackedValue<'ctx>,
) -> Result<Option<LoweredValue<'ctx>>, LoweringError> {
    if !ty.is_enum() || ty.value_width() > 64 {
        return Ok(None);
    }
    let fmt = crate::process_lower::build_c_string_global(cx.ctx, cx.module, "%p", "enum_p_fmt");
    let mut text = crate::strings::sformat_with(cx, fmt, vec![LoweredValue::Packed(cur)])?.llvm;
    for m in ty.enum_members() {
        let cv = m.constant_value();
        let iv = cv.as_ref().and_then(|c| c.as_integer()).ok_or_else(|| {
            LoweringError::unsupported_at("an enum member with no constant value", &cx.fn_sym)
        })?;
        let v =
            crate::expr::lower_constant(cx, iv, None)?.into_packed("a wide enum", &cx.fn_sym)?;
        let hit =
            cx.b.build_int_compare(IntPredicate::EQ, cur.llvm, v.llvm, "enum_p_hit")
                .unwrap();
        let lit = crate::strings::literal(cx, m.name().as_bytes()).llvm;
        text =
            cx.b.build_select(hit, lit, text, "enum_p_name")
                .unwrap()
                .into_int_value();
    }
    Ok(Some(LoweredValue::Str(crate::strings::StrValue {
        llvm: text,
    })))
}

fn lower_enum<'ctx, 'd>(
    cx: &LowerCtx<'ctx, 'd, '_>,
    name: KnownSystemName,
    e: sv_lang::Expression<'d>,
    this: sv_lang::Expression<'d>,
    ty: sv_lang::Type<'d>,
    rest: &[sv_lang::Expression<'d>],
) -> Result<LoweredValue<'ctx>, LoweringError> {
    use KnownSystemName as K;
    let op = OpBuilder {
        ctx: cx.ctx,
        b: &cx.b,
    };
    if name != K::Name
        && let Some(iv) = e.constant_value().as_ref().and_then(|c| c.as_integer())
    {
        return crate::expr::lower_constant(cx, iv, Some(e));
    }
    let members: Vec<(String, PackedValue<'ctx>)> = ty
        .enum_members()
        .map(|m| {
            let cv = m.constant_value();
            let iv = cv.as_ref().and_then(|c| c.as_integer()).ok_or_else(|| {
                LoweringError::unsupported_at("an enum member with no constant value", &cx.fn_sym)
            })?;
            let v = crate::expr::lower_constant(cx, iv, None)?;
            Ok((
                m.name().to_string(),
                v.into_packed("a wide enum", &cx.fn_sym)?,
            ))
        })
        .collect::<Result<_, _>>()?;
    let width = ty.value_width();
    let signed = ty.is_signed();
    let cur = lower_expr(cx, this)?.into_packed("an enum value", &cx.fn_sym)?;
    let i64t = cx.ctx.i64_type();
    // The current value's member index, or -1.
    let mut idx = i64t.const_all_ones();
    for (i, (_, v)) in members.iter().enumerate().rev() {
        let hit =
            cx.b.build_int_compare(IntPredicate::EQ, cur.llvm, v.llvm, "enum_hit")
                .unwrap();
        idx =
            cx.b.build_select(hit, i64t.const_int(i as u64, false), idx, "enum_idx")
                .unwrap()
                .into_int_value();
    }
    let is_member =
        cx.b.build_int_compare(IntPredicate::SGE, idx, i64t.const_zero(), "enum_member")
            .unwrap();
    match name {
        K::Name => {
            let mut id = crate::strings::literal(cx, b"").llvm;
            for (i, (n, _)) in members.iter().enumerate() {
                let hit =
                    cx.b.build_int_compare(
                        IntPredicate::EQ,
                        idx,
                        i64t.const_int(i as u64, false),
                        "enum_name_hit",
                    )
                    .unwrap();
                let lit = crate::strings::literal(cx, n.as_bytes()).llvm;
                id =
                    cx.b.build_select(hit, lit, id, "enum_name")
                        .unwrap()
                        .into_int_value();
            }
            Ok(LoweredValue::Str(crate::strings::StrValue { llvm: id }))
        }
        K::Next | K::Prev => {
            let n = members.len() as u64;
            let step = match rest.first() {
                Some(s) => {
                    let sv = lower_expr(cx, *s)?.into_packed("an enum step", &cx.fn_sym)?;
                    crate::expr::mem_row_index_i64(&op, cx, sv)
                }
                None => i64t.const_int(1, false),
            };
            let step =
                cx.b.build_int_signed_rem(step, i64t.const_int(n, false), "enum_step")
                    .unwrap();
            let moved = if name == K::Next {
                cx.b.build_int_add(idx, step, "enum_fwd").unwrap()
            } else {
                cx.b.build_int_sub(idx, step, "enum_back").unwrap()
            };
            // ((moved % n) + n) % n
            let nn = i64t.const_int(n, false);
            let r = cx.b.build_int_signed_rem(moved, nn, "enum_r").unwrap();
            let r = cx.b.build_int_add(r, nn, "enum_r_pos").unwrap();
            let r = cx.b.build_int_signed_rem(r, nn, "enum_r_mod").unwrap();
            let mut out = crate::arrays::default_value(cx, &ty);
            for (i, (_, v)) in members.iter().enumerate() {
                let hit =
                    cx.b.build_int_compare(
                        IntPredicate::EQ,
                        r,
                        i64t.const_int(i as u64, false),
                        "enum_pick",
                    )
                    .unwrap();
                let pick =
                    cx.b.build_select(hit, v.llvm, out, "enum_val")
                        .unwrap()
                        .into_int_value();
                out =
                    cx.b.build_select(is_member, pick, out, "enum_next")
                        .unwrap()
                        .into_int_value();
            }
            Ok(LoweredValue::Packed(PackedValue {
                llvm: out,
                width,
                repr: cx.repr,
                signed,
            }))
        }
        // first/last/num always fold (they depend on the type alone).
        _ => Err(LoweringError::unsupported_at(
            "an enum first()/last()/num() that did not fold to a constant",
            &cx.fn_sym,
        )),
    }
}

/// `v` zero-extended or truncated to `width` bits.
pub(crate) fn fit<'ctx>(
    cx: &LowerCtx<'ctx, '_, '_>,
    v: IntValue<'ctx>,
    width: u32,
) -> IntValue<'ctx> {
    let ty = crate::types::int_type(cx.ctx, width);
    let have = v.get_type().get_bit_width();
    if have < width {
        cx.b.build_int_z_extend(v, ty, "sysf_zext").unwrap()
    } else if have > width {
        cx.b.build_int_truncate(v, ty, "sysf_trunc").unwrap()
    } else {
        v
    }
}