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
// Copyright (c) 2016-2021 Fabian Schuiki

//! Rvalue expressions
//!
//! An MIR representation for all expressions that may appear on the right-hand
//! side of an assignment.

use crate::crate_prelude::*;
use crate::{
    mir::{
        lvalue::Lvalue,
        print::{Context, Print},
        visit::{AcceptVisitor, Visitor, WalkVisitor},
    },
    ty::{Domain, Sign, UnpackedType},
    ParamEnv,
};
use std::collections::HashMap;
use std::fmt::Write;

/// An rvalue expression.
#[moore_derive::visit_without_foreach]
#[derive(Clone, Eq, PartialEq)]
pub struct Rvalue<'a> {
    /// A unique id.
    pub id: NodeId,
    /// The expression node which spawned this rvalue.
    pub origin: NodeId,
    /// The environment within which the rvalue lives.
    pub env: ParamEnv,
    /// The span in the source file where the rvalue originates from.
    pub span: Span,
    /// The type of the expression.
    pub ty: &'a UnpackedType<'a>,
    /// The expression data.
    pub kind: RvalueKind<'a>,
    /// Whether this expression has a constant value.
    pub konst: bool,
}

impl<'a> Rvalue<'a> {
    /// Check whether the rvalue represents a lowering error tombstone.
    pub fn is_error(&self) -> bool {
        self.ty.is_error() || self.kind.is_error()
    }

    /// Check whether the rvalue is a constant.
    pub fn is_const(&self) -> bool {
        self.konst
    }

    /// Get the `Intf` nested within `Index`, if one exists.
    pub fn get_intf(&self) -> Option<NodeId> {
        match self.kind {
            mir::RvalueKind::Index { value, .. } => value.get_intf(),
            mir::RvalueKind::Intf(intf) => Some(intf),
            _ => None,
        }
    }
}

impl<'a> std::ops::Deref for Rvalue<'a> {
    type Target = RvalueKind<'a>;

    fn deref(&self) -> &RvalueKind<'a> {
        &self.kind
    }
}

impl<'a> std::fmt::Debug for Rvalue<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.print(f)
    }
}

impl<'a> Print for Rvalue<'a> {
    fn print_context(
        &self,
        outer: &mut impl Write,
        inner: &mut impl Write,
        ctx: &mut Context,
    ) -> std::fmt::Result {
        write!(inner, "Rvalue ")?;
        match self.kind {
            RvalueKind::CastValueDomain { value, .. } => {
                write!(inner, "CastValueDomain({})", ctx.print(outer, value))?
            }
            RvalueKind::Transmute(v) => write!(inner, "Transmute({})", ctx.print(outer, v))?,
            RvalueKind::CastSign(sign, arg) => {
                write!(inner, "CastSign({}, {})", sign, ctx.print(outer, arg))?
            }
            RvalueKind::CastToBool(arg) => write!(inner, "CastToBool({})", ctx.print(outer, arg))?,
            RvalueKind::Truncate(size, arg) => {
                write!(inner, "Truncate({}, {})", size, ctx.print(outer, arg))?
            }
            RvalueKind::ZeroExtend(size, arg) => {
                write!(inner, "ZeroExtend({}, {})", size, ctx.print(outer, arg))?
            }
            RvalueKind::SignExtend(size, arg) => {
                write!(inner, "SignExtend({}, {})", size, ctx.print(outer, arg))?
            }
            RvalueKind::ConstructArray(ref args) => write!(
                inner,
                "ConstructArray({})",
                ctx.print_comma_separated(outer, args.iter().map(|(_idx, v)| v)),
            )?,
            RvalueKind::ConstructStruct(ref args) => write!(
                inner,
                "ConstructStruct({})",
                ctx.print_comma_separated(outer, args),
            )?,
            RvalueKind::Const(arg) => write!(inner, "{}", arg)?,
            RvalueKind::UnaryBitwise { op, arg } => {
                write!(inner, "UnaryBitwise {:?} {}", op, ctx.print(outer, arg))?
            }
            RvalueKind::BinaryBitwise { op, lhs, rhs } => write!(
                inner,
                "BinaryBitwise {} {:?} {}",
                ctx.print(outer, lhs),
                op,
                ctx.print(outer, rhs)
            )?,
            RvalueKind::IntUnaryArith {
                op,
                sign,
                domain,
                arg,
            } => write!(
                inner,
                "IntUnaryArith {:?} {} ({:?}, {:?})",
                op,
                ctx.print(outer, arg),
                sign,
                domain
            )?,
            RvalueKind::IntBinaryArith {
                op,
                sign,
                domain,
                lhs,
                rhs,
            } => write!(
                inner,
                "IntBinaryArith {} {:?} {} ({:?}, {:?})",
                ctx.print(outer, lhs),
                op,
                ctx.print(outer, rhs),
                sign,
                domain
            )?,
            RvalueKind::IntComp {
                op,
                sign,
                domain,
                lhs,
                rhs,
            } => write!(
                inner,
                "IntComp {} {:?} {} ({:?}, {:?})",
                ctx.print(outer, lhs),
                op,
                ctx.print(outer, rhs),
                sign,
                domain
            )?,
            RvalueKind::Concat(ref args) => {
                write!(inner, "Concat({})", ctx.print_comma_separated(outer, args))?
            }
            RvalueKind::Repeat(num, arg) => {
                write!(inner, "Repeat({} x {})", num, ctx.print(outer, arg))?
            }
            RvalueKind::Var(arg) => write!(inner, "Var({:?})", arg)?,
            RvalueKind::Port(arg) => write!(inner, "Port({:?})", arg)?,
            RvalueKind::Intf(arg) => write!(inner, "Intf({:?})", arg)?,
            RvalueKind::IntfSignal(arg, sig) => {
                write!(inner, "IntfSignal({}, {:?})", ctx.print(outer, arg), sig)?
            }
            RvalueKind::Index {
                value,
                base,
                length,
            } => {
                if length == 0 {
                    write!(
                        inner,
                        "{}[{}]",
                        ctx.print(outer, value),
                        ctx.print(outer, base)
                    )?
                } else {
                    write!(
                        inner,
                        "{}[{}+:{}]",
                        ctx.print(outer, value),
                        ctx.print(outer, base),
                        length,
                    )?
                }
            }
            RvalueKind::Member { value, field } => {
                write!(inner, "{}.{}", ctx.print(outer, value), field)?
            }
            RvalueKind::Ternary {
                cond,
                true_value,
                false_value,
            } => write!(
                inner,
                "{} ? {} : {}",
                ctx.print(outer, cond),
                ctx.print(outer, true_value),
                ctx.print(outer, false_value)
            )?,
            RvalueKind::Shift {
                op,
                arith,
                value,
                amount,
            } => write!(
                inner,
                "Shift {:?} {} {} by {}",
                op,
                if arith { "arith" } else { "logic" },
                ctx.print(outer, value),
                ctx.print(outer, amount)
            )?,
            RvalueKind::Reduction { op, arg } => {
                write!(inner, "Reduce({:?}, {})", op, ctx.print(outer, arg))?
            }
            RvalueKind::Assignment {
                lvalue,
                rvalue,
                result,
            } => write!(
                inner,
                "{}, {{ {} = {} }}",
                ctx.print(outer, result),
                ctx.print(outer, lvalue),
                ctx.print(outer, rvalue)
            )?,
            RvalueKind::PackString(arg) => write!(inner, "PackString({})", ctx.print(outer, arg))?,
            RvalueKind::UnpackString(arg) => {
                write!(inner, "UnpackString({})", ctx.print(outer, arg))?
            }
            RvalueKind::StringComp { op, lhs, rhs } => write!(
                inner,
                "StringComp {} {:?} {}",
                ctx.print(outer, lhs),
                op,
                ctx.print(outer, rhs)
            )?,
            RvalueKind::Error => write!(inner, "<error>")?,
        }
        write!(inner, " : {}", self.ty)?;
        Ok(())
    }
}

/// The different forms an rvalue expression may take.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum RvalueKind<'a> {
    /// A cast from a four-valued type to a two-valued type, or vice versa.
    /// E.g. `integer` to `int`, or `int` to `integer`.
    CastValueDomain {
        from: ty::Domain,
        to: ty::Domain,
        value: &'a Rvalue<'a>,
    },
    /// A type cast which does not incur any operation. For example, going from
    /// `bit [31:0]` to `int`, or vice versa.
    Transmute(&'a Rvalue<'a>),
    /// A cast from one sign to another. E.g. `logic signed` to
    /// `logic unsigned`.
    // TODO: Add SBVT
    CastSign(ty::Sign, &'a Rvalue<'a>),
    /// A cast from a simple bit type to a boolean.
    // TODO: Add SBVT
    CastToBool(&'a Rvalue<'a>),
    /// Shrink the width of a vector type. E.g. `bit [31:0]` to `bit [7:0]`.
    // TODO: Add SBVT
    Truncate(usize, &'a Rvalue<'a>),
    /// Increase the width of a vector by zero extension. E.g. `bit [7:0]` to
    /// `bit [31:0]`.
    // TODO: Add SBVT
    ZeroExtend(usize, &'a Rvalue<'a>),
    /// Increase the width of a vector by sign extension. E.g. `bit signed
    /// [7:0]` to `bit signed [31:0]`.
    // TODO: Add SBVT
    SignExtend(usize, &'a Rvalue<'a>),
    /// Constructor for an array.
    ConstructArray(HashMap<usize, &'a Rvalue<'a>>),
    /// Constructor for a struct.
    ConstructStruct(Vec<&'a Rvalue<'a>>),
    /// A constant value.
    Const(value::Value<'a>),
    /// A unary bitwise operator.
    UnaryBitwise {
        op: UnaryBitwiseOp,
        // TODO: Add SBVT
        arg: &'a Rvalue<'a>,
    },
    /// A binary bitwise operator.
    BinaryBitwise {
        op: BinaryBitwiseOp,
        // TODO: Add SBVT
        lhs: &'a Rvalue<'a>,
        rhs: &'a Rvalue<'a>,
    },
    /// An integral unary arithmetic operator.
    ///
    /// If any bit of the operand is x/z, the entire result is x.
    IntUnaryArith {
        op: IntUnaryArithOp,
        // TODO: Add SBVT
        sign: Sign,
        domain: Domain,
        arg: &'a Rvalue<'a>,
    },
    /// An integral binary arithmetic operator.
    ///
    /// If any bit of the operands are x/z, the entire result is x.
    IntBinaryArith {
        op: IntBinaryArithOp,
        // TODO: Add SBVT
        sign: Sign,
        domain: Domain,
        lhs: &'a Rvalue<'a>,
        rhs: &'a Rvalue<'a>,
    },
    /// An integral comparison operator.
    ///
    /// If any bit of the operands are x/z, the entire result is x.
    IntComp {
        op: IntCompOp,
        // TODO: Add SBVT
        sign: Sign,
        domain: Domain,
        lhs: &'a Rvalue<'a>,
        rhs: &'a Rvalue<'a>,
    },
    /// Concatenate multiple values.
    ///
    /// The values are cast to and treated as packed bit vectors, and the result
    /// is yet another packed bit vector. The lowest index corresponds to the
    /// left-most item in the concatenation, which is at the MSB end of the
    /// final packed bit vector.
    Concat(Vec<&'a Rvalue<'a>>),
    /// Repeat a value multiple times.
    ///
    /// The value is cast to and treated as a packed bit vector, and the result
    /// is yet another packed bit vector.
    // TODO: Add SBVT
    Repeat(usize, &'a Rvalue<'a>),
    /// A reference to a variable declaration.
    Var(NodeId),
    /// A reference to a port declaration.
    Port(NodeId),
    /// A reference to an interface.
    Intf(NodeId),
    /// A reference to a locally instantiated interface signal.
    IntfSignal(&'a Rvalue<'a>, NodeId),
    /// A bit- or part-select.
    Index {
        value: &'a Rvalue<'a>,
        base: &'a Rvalue<'a>,
        /// Length of the selection. Bit-select if zero.
        length: usize,
    },
    /// A struct field access.
    Member { value: &'a Rvalue<'a>, field: usize },
    /// The ternary operator.
    Ternary {
        cond: &'a Rvalue<'a>,
        true_value: &'a Rvalue<'a>,
        false_value: &'a Rvalue<'a>,
    },
    /// A shift operation.
    Shift {
        op: ShiftOp,
        arith: bool,
        value: &'a Rvalue<'a>,
        amount: &'a Rvalue<'a>,
    },
    /// A reduction operator.
    Reduction {
        op: BinaryBitwiseOp,
        // TODO: Add SBVT
        arg: &'a Rvalue<'a>,
    },
    /// An assignment operator.
    Assignment {
        lvalue: &'a Lvalue<'a>,
        rvalue: &'a Rvalue<'a>,
        /// What value is produced as the assignment's value. This is usually
        /// the rvalue, but may be different (e.g. for the `i++` or `i--`).
        result: &'a Rvalue<'a>,
    },
    /// Pack a string value into a fixed-size packed bit vector.
    PackString(&'a Rvalue<'a>),
    /// Unpack a string value from a fixed-size packed bit vector.
    UnpackString(&'a Rvalue<'a>),
    /// A string comparison operator.
    StringComp {
        op: StringCompOp,
        lhs: &'a Rvalue<'a>,
        rhs: &'a Rvalue<'a>,
    },
    /// An error occurred during lowering.
    Error,
}

impl<'a> RvalueKind<'a> {
    /// Check whether the rvalue represents a lowering error tombstone.
    pub fn is_error(&self) -> bool {
        match self {
            RvalueKind::Error => true,
            _ => false,
        }
    }

    /// Check whether this rvalue is a constant.
    pub fn is_const(&self) -> bool {
        match self {
            RvalueKind::CastValueDomain { value, .. }
            | RvalueKind::Transmute(value)
            | RvalueKind::CastSign(_, value)
            | RvalueKind::CastToBool(value)
            | RvalueKind::Truncate(_, value)
            | RvalueKind::ZeroExtend(_, value)
            | RvalueKind::SignExtend(_, value)
            | RvalueKind::Repeat(_, value)
            | RvalueKind::Member { value, .. }
            | RvalueKind::PackString(value)
            | RvalueKind::UnpackString(value) => value.is_const(),
            RvalueKind::ConstructArray(values) => values.values().all(|v| v.is_const()),
            RvalueKind::ConstructStruct(values) => values.iter().all(|v| v.is_const()),
            RvalueKind::Const(_) => true,
            RvalueKind::UnaryBitwise { arg, .. }
            | RvalueKind::IntUnaryArith { arg, .. }
            | RvalueKind::Reduction { arg, .. } => arg.is_const(),
            RvalueKind::BinaryBitwise { lhs, rhs, .. }
            | RvalueKind::IntBinaryArith { lhs, rhs, .. }
            | RvalueKind::IntComp { lhs, rhs, .. }
            | RvalueKind::StringComp { lhs, rhs, .. } => lhs.is_const() && rhs.is_const(),
            RvalueKind::Concat(values) => values.iter().all(|v| v.is_const()),
            RvalueKind::Var(_) => false,
            RvalueKind::Port(_) => false,
            RvalueKind::Intf(_) => false,
            RvalueKind::IntfSignal(..) => false,
            RvalueKind::Index { .. } => false, // TODO(fschuiki): reactivate once impl
            // RvalueKind::Index { value, base, .. } => value.is_const() && base.is_const(),
            RvalueKind::Ternary {
                cond,
                true_value,
                false_value,
            } => cond.is_const() && true_value.is_const() && false_value.is_const(),
            RvalueKind::Shift { value, amount, .. } => value.is_const() && amount.is_const(),
            RvalueKind::Assignment { .. } => false,
            RvalueKind::Error => true,
        }
    }
}

/// The unary bitwise operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum UnaryBitwiseOp {
    Not,
}

/// The binary bitwise operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum BinaryBitwiseOp {
    And,
    Or,
    Xor,
}

/// The integer unary arithmetic operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum IntUnaryArithOp {
    Neg,
}

/// The integer binary arithmetic operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum IntBinaryArithOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
}

/// The integer comparison operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum IntCompOp {
    Eq,
    Neq,
    Lt,
    Leq,
    Gt,
    Geq,
}

/// The string comparison operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum StringCompOp {
    Eq,
    Neq,
}

/// The shift operators.
#[moore_derive::visit_without_foreach]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum ShiftOp {
    Left,
    Right,
}