thalir-core 0.1.0

Core IR types and builders for ThalIR smart contract analysis
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
use super::{IRContext, IRRegistry};
use crate::{
    block::{BlockId, Terminator},
    function::{
        DataLocation, Function, FunctionSignature, LocalId, LocalVariable, Mutability, Parameter,
        Visibility,
    },
    instructions::{ContextVariable, Instruction, StorageKey},
    types::Type,
    values::{Constant, ParamId, SourceLocation, Value},
    IrError, Result,
};
use std::collections::HashSet;

#[allow(dead_code)]

pub struct FunctionBuilderCursor<'a> {
    contract_name: String,
    function: Function,
    context: &'a mut IRContext,
    registry: &'a mut IRRegistry,
    created_blocks: HashSet<BlockId>,
    current_source_location: Option<SourceLocation>,
}

impl<'a> FunctionBuilderCursor<'a> {
    pub fn new(
        contract_name: String,
        name: String,
        context: &'a mut IRContext,
        registry: &'a mut IRRegistry,
    ) -> Self {
        let signature = FunctionSignature {
            name: name.clone(),
            params: Vec::new(),
            returns: Vec::new(),
            is_payable: false,
        };

        let function = Function::new(signature);

        Self {
            contract_name,
            function,
            context,
            registry,
            created_blocks: HashSet::new(),
            current_source_location: None,
        }
    }

    pub fn set_source_location(&mut self, location: SourceLocation) {
        self.current_source_location = Some(location);
    }

    pub fn clear_source_location(&mut self) {
        self.current_source_location = None;
    }

    pub fn init_cursor(&mut self) {}

    pub fn param(&mut self, name: &str, ty: Type) -> &mut Self {
        self.function
            .signature
            .params
            .push(Parameter::new(name, ty));
        self
    }

    pub fn get_params(&self) -> &Vec<Parameter> {
        &self.function.signature.params
    }

    pub fn returns(&mut self, ty: Type) -> &mut Self {
        self.function.signature.returns = vec![ty];
        self
    }

    pub fn returns_multiple(&mut self, types: Vec<Type>) -> &mut Self {
        self.function.signature.returns = types;
        self
    }

    pub fn visibility(&mut self, vis: Visibility) -> &mut Self {
        self.function.visibility = vis;
        self
    }

    pub fn mutability(&mut self, mut_: Mutability) -> &mut Self {
        self.function.mutability = mut_;
        self
    }

    pub fn create_block(&mut self) -> BlockId {
        let block_id = self.function.body.create_block();
        self.created_blocks.insert(block_id);
        block_id
    }

    pub fn entry_block(&self) -> BlockId {
        self.function.body.entry_block
    }

    pub fn switch_to_block(&mut self, block_id: BlockId) -> Result<()> {
        if !self.created_blocks.contains(&block_id) && block_id != self.function.body.entry_block {
            return Err(IrError::BuilderError(format!(
                "Block {:?} does not exist",
                block_id
            )));
        }

        self.context.set_current_block(block_id);
        Ok(())
    }

    pub fn current_block(&self) -> Option<BlockId> {
        self.context.current_block()
    }

    pub fn is_terminated(&self) -> bool {
        if let Some(block_id) = self.current_block() {
            self.function
                .body
                .blocks
                .get(&block_id)
                .map(|b| b.is_terminated())
                .unwrap_or(false)
        } else {
            false
        }
    }

    pub fn ins(&mut self) -> Result<FunctionInstBuilder<'_>> {
        let block_id = self.current_block().ok_or_else(|| {
            IrError::BuilderError("No current block - call switch_to_block first".into())
        })?;

        Ok(FunctionInstBuilder {
            block_id,
            function: &mut self.function,
            context: self.context,
            source_location: self.current_source_location.clone(),
        })
    }

    pub fn local(&mut self, name: &str, ty: Type) -> Value {
        let var_id = self.context.ssa().get_or_create_var(name);
        self.function.body.locals.push(LocalVariable {
            id: LocalId(self.function.body.locals.len() as u32),
            name: name.to_string(),
            var_type: ty,
            location: DataLocation::Memory,
        });
        Value::Variable(var_id)
    }

    pub fn get_param(&self, index: usize) -> Value {
        Value::Param(ParamId(index as u32))
    }

    pub fn build(self) -> Result<Function> {
        for block_id in &self.created_blocks {
            if let Some(block) = self.function.body.blocks.get(block_id) {
                if !block.is_terminated() {
                    return Err(IrError::BuilderError(format!(
                        "Block {:?} is not terminated",
                        block_id
                    )));
                }
            }
        }

        self.registry
            .add_function(self.contract_name.clone(), self.function.clone())?;
        Ok(self.function)
    }
}

pub struct FunctionInstBuilder<'a> {
    block_id: BlockId,
    function: &'a mut Function,
    #[allow(dead_code)]
    context: &'a mut IRContext,
    source_location: Option<SourceLocation>,
}

impl<'a> FunctionInstBuilder<'a> {
    pub fn constant_bool(&mut self, value: bool) -> Value {
        Value::Constant(Constant::Bool(value))
    }

    pub fn constant_uint(&mut self, value: u64, bits: u16) -> Value {
        use num_bigint::BigUint;
        Value::Constant(Constant::Uint(BigUint::from(value), bits))
    }

    pub fn constant_int(&mut self, value: i64, bits: u16) -> Value {
        use num_bigint::BigInt;
        Value::Constant(Constant::Int(BigInt::from(value), bits))
    }

    pub fn add(&mut self, left: Value, right: Value, ty: Type) -> Value {
        let result = self.next_value();
        let inst = Instruction::Add {
            result: result.clone(),
            left,
            right,
            ty,
        };
        self.insert_inst(inst);
        result
    }

    pub fn sub(&mut self, left: Value, right: Value, ty: Type) -> Value {
        let result = self.next_value();
        let inst = Instruction::Sub {
            result: result.clone(),
            left,
            right,
            ty,
        };
        self.insert_inst(inst);
        result
    }

    pub fn lt(&mut self, left: Value, right: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::Lt {
            result: result.clone(),
            left,
            right,
        };
        self.insert_inst(inst);
        result
    }

    pub fn eq(&mut self, left: Value, right: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::Eq {
            result: result.clone(),
            left,
            right,
        };
        self.insert_inst(inst);
        result
    }

    pub fn gt(&mut self, left: Value, right: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::Gt {
            result: result.clone(),
            left,
            right,
        };
        self.insert_inst(inst);
        result
    }

    pub fn mul(&mut self, left: Value, right: Value, ty: Type) -> Value {
        let result = self.next_value();
        let inst = Instruction::Mul {
            result: result.clone(),
            left,
            right,
            ty,
        };
        self.insert_inst(inst);
        result
    }

    pub fn div(&mut self, left: Value, right: Value, ty: Type) -> Value {
        let result = self.next_value();
        let inst = Instruction::Div {
            result: result.clone(),
            left,
            right,
            ty,
        };
        self.insert_inst(inst);
        result
    }

    pub fn not(&mut self, value: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::Not {
            result: result.clone(),
            operand: value,
        };
        self.insert_inst(inst);
        result
    }

    pub fn and(&mut self, left: Value, right: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::And {
            result: result.clone(),
            left,
            right,
        };
        self.insert_inst(inst);
        result
    }

    pub fn or(&mut self, left: Value, right: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::Or {
            result: result.clone(),
            left,
            right,
        };
        self.insert_inst(inst);
        result
    }

    pub fn sload(&mut self, key: Value) -> Value {
        let result = self.next_value();
        let inst = Instruction::StorageLoad {
            result: result.clone(),
            key: StorageKey::Dynamic(key),
        };
        self.insert_inst(inst);
        result
    }

    pub fn sstore(&mut self, key: Value, value: Value) -> Result<()> {
        let inst = Instruction::StorageStore {
            key: StorageKey::Dynamic(key),
            value,
        };
        self.insert_inst(inst);
        Ok(())
    }

    pub fn branch(
        &mut self,
        condition: Value,
        then_block: BlockId,
        else_block: BlockId,
    ) -> Result<()> {
        let term = Terminator::Branch {
            condition,
            then_block,
            then_args: Vec::new(),
            else_block,
            else_args: Vec::new(),
        };
        self.set_terminator(term)
    }

    pub fn jump(&mut self, target: BlockId) -> Result<()> {
        let term = Terminator::Jump(target, Vec::new());
        self.set_terminator(term)
    }

    pub fn return_value(&mut self, value: Value) -> Result<()> {
        let term = Terminator::Return(Some(value));
        self.set_terminator(term)
    }

    pub fn return_void(&mut self) -> Result<()> {
        let term = Terminator::Return(None);
        self.set_terminator(term)
    }

    pub fn msg_sender(&mut self) -> Value {
        let result = self.next_value();
        let inst = Instruction::GetContext {
            result: result.clone(),
            var: ContextVariable::MsgSender,
        };
        self.insert_inst(inst);
        result
    }

    pub fn msg_value(&mut self) -> Value {
        let result = self.next_value();
        let inst = Instruction::GetContext {
            result: result.clone(),
            var: ContextVariable::MsgValue,
        };
        self.insert_inst(inst);
        result
    }

    fn insert_inst(&mut self, inst: Instruction) {
        if let Some(block) = self.function.body.blocks.get_mut(&self.block_id) {
            if let Some(ref location) = self.source_location {
                let index = block.instructions.len();
                block
                    .metadata
                    .instruction_locations
                    .insert(index, location.clone());
            }
            block.instructions.push(inst);
        }
    }

    fn set_terminator(&mut self, term: Terminator) -> Result<()> {
        if let Some(block) = self.function.body.blocks.get_mut(&self.block_id) {
            if !matches!(block.terminator, Terminator::Invalid) {
                return Err(IrError::BuilderError("Block already terminated".into()));
            }
            block.terminator = term;
            Ok(())
        } else {
            Err(IrError::BuilderError("Block not found".into()))
        }
    }

    fn next_value(&mut self) -> Value {
        use crate::values::TempId;
        use std::sync::atomic::{AtomicU32, Ordering};

        static COUNTER: AtomicU32 = AtomicU32::new(1000);
        let id = COUNTER.fetch_add(1, Ordering::Relaxed);
        Value::Temp(TempId(id))
    }
}