peepmatic 0.78.0

DSL and compiler for generating peephole optimizers
Documentation
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
//! Abstract syntax tree type definitions.
//!
//! This file makes fairly heavy use of macros, which are defined in the
//! `peepmatic_macro` crate that lives at `crates/macro`. Notably, the following
//! traits are all derived via `derive(Ast)`:
//!
//! * `Span` -- access the `wast::Span` where an AST node was parsed from. For
//!   `struct`s, there must be a `span: wast::Span` field, because the macro
//!   always generates an implementation that returns `self.span` for
//!   `struct`s. For `enum`s, every variant must have a single, unnamed field
//!   which implements the `Span` trait. The macro will generate code to return
//!   the span of whatever variant it is.
//!
//! * `ChildNodes` -- get each of the child AST nodes that a given node
//!   references. Some fields in an AST type aren't actually considered an AST
//!   node (like spans) and these are ignored via the `#[peepmatic(skip_child)]`
//!   attribute. Some fields contain multiple AST nodes (like vectors of
//!   operands) and these are flattened with `#[peepmatic(flatten)]`.
//!
//! * `From<&'a Self> for DynAstRef<'a>` -- convert a particular AST type into
//!   `DynAstRef`, which is an `enum` of all the different kinds of AST nodes.

use peepmatic_macro::Ast;
use peepmatic_runtime::{
    r#type::{BitWidth, Type},
    unquote::UnquoteOperator,
};
use std::cell::Cell;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use wast::Id;

/// A reference to any AST node.
#[derive(Debug, Clone, Copy)]
pub enum DynAstRef<'a, TOperator> {
    /// A reference to an `Optimizations`.
    Optimizations(&'a Optimizations<'a, TOperator>),

    /// A reference to an `Optimization`.
    Optimization(&'a Optimization<'a, TOperator>),

    /// A reference to an `Lhs`.
    Lhs(&'a Lhs<'a, TOperator>),

    /// A reference to an `Rhs`.
    Rhs(&'a Rhs<'a, TOperator>),

    /// A reference to a `Pattern`.
    Pattern(&'a Pattern<'a, TOperator>),

    /// A reference to a `Precondition`.
    Precondition(&'a Precondition<'a, TOperator>),

    /// A reference to a `ConstraintOperand`.
    ConstraintOperand(&'a ConstraintOperand<'a, TOperator>),

    /// A reference to a `ValueLiteral`.
    ValueLiteral(&'a ValueLiteral<'a, TOperator>),

    /// A reference to a `Constant`.
    Constant(&'a Constant<'a, TOperator>),

    /// A reference to a `PatternOperation`.
    PatternOperation(&'a Operation<'a, TOperator, Pattern<'a, TOperator>>),

    /// A reference to a `Variable`.
    Variable(&'a Variable<'a, TOperator>),

    /// A reference to an `Integer`.
    Integer(&'a Integer<'a, TOperator>),

    /// A reference to a `Boolean`.
    Boolean(&'a Boolean<'a, TOperator>),

    /// A reference to a `ConditionCode`.
    ConditionCode(&'a ConditionCode<'a, TOperator>),

    /// A reference to an `Unquote`.
    Unquote(&'a Unquote<'a, TOperator>),

    /// A reference to an `RhsOperation`.
    RhsOperation(&'a Operation<'a, TOperator, Rhs<'a, TOperator>>),
}

impl<'a, 'b, TOperator> ChildNodes<'a, 'b, TOperator> for DynAstRef<'a, TOperator> {
    fn child_nodes(&'b self, sink: &mut impl Extend<DynAstRef<'a, TOperator>>) {
        match self {
            Self::Optimizations(x) => x.child_nodes(sink),
            Self::Optimization(x) => x.child_nodes(sink),
            Self::Lhs(x) => x.child_nodes(sink),
            Self::Rhs(x) => x.child_nodes(sink),
            Self::Pattern(x) => x.child_nodes(sink),
            Self::Precondition(x) => x.child_nodes(sink),
            Self::ConstraintOperand(x) => x.child_nodes(sink),
            Self::ValueLiteral(x) => x.child_nodes(sink),
            Self::Constant(x) => x.child_nodes(sink),
            Self::PatternOperation(x) => x.child_nodes(sink),
            Self::Variable(x) => x.child_nodes(sink),
            Self::Integer(x) => x.child_nodes(sink),
            Self::Boolean(x) => x.child_nodes(sink),
            Self::ConditionCode(x) => x.child_nodes(sink),
            Self::Unquote(x) => x.child_nodes(sink),
            Self::RhsOperation(x) => x.child_nodes(sink),
        }
    }
}

/// A trait implemented by all AST nodes.
///
/// All AST nodes can:
///
/// * Enumerate their children via `ChildNodes`.
///
/// * Give you the `wast::Span` where they were defined.
///
/// * Be converted into a `DynAstRef`.
///
/// This trait is blanked implemented for everything that does those three
/// things, and in practice those three thrings are all implemented by the
/// `derive(Ast)` macro.
pub trait Ast<'a, TOperator>: 'a + ChildNodes<'a, 'a, TOperator> + Span
where
    DynAstRef<'a, TOperator>: From<&'a Self>,
    TOperator: 'a,
{
}

impl<'a, T, TOperator> Ast<'a, TOperator> for T
where
    T: 'a + ?Sized + ChildNodes<'a, 'a, TOperator> + Span,
    DynAstRef<'a, TOperator>: From<&'a Self>,
    TOperator: 'a,
{
}

/// Enumerate the child AST nodes of a given node.
pub trait ChildNodes<'a, 'b, TOperator>
where
    TOperator: 'a,
{
    /// Get each of this AST node's children, in order.
    fn child_nodes(&'b self, sink: &mut impl Extend<DynAstRef<'a, TOperator>>);
}

/// A trait for getting the span where an AST node was defined.
pub trait Span {
    /// Get the span where this AST node was defined.
    fn span(&self) -> wast::Span;
}

/// A set of optimizations.
///
/// This is the root AST node.
#[derive(Debug, Ast)]
pub struct Optimizations<'a, TOperator> {
    /// Where these `Optimizations` were defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The optimizations.
    #[peepmatic(flatten)]
    pub optimizations: Vec<Optimization<'a, TOperator>>,
}

/// A complete optimization: a left-hand side to match against and a right-hand
/// side replacement.
#[derive(Debug, Ast)]
pub struct Optimization<'a, TOperator> {
    /// Where this `Optimization` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The left-hand side that matches when this optimization applies.
    pub lhs: Lhs<'a, TOperator>,

    /// The new sequence of instructions to replace an old sequence that matches
    /// the left-hand side with.
    pub rhs: Rhs<'a, TOperator>,
}

/// A left-hand side describes what is required for a particular optimization to
/// apply.
///
/// A left-hand side has two parts: a structural pattern for describing
/// candidate instruction sequences, and zero or more preconditions that add
/// additional constraints upon instruction sequences matched by the pattern.
#[derive(Debug, Ast)]
pub struct Lhs<'a, TOperator> {
    /// Where this `Lhs` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// A pattern that describes sequences of instructions to match.
    pub pattern: Pattern<'a, TOperator>,

    /// Additional constraints that a match must satisfy in addition to
    /// structually matching the pattern, e.g. some constant must be a power of
    /// two.
    #[peepmatic(flatten)]
    pub preconditions: Vec<Precondition<'a, TOperator>>,
}

/// A structural pattern, potentially with wildcard variables for matching whole
/// subtrees.
#[derive(Debug, Ast)]
pub enum Pattern<'a, TOperator> {
    /// A specific value. These are written as `1234` or `0x1234` or `true` or
    /// `false`.
    ValueLiteral(ValueLiteral<'a, TOperator>),

    /// A constant that matches any constant value. This subsumes value
    /// patterns. These are upper-case identifiers like `$C`.
    Constant(Constant<'a, TOperator>),

    /// An operation pattern with zero or more operand patterns. These are
    /// s-expressions like `(iadd $x $y)`.
    Operation(Operation<'a, TOperator, Pattern<'a, TOperator>>),

    /// A variable that matches any kind of subexpression. This subsumes all
    /// other patterns. These are lower-case identifiers like `$x`.
    Variable(Variable<'a, TOperator>),
}

/// An integer or boolean value literal.
#[derive(Debug, Ast)]
pub enum ValueLiteral<'a, TOperator> {
    /// An integer value.
    Integer(Integer<'a, TOperator>),

    /// A boolean value: `true` or `false`.
    Boolean(Boolean<'a, TOperator>),

    /// A condition code: `eq`, `ne`, etc...
    ConditionCode(ConditionCode<'a, TOperator>),
}

/// An integer literal.
#[derive(Debug, PartialEq, Eq, Ast)]
pub struct Integer<'a, TOperator> {
    /// Where this `Integer` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The integer value.
    ///
    /// Note that although Cranelift allows 128 bits wide values, the widest
    /// supported constants as immediates are 64 bits.
    #[peepmatic(skip_child)]
    pub value: i64,

    /// The bit width of this integer.
    ///
    /// This is either a fixed bit width, or polymorphic over the width of the
    /// optimization.
    ///
    /// This field is initialized from `None` to `Some` by the type checking
    /// pass in `src/verify.rs`.
    #[peepmatic(skip_child)]
    pub bit_width: Cell<Option<BitWidth>>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}

impl<TOperator> Hash for Integer<'_, TOperator> {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        let Integer {
            span,
            value,
            bit_width,
            marker: _,
        } = self;
        span.hash(state);
        value.hash(state);
        let bit_width = bit_width.get();
        bit_width.hash(state);
    }
}

/// A boolean literal.
#[derive(Debug, PartialEq, Eq, Ast)]
pub struct Boolean<'a, TOperator> {
    /// Where this `Boolean` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The boolean value.
    #[peepmatic(skip_child)]
    pub value: bool,

    /// The bit width of this boolean.
    ///
    /// This is either a fixed bit width, or polymorphic over the width of the
    /// optimization.
    ///
    /// This field is initialized from `None` to `Some` by the type checking
    /// pass in `src/verify.rs`.
    #[peepmatic(skip_child)]
    pub bit_width: Cell<Option<BitWidth>>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}

impl<TOperator> Hash for Boolean<'_, TOperator> {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        let Boolean {
            span,
            value,
            bit_width,
            marker: _,
        } = self;
        span.hash(state);
        value.hash(state);
        let bit_width = bit_width.get();
        bit_width.hash(state);
    }
}

/// A condition code.
#[derive(Debug, Ast)]
pub struct ConditionCode<'a, TOperator> {
    /// Where this `ConditionCode` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The actual condition code.
    #[peepmatic(skip_child)]
    pub cc: peepmatic_runtime::cc::ConditionCode,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}

/// A symbolic constant.
///
/// These are identifiers containing uppercase letters: `$C`, `$MY-CONST`,
/// `$CONSTANT1`.
#[derive(Debug, Ast)]
pub struct Constant<'a, TOperator> {
    /// Where this `Constant` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// This constant's identifier.
    #[peepmatic(skip_child)]
    pub id: Id<'a>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}

/// A variable that matches any subtree.
///
/// Duplicate uses of the same variable constrain each occurrence's match to
/// being the same as each other occurrence as well, e.g. `(iadd $x $x)` matches
/// `(iadd 5 5)` but not `(iadd 1 2)`.
#[derive(Debug, Ast)]
pub struct Variable<'a, TOperator> {
    /// Where this `Variable` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// This variable's identifier.
    #[peepmatic(skip_child)]
    pub id: Id<'a>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}

/// An operation with an operator, and operands of type `T`.
#[derive(Debug, Ast)]
#[peepmatic(no_into_dyn_node)]
pub struct Operation<'a, TOperator, TOperand>
where
    TOperator: 'a,
    TOperand: 'a + Ast<'a, TOperator>,
    DynAstRef<'a, TOperator>: From<&'a TOperand>,
{
    /// The span where this operation was written.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The operator for this operation, e.g. `imul` or `iadd`.
    #[peepmatic(skip_child)]
    pub operator: TOperator,

    /// An optional ascribed or inferred type for the operator.
    #[peepmatic(skip_child)]
    pub r#type: Cell<Option<Type>>,

    /// This operation's operands.
    ///
    /// When `Operation` is used in a pattern, these are the sub-patterns for
    /// the operands. When `Operation is used in a right-hand side replacement,
    /// these are the sub-replacements for the operands.
    #[peepmatic(flatten)]
    pub operands: Vec<TOperand>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a ()>,
}

impl<'a, TOperator> From<&'a Operation<'a, TOperator, Pattern<'a, TOperator>>>
    for DynAstRef<'a, TOperator>
{
    #[inline]
    fn from(o: &'a Operation<'a, TOperator, Pattern<'a, TOperator>>) -> DynAstRef<'a, TOperator> {
        DynAstRef::PatternOperation(o)
    }
}

impl<'a, TOperator> From<&'a Operation<'a, TOperator, Rhs<'a, TOperator>>>
    for DynAstRef<'a, TOperator>
{
    #[inline]
    fn from(o: &'a Operation<'a, TOperator, Rhs<'a, TOperator>>) -> DynAstRef<'a, TOperator> {
        DynAstRef::RhsOperation(o)
    }
}

/// A precondition adds additional constraints to a pattern, such as "$C must be
/// a power of two".
#[derive(Debug, Ast)]
pub struct Precondition<'a, TOperator> {
    /// Where this `Precondition` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The constraint operator.
    #[peepmatic(skip_child)]
    pub constraint: Constraint,

    /// The operands of the constraint.
    #[peepmatic(flatten)]
    pub operands: Vec<ConstraintOperand<'a, TOperator>>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}

/// Contraint operators.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Constraint {
    /// Is the operand a power of two?
    IsPowerOfTwo,

    /// Check the bit width of a value.
    BitWidth,

    /// Does the argument fit within our target architecture's native word size?
    FitsInNativeWord,
}

/// An operand of a precondition's constraint.
#[derive(Debug, Ast)]
pub enum ConstraintOperand<'a, TOperator> {
    /// A value literal operand.
    ValueLiteral(ValueLiteral<'a, TOperator>),

    /// A constant operand.
    Constant(Constant<'a, TOperator>),

    /// A variable operand.
    Variable(Variable<'a, TOperator>),
}

/// The right-hand side of an optimization that contains the instructions to
/// replace any matched left-hand side with.
#[derive(Debug, Ast)]
pub enum Rhs<'a, TOperator> {
    /// A value literal right-hand side.
    ValueLiteral(ValueLiteral<'a, TOperator>),

    /// A constant right-hand side (the constant must have been matched and
    /// bound in the left-hand side's pattern).
    Constant(Constant<'a, TOperator>),

    /// A variable right-hand side (the variable must have been matched and
    /// bound in the left-hand side's pattern).
    Variable(Variable<'a, TOperator>),

    /// An unquote expression that is evaluated while replacing the left-hand
    /// side with the right-hand side. The result of the evaluation is used in
    /// the replacement.
    Unquote(Unquote<'a, TOperator>),

    /// A compound right-hand side consisting of an operation and subsequent
    /// right-hand side operands.
    Operation(Operation<'a, TOperator, Rhs<'a, TOperator>>),
}

/// An unquote operation.
///
/// Rather than replaciong a left-hand side, these are evaluated and then the
/// result of the evaluation replaces the left-hand side. This allows for
/// compile-time computation while replacing a matched left-hand side with a
/// right-hand side.
///
/// For example, given the unqouted right-hand side `$(log2 $C)`, we replace any
/// instructions that match its left-hand side with the compile-time result of
/// `log2($C)` (the left-hand side must match and bind the constant `$C`).
#[derive(Debug, Ast)]
pub struct Unquote<'a, TOperator> {
    /// Where this `Unquote` was defined.
    #[peepmatic(skip_child)]
    pub span: wast::Span,

    /// The operator for this unquote operation.
    #[peepmatic(skip_child)]
    pub operator: UnquoteOperator,

    /// The operands for this unquote operation.
    #[peepmatic(flatten)]
    pub operands: Vec<Rhs<'a, TOperator>>,

    #[allow(missing_docs)]
    #[peepmatic(skip_child)]
    pub marker: PhantomData<&'a TOperator>,
}