sway-core 0.71.0

Sway core language.
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
use super::{AllocatedProgram, FnName, SelectorOpt};
use crate::{
    asm_generation::{
        fuel::{
            abstract_instruction_set::AbstractInstructionSet,
            allocated_abstract_instruction_set::AllocatedAbstractInstructionSet,
            compiler_constants,
            data_section::{DataSection, Entry, EntryName},
            globals_section::GlobalsSection,
            register_sequencer::RegisterSequencer,
        },
        ProgramKind,
    },
    asm_lang::{
        allocated_ops::{AllocatedInstruction, AllocatedRegister},
        AllocatedAbstractOp, ConstantRegister, ControlFlowOp, JumpType, Label, VirtualImmediate12,
        VirtualImmediate18, VirtualImmediate24,
    },
    decl_engine::DeclRefFunction,
    OptLevel,
};
use either::Either;
use sway_error::error::CompileError;
use sway_features::ExperimentalFeatures;

/// The entry point of an abstract program.
pub(crate) struct AbstractEntry {
    pub(crate) selector: SelectorOpt,
    pub(crate) label: Label,
    pub(crate) ops: AbstractInstructionSet,
    pub(crate) name: FnName,
    pub(crate) test_decl_ref: Option<DeclRefFunction>,
}

/// An [AbstractProgram] represents code generated by the compilation from IR, with virtual registers
/// and abstract control flow.
///
/// Use `AbstractProgram::to_allocated_program()` to perform register allocation.
///
pub(crate) struct AbstractProgram {
    kind: ProgramKind,
    data_section: DataSection,
    globals_section: GlobalsSection,
    before_entries: AbstractInstructionSet,
    entries: Vec<AbstractEntry>,
    non_entries: Vec<AbstractInstructionSet>,
    reg_seqr: RegisterSequencer,
    experimental: ExperimentalFeatures,
}

impl AbstractProgram {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        kind: ProgramKind,
        data_section: DataSection,
        globals_section: GlobalsSection,
        before_entries: AbstractInstructionSet,
        entries: Vec<AbstractEntry>,
        non_entries: Vec<AbstractInstructionSet>,
        reg_seqr: RegisterSequencer,
        experimental: ExperimentalFeatures,
    ) -> Self {
        AbstractProgram {
            kind,
            data_section,
            globals_section,
            before_entries,
            entries,
            non_entries,
            reg_seqr,
            experimental,
        }
    }

    /// True if the [AbstractProgram] does not contain any instructions, or entries, or data in the data section.
    pub(crate) fn is_empty(&self) -> bool {
        self.non_entries.is_empty()
            && self.entries.is_empty()
            && self.data_section.iter_all_entries().next().is_none()
    }

    /// Adds prologue, globals allocation, before entries, contract method switch, and allocates virtual register.
    pub(crate) fn into_allocated_program(
        mut self,
        fallback_fn: Option<crate::asm_lang::Label>,
        opt_level: OptLevel,
    ) -> Result<AllocatedProgram, CompileError> {
        let mut prologue = self.build_prologue();
        self.append_globals_allocation(&mut prologue);
        self.append_before_entries(&mut prologue, opt_level)?;

        match (self.experimental.new_encoding, self.kind) {
            (true, ProgramKind::Contract) => {
                self.append_jump_to_entry(&mut prologue);
            }
            (false, ProgramKind::Contract) => {
                self.append_encoding_v0_contract_abi_switch(&mut prologue, fallback_fn);
            }
            _ => {}
        }

        // Keep track of the labels (and names) that represent program entry points.
        let entries: Vec<_> = self
            .entries
            .iter()
            .map(|entry| {
                (
                    entry.selector,
                    entry.label,
                    entry.name.clone(),
                    entry.test_decl_ref.clone(),
                )
            })
            .collect();

        // Gather all functions.
        let all_functions = self
            .entries
            .into_iter()
            .map(|entry| entry.ops)
            .chain(self.non_entries);

        // Optimize and then verify abstract functions.
        let abstract_functions = all_functions
            .map(|instruction_set| instruction_set.optimize(&self.data_section, opt_level))
            .map(AbstractInstructionSet::verify)
            .collect::<Result<Vec<AbstractInstructionSet>, CompileError>>()?;

        // Allocate the registers for each function.
        let allocated_functions = abstract_functions
            .into_iter()
            .map(|abstract_instruction_set| {
                let allocated = abstract_instruction_set.allocate_registers()?;
                Ok(allocated.lower_pusha_popa())
            })
            .collect::<Result<Vec<AllocatedAbstractInstructionSet>, CompileError>>()?;

        // Optimize allocated functions.
        let functions = allocated_functions
            .into_iter()
            .map(|instruction_set| instruction_set.optimize())
            // TODO: Add verification. E.g., verify that:
            //        - function has exactly one CFEI/CFSI pair,
            //        - the stack use for each function is balanced,
            //        - $$locbase is only used if stack has been allocated for it.
            //        - etc.
            // .map(AllocatedAbstractInstructionSet::verify)
            .collect::<Vec<AllocatedAbstractInstructionSet>>();

        Ok(AllocatedProgram {
            kind: self.kind,
            data_section: self.data_section,
            prologue,
            functions,
            entries,
        })
    }

    fn append_before_entries(
        &self,
        prologue: &mut AllocatedAbstractInstructionSet,
        opt_level: OptLevel,
    ) -> Result<(), CompileError> {
        let before_entries = self
            .before_entries
            .clone()
            .optimize(&self.data_section, opt_level);
        let before_entries = before_entries.verify()?;
        let mut before_entries = before_entries.allocate_registers()?;
        prologue.ops.append(&mut before_entries.ops);
        Ok(())
    }

    /// Builds the asm preamble, which includes metadata and a jump past the metadata.
    /// Right now, it looks like this:
    ///
    /// WORD OP
    ///     1    MOV $scratch $pc
    ///     -    JMPF $zero i10
    ///     2    DATA_START (0-32) (in bytes, offset from $is)
    ///     -    DATA_START (32-64)
    ///     3    CONFIGURABLES_OFFSET (0-32)
    ///     -    CONFIGURABLES_OFFSET (32-64)
    ///     4    LW $ds $scratch 1
    ///     -    ADD $ds $ds $scratch
    ///     5    .program_start:
    fn build_prologue(&mut self) -> AllocatedAbstractInstructionSet {
        const _: () = assert!(
            crate::PRELUDE_CONFIGURABLES_OFFSET_IN_BYTES == 16,
            "Inconsistency in the assumption of prelude organisation"
        );
        const _: () = assert!(
            crate::PRELUDE_CONFIGURABLES_SIZE_IN_BYTES == 8,
            "Inconsistency in the assumption of prelude organisation"
        );
        const _: () = assert!(
            crate::PRELUDE_SIZE_IN_BYTES == 32,
            "Inconsistency in the assumption of prelude organisation"
        );
        let label = self.reg_seqr.get_label();
        AllocatedAbstractInstructionSet {
            function: None,
            ops: [
                AllocatedAbstractOp {
                    opcode: Either::Left(AllocatedInstruction::MOVE(
                        AllocatedRegister::Constant(ConstantRegister::Scratch),
                        AllocatedRegister::Constant(ConstantRegister::ProgramCounter),
                    )),
                    comment: String::new(),
                    owning_span: None,
                },
                // word 1.5
                AllocatedAbstractOp {
                    opcode: Either::Right(ControlFlowOp::Jump {
                        to: label,
                        type_: JumpType::Unconditional,
                    }),
                    comment: String::new(),
                    owning_span: None,
                },
                // word 2 -- full word u64 placeholder
                AllocatedAbstractOp {
                    opcode: Either::Right(ControlFlowOp::DataSectionOffsetPlaceholder),
                    comment: "data section offset".into(),
                    owning_span: None,
                },
                // word 3 -- full word u64 placeholder
                AllocatedAbstractOp {
                    opcode: Either::Right(ControlFlowOp::ConfigurablesOffsetPlaceholder),
                    comment: "configurables offset".into(),
                    owning_span: None,
                },
                AllocatedAbstractOp {
                    opcode: Either::Right(ControlFlowOp::Label(label)),
                    comment: "end of configurables offset".into(),
                    owning_span: None,
                },
                // word 4 -- load the data offset into $ds
                AllocatedAbstractOp {
                    opcode: Either::Left(AllocatedInstruction::LW(
                        AllocatedRegister::Constant(ConstantRegister::DataSectionStart),
                        AllocatedRegister::Constant(ConstantRegister::Scratch),
                        VirtualImmediate12::new(1),
                    )),
                    comment: "".into(),
                    owning_span: None,
                },
                // word 4.5 -- add $ds $ds $is
                AllocatedAbstractOp {
                    opcode: Either::Left(AllocatedInstruction::ADD(
                        AllocatedRegister::Constant(ConstantRegister::DataSectionStart),
                        AllocatedRegister::Constant(ConstantRegister::DataSectionStart),
                        AllocatedRegister::Constant(ConstantRegister::Scratch),
                    )),
                    comment: "".into(),
                    owning_span: None,
                },
            ]
            .to_vec(),
        }
    }

    // WHen the new encoding is used, jumps to the `__entry`  function
    fn append_jump_to_entry(&mut self, asm: &mut AllocatedAbstractInstructionSet) {
        let entry = self.entries.iter().find(|x| x.name == "__entry").unwrap();
        asm.ops.push(AllocatedAbstractOp {
            opcode: Either::Right(ControlFlowOp::Jump {
                to: entry.label,
                type_: JumpType::Unconditional,
            }),
            comment: "jump to ABI function selector".into(),
            owning_span: None,
        });
    }

    /// Builds the contract switch statement based on the first argument to a contract call: the
    /// 'selector'.
    /// See https://fuellabs.github.io/fuel-specs/master/vm#call-frames which
    /// describes the first argument to be at word offset 73.
    fn append_encoding_v0_contract_abi_switch(
        &mut self,
        asm: &mut AllocatedAbstractInstructionSet,
        fallback_fn: Option<crate::asm_lang::Label>,
    ) {
        const SELECTOR_WORD_OFFSET: u64 = 73;
        const INPUT_SELECTOR_REG: AllocatedRegister = AllocatedRegister::Allocated(0);
        const PROG_SELECTOR_REG: AllocatedRegister = AllocatedRegister::Allocated(1);
        const CMP_RESULT_REG: AllocatedRegister = AllocatedRegister::Allocated(2);

        // Build the switch statement for selectors.
        asm.ops.push(AllocatedAbstractOp {
            opcode: Either::Right(ControlFlowOp::Comment),
            comment: "[function selection]: begin contract function selector switch".into(),
            owning_span: None,
        });

        // Load the selector from the call frame.
        asm.ops.push(AllocatedAbstractOp {
            opcode: Either::Left(AllocatedInstruction::LW(
                INPUT_SELECTOR_REG,
                AllocatedRegister::Constant(ConstantRegister::FramePointer),
                VirtualImmediate12::new(SELECTOR_WORD_OFFSET),
            )),
            comment: "[function selection]: load input function selector".into(),
            owning_span: None,
        });

        // Add a 'case' for each entry with a selector.
        for entry in &self.entries {
            let selector = match entry.selector {
                Some(sel) => sel,
                // Skip entries that don't have a selector - they're probably tests.
                None => continue,
            };

            // Put the selector in the data section.
            let data_label = self.data_section.insert_data_value(Entry::new_word(
                u32::from_be_bytes(selector) as u64,
                EntryName::NonConfigurable,
                None,
            ));

            // Load the data into a register for comparison.
            asm.ops.push(AllocatedAbstractOp {
                opcode: Either::Left(AllocatedInstruction::LoadDataId(
                    PROG_SELECTOR_REG,
                    data_label,
                )),
                comment: format!(
                    "[function selection]: load function {} selector for comparison",
                    entry.name
                ),
                owning_span: None,
            });

            // Compare with the input selector.
            asm.ops.push(AllocatedAbstractOp {
                opcode: Either::Left(AllocatedInstruction::EQ(
                    CMP_RESULT_REG,
                    INPUT_SELECTOR_REG,
                    PROG_SELECTOR_REG,
                )),
                comment: format!(
                    "[function selection]: compare function {} selector with input selector",
                    entry.name
                ),
                owning_span: None,
            });

            // Jump to the function label if the selector was equal.
            asm.ops.push(AllocatedAbstractOp {
                // If the comparison result is _not_ equal to 0, then it was indeed equal.
                opcode: Either::Right(ControlFlowOp::Jump {
                    to: entry.label,
                    type_: JumpType::NotZero(CMP_RESULT_REG),
                }),
                comment: "[function selection]: jump to selected contract function".into(),
                owning_span: None,
            });
        }

        if let Some(fallback_fn) = fallback_fn {
            asm.ops.push(AllocatedAbstractOp {
                opcode: Either::Right(ControlFlowOp::Jump {
                    to: fallback_fn,
                    type_: JumpType::Call,
                }),
                comment: "[function selection]: call contract fallback function".into(),
                owning_span: None,
            });
        }

        asm.ops.push(AllocatedAbstractOp {
            opcode: Either::Left(AllocatedInstruction::MOVI(
                AllocatedRegister::Constant(ConstantRegister::Scratch),
                VirtualImmediate18::new(compiler_constants::MISMATCHED_SELECTOR_REVERT_CODE.into()),
            )),
            comment: "[function selection]: load revert code for mismatched function selector"
                .into(),
            owning_span: None,
        });
        asm.ops.push(AllocatedAbstractOp {
            opcode: Either::Left(AllocatedInstruction::RVRT(AllocatedRegister::Constant(
                ConstantRegister::Scratch,
            ))),
            comment: "[function selection]: revert if no selectors have matched".into(),
            owning_span: None,
        });
    }

    fn append_globals_allocation(&self, asm: &mut AllocatedAbstractInstructionSet) {
        let len_in_bytes = self.globals_section.len_in_bytes();
        asm.ops.push(AllocatedAbstractOp {
            opcode: Either::Left(AllocatedInstruction::CFEI(VirtualImmediate24::new(
                len_in_bytes,
            ))),
            comment: "allocate stack space for globals".into(),
            owning_span: None,
        });
    }
}

impl std::fmt::Display for AbstractProgram {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, ";; Program kind: {:?}", self.kind)?;

        writeln!(f, ";; --- Before Entries ---")?;
        writeln!(f, "{}\n", self.before_entries)?;

        writeln!(f, ";; --- Entries ---")?;
        for entry in &self.entries {
            writeln!(f, "{}\n", entry.ops)?;
        }
        writeln!(f, ";; --- Functions ---")?;
        for function in &self.non_entries {
            writeln!(f, "{function}\n")?;
        }
        writeln!(f, ";; --- Data ---")?;
        write!(f, "{}", self.data_section)
    }
}