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
use arret_syntax::span::Span;

use arret_runtime::abitype;
use arret_runtime::boxed;
use arret_runtime::boxed::prelude::*;

use crate::codegen::GenAbi;
use crate::mir::builder::{Builder, BuiltReg, TryToBuilder};
use crate::mir::costing::{cost_for_op_category, cost_for_ops};
use crate::mir::eval_hir::EvalHirCtx;
use crate::mir::ops::*;
use crate::mir::tagset::TypeTagSet;
use crate::mir::value;
use crate::mir::value::build_reg::value_to_reg;
use crate::mir::value::to_const::value_to_const;
use crate::mir::value::Value;
use crate::ty::record;

pub enum EqualityResult {
    Static(bool),
    Dynamic(Value),
}

impl EqualityResult {
    fn from_bool_reg(reg: BuiltReg) -> EqualityResult {
        EqualityResult::Dynamic(value::RegValue::new(reg, abitype::AbiType::Bool).into())
    }
}

impl From<EqualityResult> for Value {
    fn from(er: EqualityResult) -> Value {
        match er {
            EqualityResult::Static(true) => boxed::TRUE_INSTANCE.as_any_ref().into(),
            EqualityResult::Static(false) => boxed::FALSE_INSTANCE.as_any_ref().into(),
            EqualityResult::Dynamic(value) => value,
        }
    }
}

fn runtime_compare(
    ehx: &mut EvalHirCtx,
    b: &mut Builder,
    span: Span,
    left_value: &Value,
    right_value: &Value,
) -> BuiltReg {
    let left_reg = value_to_reg(ehx, b, span, left_value, &abitype::BoxedAbiType::Any.into());

    let right_reg = value_to_reg(
        ehx,
        b,
        span,
        right_value,
        &abitype::BoxedAbiType::Any.into(),
    );

    let abi = GenAbi {
        takes_task: true,
        params: Box::new([
            abitype::BoxedAbiType::Any.into(),
            abitype::BoxedAbiType::Any.into(),
        ]),
        ret: abitype::AbiType::Bool.into(),
    };

    let callee = Callee::StaticSymbol(StaticSymbol {
        symbol: "arret_runtime_equals",
        impure: false,
        abi,
    });

    b.push_reg(
        span,
        OpKind::Call,
        CallOp {
            callee,
            impure: false,
            args: Box::new([left_reg.into(), right_reg.into()]),
        },
    )
}

fn build_native_compare<F>(
    ehx: &mut EvalHirCtx,
    b: &mut Builder,
    span: Span,
    left_value: &Value,
    right_value: &Value,
    abi_type: &abitype::AbiType,
    op_kind: F,
) -> BuiltReg
where
    F: FnOnce(RegId, BinaryOp) -> OpKind,
{
    let left_reg = value_to_reg(ehx, b, span, left_value, abi_type);
    let right_reg = value_to_reg(ehx, b, span, right_value, abi_type);

    b.push_reg(
        span,
        op_kind,
        BinaryOp {
            lhs_reg: left_reg.into(),
            rhs_reg: right_reg.into(),
        },
    )
}

fn build_record_equality(
    ehx: &mut EvalHirCtx,
    parent_b: &mut Builder,
    span: Span,
    record_cons: &record::ConsId,
    left_value: &Value,
    right_value: &Value,
) -> EqualityResult {
    use crate::mir::record_field::load_record_field;

    // Try a fieldwise comparison
    let field_count = record_cons.fields().len();
    let mut fieldwise_b = Builder::new();
    let mut fieldwise_regs = Vec::<BuiltReg>::with_capacity(field_count);

    for field_index in 0..field_count {
        let left_field = load_record_field(
            ehx,
            &mut fieldwise_b,
            span,
            record_cons,
            left_value,
            field_index,
        );

        let right_field = load_record_field(
            ehx,
            &mut fieldwise_b,
            span,
            record_cons,
            right_value,
            field_index,
        );

        match eval_equality(ehx, &mut fieldwise_b, span, &left_field, &right_field) {
            EqualityResult::Static(false) => {
                // The whole comparison is false; we don't need to build anything
                return EqualityResult::Static(false);
            }
            EqualityResult::Static(true) => {
                // We can ignore this comparison
            }
            EqualityResult::Dynamic(value) => {
                let fieldwise_reg =
                    value_to_reg(ehx, &mut fieldwise_b, span, &value, &abitype::AbiType::Bool);
                fieldwise_regs.push(fieldwise_reg);
            }
        }
    }

    let mut fieldwise_reg_iter = fieldwise_regs.into_iter();
    let first_fieldwise_reg = if let Some(fieldwise_reg) = fieldwise_reg_iter.next() {
        fieldwise_reg
    } else {
        // This is statically true
        return EqualityResult::Static(true);
    };

    let combined_fieldwise_reg =
        fieldwise_reg_iter.fold(first_fieldwise_reg, |acc_reg, fieldwise_reg| {
            let phi_result_reg = fieldwise_b.alloc_local();
            fieldwise_b.push(
                span,
                OpKind::Cond(CondOp {
                    reg_phi: Some(RegPhi {
                        output_reg: phi_result_reg.into(),
                        true_result_reg: acc_reg.into(),
                        false_result_reg: fieldwise_reg.into(),
                    }),
                    test_reg: fieldwise_reg.into(),
                    true_ops: Box::new([]),
                    false_ops: Box::new([]),
                }),
            );

            phi_result_reg
        });

    // Try a runtime compare
    let mut runtime_b = Builder::new();
    let runtime_reg = runtime_compare(ehx, &mut runtime_b, span, left_value, right_value);

    // Build ops for both options and cost them
    let fieldwise_ops = fieldwise_b.into_ops();
    let fieldwise_cost = cost_for_ops(fieldwise_ops.iter());

    let runtime_ops = runtime_b.into_ops();
    // Favour fieldwise comparisons. Runtime comparisons of records are more expensive than other
    // types but this wouldn't be captured by `cost_for_ops`. Account for at least the cost of
    // loading the class map.
    let runtime_cost = cost_for_ops(runtime_ops.iter()) + cost_for_op_category(OpCategory::MemLoad);

    if runtime_cost < fieldwise_cost {
        parent_b.append(runtime_ops.into_vec().into_iter());
        EqualityResult::from_bool_reg(runtime_reg)
    } else {
        parent_b.append(fieldwise_ops.into_vec().into_iter());
        EqualityResult::from_bool_reg(combined_fieldwise_reg)
    }
}

/// Builds a comparison between two values known to be boolean
fn build_bool_equality(
    ehx: &mut EvalHirCtx,
    b: &mut Builder,
    span: Span,
    left_value: &Value,
    right_value: &Value,
) -> EqualityResult {
    enum ValueClass {
        ConstTrue,
        Boxed,
        Other,
    }

    fn classify_value(value: &Value) -> ValueClass {
        match value {
            Value::Const(any_ref) if any_ref.header().type_tag() == boxed::TypeTag::True => {
                ValueClass::ConstTrue
            }
            Value::Reg(reg_value) => {
                if let abitype::AbiType::Boxed(_) = &reg_value.abi_type {
                    ValueClass::Boxed
                } else {
                    ValueClass::Other
                }
            }
            _ => ValueClass::Other,
        }
    }

    let left_class = classify_value(left_value);
    let right_class = classify_value(right_value);

    let result_reg = match (left_class, right_class) {
        // Comparing a boolean to constant true can be simplified to a no-op
        (ValueClass::ConstTrue, _) => {
            return EqualityResult::Dynamic(right_value.clone());
        }
        (_, ValueClass::ConstTrue) => {
            return EqualityResult::Dynamic(left_value.clone());
        }
        (ValueClass::Boxed, ValueClass::Boxed) => {
            // If both values are boxed we can just compare the pointers
            build_native_compare(
                ehx,
                b,
                span,
                left_value,
                right_value,
                &abitype::BoxedAbiType::Any.into(),
                OpKind::BoxIdentical,
            )
        }
        _ => {
            // Fall back to a native comparison of the unboxed values
            build_native_compare(
                ehx,
                b,
                span,
                left_value,
                right_value,
                &abitype::AbiType::Bool,
                OpKind::BoolEqual,
            )
        }
    };

    EqualityResult::from_bool_reg(result_reg)
}

/// Determines if two values are statically equal
pub fn values_statically_equal(
    ehx: &mut EvalHirCtx,
    left_value: &Value,
    right_value: &Value,
) -> Option<bool> {
    match (left_value, right_value) {
        (Value::Reg(left_reg), Value::Reg(right_reg)) => {
            if [left_reg, right_reg]
                .iter()
                .any(|reg| reg.possible_type_tags == boxed::TypeTag::FunThunk.into())
            {
                // Functions are equal to nothing, including themselves
                return Some(false);
            }

            if left_reg.reg.into_reg_id() != right_reg.reg.into_reg_id() {
                // We can't determine if these are statically equal
                return None;
            }

            for partial_equal_type_tag in TypeTagSet::all().into_iter().filter(|type_tag| {
                match type_tag {
                    // Functions never compare equal
                    boxed::TypeTag::FunThunk => true,
                    // NaN != NaN
                    boxed::TypeTag::Float => true,
                    // Can contain partial equal values
                    boxed::TypeTag::Pair
                    | boxed::TypeTag::Record
                    | boxed::TypeTag::Set
                    | boxed::TypeTag::Map
                    | boxed::TypeTag::Vector => true,
                    // The rest can be compared. Add them explicitly so we will be forced to
                    // classify new types
                    boxed::TypeTag::Int
                    | boxed::TypeTag::Char
                    | boxed::TypeTag::Str
                    | boxed::TypeTag::Sym
                    | boxed::TypeTag::True
                    | boxed::TypeTag::False
                    | boxed::TypeTag::Nil => false,
                }
            }) {
                if [left_reg, right_reg]
                    .iter()
                    .all(|reg| reg.possible_type_tags.contains(partial_equal_type_tag))
                {
                    return None;
                }
            }

            Some(true)
        }
        // Functions never compare equal
        (Value::ArretFun(_) | Value::RustFun(_) | Value::TyPred(_) | Value::EqPred, _)
        | (_, Value::ArretFun(_) | Value::RustFun(_) | Value::TyPred(_) | Value::EqPred) => {
            Some(false)
        }
        _ => {
            if let Some(const_left) = value_to_const(ehx, left_value) {
                if let Some(const_right) = value_to_const(ehx, right_value) {
                    return Some(const_left.eq_in_heap(ehx.as_heap(), &const_right));
                }
            }

            None
        }
    }
}

/// Evaluates if two values are equal
///
/// This attempts `values_statically_equal` before building a runtime comparison.
pub fn eval_equality(
    ehx: &mut EvalHirCtx,
    b: &mut impl TryToBuilder,
    span: Span,
    left_value: &Value,
    right_value: &Value,
) -> EqualityResult {
    use crate::mir::value::types::{known_record_cons_for_value, possible_type_tags_for_value};

    if let Some(static_result) = values_statically_equal(ehx, left_value, right_value) {
        return EqualityResult::Static(static_result);
    }

    let b = if let Some(some_b) = b.try_to_builder() {
        some_b
    } else {
        panic!("runtime equality without builder")
    };

    let left_type_tags = possible_type_tags_for_value(left_value);
    let right_type_tags = possible_type_tags_for_value(right_value);
    let all_type_tags = left_type_tags | right_type_tags;
    let common_type_tags = left_type_tags & right_type_tags;

    if common_type_tags.is_empty() {
        // No types in common
        return EqualityResult::Static(false);
    }

    if [left_type_tags, right_type_tags].contains(&boxed::TypeTag::FunThunk.into()) {
        // Functions always compare false
        return EqualityResult::Static(false);
    }

    if all_type_tags == abitype::AbiType::Bool.into() {
        // Build a specialised comparison for `Bool`
        return build_bool_equality(ehx, b, span, left_value, right_value);
    }

    let boxed_singleton_type_tags: TypeTagSet = [
        boxed::TypeTag::True,
        boxed::TypeTag::False,
        boxed::TypeTag::Nil,
    ]
    .iter()
    .collect();

    let result_reg = if common_type_tags.is_subset(boxed_singleton_type_tags) {
        // We an do a direct pointer comparison
        build_native_compare(
            ehx,
            b,
            span,
            left_value,
            right_value,
            &abitype::BoxedAbiType::Any.into(),
            OpKind::BoxIdentical,
        )
    } else if all_type_tags == boxed::TypeTag::Int.into() {
        build_native_compare(
            ehx,
            b,
            span,
            left_value,
            right_value,
            &abitype::AbiType::Int,
            |reg_id, BinaryOp { lhs_reg, rhs_reg }| {
                OpKind::IntCompare(
                    reg_id,
                    CompareOp {
                        comparison: Comparison::Eq,
                        lhs_reg,
                        rhs_reg,
                    },
                )
            },
        )
    } else if all_type_tags == boxed::TypeTag::Char.into() {
        build_native_compare(
            ehx,
            b,
            span,
            left_value,
            right_value,
            &abitype::AbiType::Char,
            OpKind::CharEqual,
        )
    } else if all_type_tags == boxed::TypeTag::Sym.into() {
        build_native_compare(
            ehx,
            b,
            span,
            left_value,
            right_value,
            &abitype::AbiType::InternedSym,
            OpKind::InternedSymEqual,
        )
    } else if all_type_tags == boxed::TypeTag::Float.into() {
        build_native_compare(
            ehx,
            b,
            span,
            left_value,
            right_value,
            &abitype::AbiType::Float,
            |reg_id, BinaryOp { lhs_reg, rhs_reg }| {
                OpKind::FloatCompare(
                    reg_id,
                    CompareOp {
                        comparison: Comparison::Eq,
                        lhs_reg,
                        rhs_reg,
                    },
                )
            },
        )
    } else if all_type_tags == boxed::TypeTag::Record.into() {
        let known_left_cons = known_record_cons_for_value(ehx, left_value);
        let known_right_cons = known_record_cons_for_value(ehx, right_value);

        match (known_left_cons, known_right_cons) {
            (Some(left_cons), Some(right_cons)) => {
                if left_cons == right_cons {
                    let common_cons = left_cons.clone();

                    return build_record_equality(
                        ehx,
                        b,
                        span,
                        &common_cons,
                        left_value,
                        right_value,
                    );
                } else {
                    return EqualityResult::Static(false);
                }
            }
            _ => runtime_compare(ehx, b, span, left_value, right_value),
        }
    } else {
        runtime_compare(ehx, b, span, left_value, right_value)
    };

    EqualityResult::from_bool_reg(result_reg)
}