To protect your data, the CISO officer has suggested users to enable GitLab 2FA as soon as possible.

ir.rs 24 KB
Newer Older
1
use ast::ptr::P;
qinsoon's avatar
qinsoon committed
2
use ast::op::*;
3
4
use ast::types::*;

5
use std::collections::HashMap;
qinsoon's avatar
qinsoon committed
6
use std::fmt;
qinsoon's avatar
qinsoon committed
7
use std::cell::Cell;
8
use std::cell::RefCell;
qinsoon's avatar
qinsoon committed
9

qinsoon's avatar
qinsoon committed
10
11
12
13
14
pub type WPID  = usize;
pub type MuID  = usize;
pub type MuTag = &'static str;
pub type Address = usize; // TODO: replace this with Address(usize)

15
16
pub type OpIndex = usize;

17
#[derive(Debug)]
qinsoon's avatar
qinsoon committed
18
19
20
pub struct MuFunction {
    pub fn_name: MuTag,
    pub sig: P<MuFuncSig>,
21
    pub content: Option<FunctionContent>,
qinsoon's avatar
qinsoon committed
22
    pub context: FunctionContext
23
24
25
26
}

#[derive(Debug)]
pub struct FunctionContent {
qinsoon's avatar
qinsoon committed
27
28
    pub entry: MuTag,
    pub blocks: Vec<(MuTag, Block)>
qinsoon's avatar
qinsoon committed
29
30
}

qinsoon's avatar
qinsoon committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#[derive(Debug)]
pub struct FunctionContext {
    pub values: HashMap<MuID, ValueEntry>
}

impl FunctionContext {
    fn new() -> FunctionContext {
        FunctionContext {
            values: HashMap::new()
        }
    }
    
    pub fn get_value(&self, id: MuID) -> Option<&ValueEntry> {
        self.values.get(&id)
    }
46
47
48
49
    
    pub fn get_value_mut(&mut self, id: MuID) -> Option<&mut ValueEntry> {
        self.values.get_mut(&id)
    }
qinsoon's avatar
qinsoon committed
50
51
}

52
53
impl MuFunction {
    pub fn new(fn_name: MuTag, sig: P<MuFuncSig>) -> MuFunction {
qinsoon's avatar
qinsoon committed
54
        MuFunction{fn_name: fn_name, sig: sig, content: None, context: FunctionContext::new()}
55
56
57
58
59
60
61
    }
    
    pub fn define(&mut self, content: FunctionContent) {
        self.content = Some(content)
    }
    
    pub fn new_ssa(&mut self, id: MuID, tag: MuTag, ty: P<MuType>) -> P<TreeNode> {
62
        self.context.values.insert(id, ValueEntry{id: id, tag: tag, ty: ty.clone(), use_count: Cell::new(0), expr: None});
63
64
        
        P(TreeNode {
qinsoon's avatar
qinsoon committed
65
66
67
68
69
            v: TreeNode_::Value(P(Value{
                tag: tag,
                ty: ty,
                v: Value_::SSAVar(id)
            }))
70
71
72
        })
    }
    
qinsoon's avatar
qinsoon committed
73
    pub fn new_constant(&mut self, tag: MuTag, ty: P<MuType>, v: Constant) -> P<TreeNode> {
74
        P(TreeNode{
qinsoon's avatar
qinsoon committed
75
76
77
78
79
80
            v: TreeNode_::Value(P(Value{
                tag: tag,
                ty: ty, 
                v: Value_::Constant(v)
            }))
        })
81
82
83
84
    }
    
    pub fn new_value(&mut self, v: P<Value>) -> P<TreeNode> {
        P(TreeNode{
qinsoon's avatar
qinsoon committed
85
86
            v: TreeNode_::Value(v)
        })
87
88
89
    }    
}

90
#[derive(Debug)]
91
pub struct Block {
92
93
    pub label: MuTag,
    pub content: Option<BlockContent>
qinsoon's avatar
qinsoon committed
94
95
}

96
97
98
99
100
101
impl Block {
    pub fn new(label: MuTag) -> Block {
        Block{label: label, content: None}
    }
}

102
#[derive(Debug)]
103
pub struct BlockContent {
qinsoon's avatar
qinsoon committed
104
105
106
    pub args: Vec<P<TreeNode>>,
    pub body: Vec<P<TreeNode>>,
    pub keepalives: Option<Vec<P<TreeNode>>>    
107
108
}

qinsoon's avatar
qinsoon committed
109
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
110
111
/// always use with P<TreeNode>
pub struct TreeNode {
qinsoon's avatar
qinsoon committed
112
//    pub op: OpCode,
113
    pub v: TreeNode_
qinsoon's avatar
qinsoon committed
114
115
}

116
117
118
impl TreeNode {   
    pub fn new_inst(v: Instruction) -> P<TreeNode> {
        P(TreeNode{v: TreeNode_::Instruction(v)})
qinsoon's avatar
qinsoon committed
119
    }
120
121
122
123
124
125
126
127
128
129
130
131
    
    pub fn extract_ssa_id(&self) -> Option<MuID> {
        match self.v {
            TreeNode_::Value(ref pv) => {
                match pv.v {
                    Value_::SSAVar(id) => Some(id),
                    _ => None
                }
            },
            _ => None
        }
    }
qinsoon's avatar
qinsoon committed
132
133
134
135
}

impl fmt::Debug for TreeNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136
137
138
        match self.v {
            TreeNode_::Value(ref pv) => {
                match pv.v {
139
140
                    Value_::SSAVar(id) => {
                        write!(f, "{:?} %{}#{}", pv.ty, pv.tag, id)
141
142
143
144
145
146
147
148
149
                    },
                    Value_::Constant(ref c) => {
                        write!(f, "{:?} {:?}", pv.ty, c) 
                    }
                }
            },
            TreeNode_::Instruction(ref inst) => {
                write!(f, "{:?}", inst)
            }
qinsoon's avatar
qinsoon committed
150
        }
qinsoon's avatar
qinsoon committed
151
    }
qinsoon's avatar
qinsoon committed
152
153
}

154
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
155
pub enum TreeNode_ {
qinsoon's avatar
qinsoon committed
156
    Value(P<Value>),
157
    Instruction(Instruction)
qinsoon's avatar
qinsoon committed
158
159
160
}

/// always use with P<Value>
161
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
162
pub struct Value {
163
    pub tag: MuTag,
qinsoon's avatar
qinsoon committed
164
165
    pub ty: P<MuType>,
    pub v: Value_
qinsoon's avatar
qinsoon committed
166
167
}

168
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
169
pub enum Value_ {
170
    SSAVar(MuID),
qinsoon's avatar
qinsoon committed
171
    Constant(Constant)
qinsoon's avatar
qinsoon committed
172
173
}

174
175
176
177
178
#[derive(Clone)]
pub struct ValueEntry {
    pub id: MuID,
    pub tag: MuTag,
    pub ty: P<MuType>,
179
180
181
182
183
184
185
186
    pub use_count: Cell<usize>,  // how many times this entry is used
    pub expr: Option<Instruction>
}

impl ValueEntry {
    pub fn assign_expr(&mut self, expr: Instruction) {
        self.expr = Some(expr)
    }
187
188
189
190
191
192
193
194
}

impl fmt::Debug for ValueEntry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} {}({})", self.ty, self.tag, self.id)
    }
}

195
#[derive(Clone)]
196
pub enum Constant {
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    Int(usize),
    Float(f32),
    Double(f64),
    IRef(Address),
    FuncRef(Address),
    UFuncRef(Address),
    Vector(Vec<Constant>),    
}

impl fmt::Debug for Constant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Constant::Int(v) => write!(f, "{}", v),
            &Constant::Float(v) => write!(f, "{}", v),
            &Constant::Double(v) => write!(f, "{}", v),
            &Constant::IRef(v) => write!(f, "{}", v),
            &Constant::FuncRef(v) => write!(f, "{}", v),
            &Constant::UFuncRef(v) => write!(f, "{}", v),
            &Constant::Vector(ref v) => write!(f, "{:?}", v)
        }
    }
qinsoon's avatar
qinsoon committed
218
219
}

220
#[derive(Clone)]
221
222
223
224
pub struct Instruction {
    pub value : Option<Vec<P<TreeNode>>>,
    pub ops : RefCell<Vec<P<TreeNode>>>,
    pub v: Instruction_
qinsoon's avatar
qinsoon committed
225
226
}

qinsoon's avatar
qinsoon committed
227
228
229
230
231
232
impl Instruction {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        self.v.debug_str(ops)
    }
}

qinsoon's avatar
qinsoon committed
233
234
impl fmt::Debug for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
qinsoon's avatar
qinsoon committed
235
236
237
238
239
240
        let ops = &self.ops.borrow();
        if self.value.is_some() {
            write!(f, "{:?} = {}", self.value.as_ref().unwrap(), self.v.debug_str(ops))
        } else {
            write!(f, "{}", self.v.debug_str(ops))
        }
241
242
243
    }
}

244
#[derive(Clone)]
245
246
247
248
249
250
251
pub enum Instruction_ {
    // non-terminal instruction
    
    // expressions
    
    BinOp(BinOp, OpIndex, OpIndex), 
    CmpOp(CmpOp, OpIndex, OpIndex),
qinsoon's avatar
qinsoon committed
252
253
254
255
256
257
258
259
260
    
    // yields a tuple of results from the call
    ExprCall{
        data: CallData,
        is_abort: bool, // T to abort, F to rethrow
    },
    
    // yields the memory value
    Load{
261
262
        is_ptr: bool,
        order: MemoryOrder,
263
        mem_loc: OpIndex
qinsoon's avatar
qinsoon committed
264
    },
qinsoon's avatar
qinsoon committed
265
    
qinsoon's avatar
qinsoon committed
266
267
    // yields nothing
    Store{
268
269
        is_ptr: bool,
        order: MemoryOrder,        
270
271
        mem_loc: OpIndex,
        value: OpIndex
qinsoon's avatar
qinsoon committed
272
273
274
    },
    
    // yields pair (oldvalue, boolean (T = success, F = failure))
qinsoon's avatar
qinsoon committed
275
    CmpXchg{
276
277
        is_ptr: bool,
        is_weak: bool,
qinsoon's avatar
qinsoon committed
278
279
        success_order: MemoryOrder,
        fail_order: MemoryOrder,
280
281
282
        mem_loc: OpIndex,
        expected_value: OpIndex,
        desired_value: OpIndex
qinsoon's avatar
qinsoon committed
283
284
    },
    
qinsoon's avatar
qinsoon committed
285
    // yields old memory value
qinsoon's avatar
qinsoon committed
286
    AtomicRMW{
287
        is_ptr: bool, // T for iref, F for ptr
qinsoon's avatar
qinsoon committed
288
289
        order: MemoryOrder,
        op: AtomicRMWOp,
290
291
        mem_loc: OpIndex,
        value: OpIndex // operand for op
qinsoon's avatar
qinsoon committed
292
293
    },
    
qinsoon's avatar
qinsoon committed
294
    // yields a reference of the type
qinsoon's avatar
qinsoon committed
295
    New(P<MuType>),
qinsoon's avatar
qinsoon committed
296
297
    
    // yields an iref of the type
qinsoon's avatar
qinsoon committed
298
    AllocA(P<MuType>),
qinsoon's avatar
qinsoon committed
299
300
    
    // yields ref
301
    NewHybrid(P<MuType>, OpIndex),
qinsoon's avatar
qinsoon committed
302
303
    
    // yields iref
304
    AllocAHybrid(P<MuType>, OpIndex),
qinsoon's avatar
qinsoon committed
305
306
    
    // yields stack ref
307
    NewStack(OpIndex), // func
308
                           // TODO: common inst
qinsoon's avatar
qinsoon committed
309
310
    
    // yields thread reference
311
    NewThread(OpIndex, Vec<OpIndex>), // stack, args
qinsoon's avatar
qinsoon committed
312
313
    
    // yields thread reference (thread resumes with exceptional value)
314
    NewThreadExn(OpIndex, OpIndex), // stack, exception
qinsoon's avatar
qinsoon committed
315
    
qinsoon's avatar
qinsoon committed
316
    // yields frame cursor
317
    NewFrameCursor(OpIndex), // stack
qinsoon's avatar
qinsoon committed
318
    
319
    // ref<T> -> iref<T>
320
    GetIRef(OpIndex),
qinsoon's avatar
qinsoon committed
321
    
322
    // iref|uptr<struct|hybrid<T>> int<M> -> iref|uptr<U>
qinsoon's avatar
qinsoon committed
323
    GetFieldIRef{
324
        is_ptr: bool,
325
326
        base: OpIndex, // iref or uptr
        index: OpIndex // constant
qinsoon's avatar
qinsoon committed
327
    },
qinsoon's avatar
qinsoon committed
328
    
329
    // iref|uptr<array<T N>> int<M> -> iref|uptr<T>
qinsoon's avatar
qinsoon committed
330
    GetElementIRef{
331
        is_ptr: bool,
332
333
        base: OpIndex,
        index: OpIndex // can be constant or ssa var
qinsoon's avatar
qinsoon committed
334
335
    },
    
336
    // iref|uptr<T> int<M> -> iref|uptr<T>
qinsoon's avatar
qinsoon committed
337
    ShiftIRef{
338
        is_ptr: bool,
339
340
        base: OpIndex,
        offset: OpIndex
qinsoon's avatar
qinsoon committed
341
342
    },
    
343
344
345
    // iref|uptr<hybrid<T U>> -> iref|uptr<U>
    GetVarPartIRef{
        is_ptr: bool,
346
        base: OpIndex
347
    },
qinsoon's avatar
qinsoon committed
348
349
350
351
352
353
354
355
    
//    PushFrame{
//        stack: P<Value>,
//        func: P<Value>
//    },
//    PopFrame{
//        stack: P<Value>
//    }
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

    Fence(MemoryOrder),
    
    // terminal instruction
    Return(Vec<OpIndex>),
    ThreadExit, // TODO:  common inst
    Throw(Vec<OpIndex>),
    TailCall(CallData),
    Branch1(Destination),
    Branch2{
        cond: OpIndex,
        true_dest: Destination,
        false_dest: Destination
    },
    Watchpoint{ // Watchpoint NONE ResumptionData
                //   serves as an unconditional trap. Trap to client, and resume with ResumptionData
                // Watchpoint (WPID dest) ResumptionData
                //   when disabled, jump to dest
                //   when enabled, trap to client and resume
        id: Option<WPID>,
        disable_dest: Option<Destination>,
        resume: ResumptionData
    }, 
    WPBranch{
        wp: WPID, 
        disable_dest: Destination,
        enable_dest: Destination
    },
    Call{
        data: CallData,
        resume: ResumptionData
    },
    SwapStack{
        stack: OpIndex,
        is_exception: bool,
        args: Vec<OpIndex>,
        resume: ResumptionData
    },
    Switch{
        cond: OpIndex,
        default: Destination,
        branches: Vec<(OpIndex, Destination)>
    },
    ExnInstruction{
        inner: P<Instruction>,
        resume: ResumptionData
    }
qinsoon's avatar
qinsoon committed
403
404
}

405
406
407
408
409
410
411
412
413
414
macro_rules! select {
    ($cond: expr, $res1 : expr, $res2 : expr) => {
        if $cond {
            $res1
        } else {
            $res2
        }
    }
}

qinsoon's avatar
qinsoon committed
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
impl Instruction_ {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        match self {
            &Instruction_::BinOp(op, op1, op2) => fmt::format(format_args!("{:?} {:?} {:?}", op, ops[op1], ops[op2])),
            &Instruction_::CmpOp(op, op1, op2) => fmt::format(format_args!("{:?} {:?} {:?}", op, ops[op1], ops[op2])),
            &Instruction_::ExprCall{ref data, is_abort} => {
                let abort = select!(is_abort, "ABORT_ON_EXN", "RETHROW");
                fmt::format(format_args!("CALL {} {}", data.debug_str(ops), abort))
            },
            &Instruction_::Load{is_ptr, mem_loc, order} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("LOAD {} {:?} {:?}", ptr, order, ops[mem_loc])) 
            },
            &Instruction_::Store{value, is_ptr, mem_loc, order} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("STORE {} {:?} {:?} {:?}", ptr, order, ops[mem_loc], ops[value]))
            },
            &Instruction_::CmpXchg{is_ptr, is_weak, success_order, fail_order, 
                mem_loc, expected_value, desired_value} => {
                let ptr = select!(is_ptr, "PTR", "");
                let weak = select!(is_weak, "WEAK", "");
                fmt::format(format_args!("CMPXCHG {} {} {:?} {:?} {:?} {:?} {:?}", 
                    ptr, weak, success_order, fail_order, ops[mem_loc], ops[expected_value], ops[desired_value]))  
            },
            &Instruction_::AtomicRMW{is_ptr, order, op, mem_loc, value} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("ATOMICRMW {} {:?} {:?} {:?} {:?}", ptr, order, op, ops[mem_loc], ops[value]))
            },
            &Instruction_::New(ref ty) => fmt::format(format_args!("NEW {:?}", ty)),
            &Instruction_::AllocA(ref ty) => fmt::format(format_args!("ALLOCA {:?}", ty)),
            &Instruction_::NewHybrid(ref ty, len) => fmt::format(format_args!("NEWHYBRID {:?} {:?}", ty, ops[len])),
            &Instruction_::AllocAHybrid(ref ty, len) => fmt::format(format_args!("ALLOCAHYBRID {:?} {:?}", ty, ops[len])),
            &Instruction_::NewStack(func) => fmt::format(format_args!("NEWSTACK {:?}", ops[func])),
            &Instruction_::NewThread(stack, ref args) => fmt::format(format_args!("NEWTHREAD {:?} PASS_VALUES {}", ops[stack], op_vector_str(args, ops))),
            &Instruction_::NewThreadExn(stack, exn) => fmt::format(format_args!("NEWTHREAD {:?} THROW_EXC {:?}", ops[stack], ops[exn])),
            &Instruction_::NewFrameCursor(stack) => fmt::format(format_args!("NEWFRAMECURSOR {:?}", ops[stack])),
            &Instruction_::GetIRef(reference) => fmt::format(format_args!("GETIREF {:?}", ops[reference])),
            &Instruction_::GetFieldIRef{is_ptr, base, index} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("GETFIELDIREF {} {:?} {:?}", ptr, ops[base], ops[index]))
            },
            &Instruction_::GetElementIRef{is_ptr, base, index} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("GETELEMENTIREF {} {:?} {:?}", ptr, ops[base], ops[index]))
            },
            &Instruction_::ShiftIRef{is_ptr, base, offset} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("SHIFTIREF {} {:?} {:?}", ptr, ops[base], ops[offset]))
            },
            &Instruction_::GetVarPartIRef{is_ptr, base} => {
                let ptr = select!(is_ptr, "PTR", "");
                fmt::format(format_args!("GETVARPARTIREF {} {:?}", ptr, ops[base]))
            },
            
            &Instruction_::Fence(order) => {
                fmt::format(format_args!("FENCE {:?}", order))
            },
            
            &Instruction_::Return(ref vals) => fmt::format(format_args!("RET {}", op_vector_str(vals, ops))),
            &Instruction_::ThreadExit => "THREADEXIT".to_string(),
            &Instruction_::Throw(ref vals) => fmt::format(format_args!("THROW {}", op_vector_str(vals, ops))),
            &Instruction_::TailCall(ref call) => fmt::format(format_args!("TAILCALL {}", call.debug_str(ops))),
            &Instruction_::Branch1(ref dest) => fmt::format(format_args!("BRANCH {:?}", dest.debug_str(ops))),
            &Instruction_::Branch2{cond, ref true_dest, ref false_dest} => {
                fmt::format(format_args!("BRANCH2 {:?} {} {}", ops[cond], true_dest.debug_str(ops), false_dest.debug_str(ops)))
            },
            &Instruction_::Watchpoint{id, ref disable_dest, ref resume} => {
                match id {
                    Some(id) => {
                        fmt::format(format_args!("WATCHPOINT {:?} {} {}", id, disable_dest.as_ref().unwrap().debug_str(ops), resume.debug_str(ops)))
                    },
                    None => {
                        fmt::format(format_args!("TRAP {}", resume.debug_str(ops)))
                    }
                }
            },
            &Instruction_::WPBranch{wp, ref disable_dest, ref enable_dest} => {
                fmt::format(format_args!("WPBRANCH {:?} {} {}", wp, disable_dest.debug_str(ops), enable_dest.debug_str(ops)))
            },
            &Instruction_::Call{ref data, ref resume} => fmt::format(format_args!("CALL {} {}", data.debug_str(ops), resume.debug_str(ops))),
            &Instruction_::SwapStack{stack, is_exception, ref args, ref resume} => {
                fmt::format(format_args!("SWAPSTACK {:?} {:?} {} {}", ops[stack], is_exception, op_vector_str(args, ops), resume.debug_str(ops)))
            },
            &Instruction_::Switch{cond, ref default, ref branches} => {
                let mut ret = fmt::format(format_args!("SWITCH {:?} {:?} {{", cond, default.debug_str(ops)));
                for i in 0..branches.len() {
                    let (op, ref dest) = branches[i];
                    ret.push_str(fmt::format(format_args!("{:?} {}", ops[op], dest.debug_str(ops))).as_str());
                    if i != branches.len() - 1 {
                        ret.push_str(", ");
                    }
                }
                ret.push_str("}}");
                
                ret
            },
            &Instruction_::ExnInstruction{ref inner, ref resume} => {
                fmt::format(format_args!("{:?} {:?}", inner.debug_str(ops), resume.debug_str(ops)))
            }
        }
    }    
}

518
impl fmt::Debug for Instruction_ {
519
520
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
521
522
523
            &Instruction_::BinOp(op, ref op1, ref op2) => write!(f, "{:?} {:?} {:?}", op, op1, op2),
            &Instruction_::CmpOp(op, ref op1, ref op2) => write!(f, "{:?} {:?} {:?}", op, op1, op2),
            &Instruction_::ExprCall{ref data, is_abort} => {
524
525
526
                let abort = select!(is_abort, "ABORT_ON_EXN", "RETHROW");
                write!(f, "CALL {:?} {}", data, abort)
            },
527
            &Instruction_::Load{is_ptr, ref mem_loc, order} => {
528
529
530
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "LOAD {} {:?} {:?}", ptr, order, mem_loc) 
            },
531
            &Instruction_::Store{ref value, is_ptr, ref mem_loc, order} => {
532
533
534
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "STORE {} {:?} {:?} {:?}", ptr, order, mem_loc, value)
            },
535
            &Instruction_::CmpXchg{is_ptr, is_weak, success_order, fail_order, 
536
537
538
539
540
541
                ref mem_loc, ref expected_value, ref desired_value} => {
                let ptr = select!(is_ptr, "PTR", "");
                let weak = select!(is_weak, "WEAK", "");
                write!(f, "CMPXCHG {} {} {:?} {:?} {:?} {:?} {:?}", 
                    ptr, weak, success_order, fail_order, mem_loc, expected_value, desired_value)  
            },
542
            &Instruction_::AtomicRMW{is_ptr, order, op, ref mem_loc, ref value} => {
543
544
545
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "ATOMICRMW {} {:?} {:?} {:?} {:?}", ptr, order, op, mem_loc, value)
            },
546
547
548
549
550
551
552
553
554
555
            &Instruction_::New(ref ty) => write!(f, "NEW {:?}", ty),
            &Instruction_::AllocA(ref ty) => write!(f, "ALLOCA {:?}", ty),
            &Instruction_::NewHybrid(ref ty, ref len) => write!(f, "NEWHYBRID {:?} {:?}", ty, len),
            &Instruction_::AllocAHybrid(ref ty, ref len) => write!(f, "ALLOCAHYBRID {:?} {:?}", ty, len),
            &Instruction_::NewStack(ref func) => write!(f, "NEWSTACK {:?}", func),
            &Instruction_::NewThread(ref stack, ref args) => write!(f, "NEWTHREAD {:?} PASS_VALUES {:?}", stack, args),
            &Instruction_::NewThreadExn(ref stack, ref exn) => write!(f, "NEWTHREAD {:?} THROW_EXC {:?}", stack, exn),
            &Instruction_::NewFrameCursor(ref stack) => write!(f, "NEWFRAMECURSOR {:?}", stack),
            &Instruction_::GetIRef(ref reference) => write!(f, "GETIREF {:?}", reference),
            &Instruction_::GetFieldIRef{is_ptr, ref base, ref index} => {
556
557
558
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "GETFIELDIREF {} {:?} {:?}", ptr, base, index)
            },
559
            &Instruction_::GetElementIRef{is_ptr, ref base, ref index} => {
560
561
562
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "GETELEMENTIREF {} {:?} {:?}", ptr, base, index)
            },
563
            &Instruction_::ShiftIRef{is_ptr, ref base, ref offset} => {
564
565
566
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "SHIFTIREF {} {:?} {:?}", ptr, base, offset)
            },
567
            &Instruction_::GetVarPartIRef{is_ptr, ref base} => {
568
569
                let ptr = select!(is_ptr, "PTR", "");
                write!(f, "GETVARPARTIREF {} {:?}", ptr, base)
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
            },
            
            &Instruction_::Fence(order) => {
                write!(f, "FENCE {:?}", order)
            }            
            
            &Instruction_::Return(ref vals) => write!(f, "RET {:?}", vals),
            &Instruction_::ThreadExit => write!(f, "THREADEXIT"),
            &Instruction_::Throw(ref vals) => write!(f, "THROW {:?}", vals),
            &Instruction_::TailCall(ref call) => write!(f, "TAILCALL {:?}", call),
            &Instruction_::Branch1(ref dest) => write!(f, "BRANCH {:?}", dest),
            &Instruction_::Branch2{ref cond, ref true_dest, ref false_dest} => {
                write!(f, "BRANCH2 {:?} {:?} {:?}", cond, true_dest, false_dest)
            },
            &Instruction_::Watchpoint{id, ref disable_dest, ref resume} => {
                match id {
                    Some(id) => {
                        write!(f, "WATCHPOINT {:?} {:?} {:?}", id, disable_dest.as_ref().unwrap(), resume)
                    },
                    None => {
                        write!(f, "TRAP {:?}", resume)
                    }
                }
            },
            &Instruction_::WPBranch{wp, ref disable_dest, ref enable_dest} => {
                write!(f, "WPBRANCH {:?} {:?} {:?}", wp, disable_dest, enable_dest)
            },
            &Instruction_::Call{ref data, ref resume} => write!(f, "CALL {:?} {:?}", data, resume),
            &Instruction_::SwapStack{ref stack, is_exception, ref args, ref resume} => {
                write!(f, "SWAPSTACK {:?} {:?} {:?} {:?}", stack, is_exception, args, resume)
            },
            &Instruction_::Switch{ref cond, ref default, ref branches} => {
                write!(f, "SWITCH {:?} {:?} {{{:?}}}", cond, default, branches)
            },
            &Instruction_::ExnInstruction{ref inner, ref resume} => {
                write!(f, "{:?} {:?}", inner, resume)
606
607
            }
        }
608
    }    
609
610
}

qinsoon's avatar
qinsoon committed
611
612
613
614
615
616
617
618
619
#[derive(Copy, Clone, Debug)]
pub enum MemoryOrder {
    NotAtomic,
    Relaxed,
    Consume,
    Acquire,
    Release,
    AcqRel,
    SeqCst
620
621
}

qinsoon's avatar
qinsoon committed
622
623
624
625
#[derive(Copy, Clone, Debug)]
pub enum CallConvention {
    Mu,
    Foreign(ForeignFFI)
qinsoon's avatar
qinsoon committed
626
627
}

qinsoon's avatar
qinsoon committed
628
629
630
#[derive(Copy, Clone, Debug)]
pub enum ForeignFFI {
    C
qinsoon's avatar
qinsoon committed
631
632
}

633
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
634
pub struct CallData {
635
636
    pub func: OpIndex,
    pub args: Vec<OpIndex>,
qinsoon's avatar
qinsoon committed
637
    pub convention: CallConvention
638
639
}

qinsoon's avatar
qinsoon committed
640
641
642
643
644
645
impl CallData {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        fmt::format(format_args!("{:?} {:?} ({})", self.convention, ops[self.func], op_vector_str(&self.args, ops)))
    }
}

646
647
648
649
650
651
652
impl fmt::Debug for CallData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} {:?} ({:?})", self.convention, self.func, self.args)
    }    
}

#[derive(Clone)]
qinsoon's avatar
qinsoon committed
653
654
655
pub struct ResumptionData {
    pub normal_dest: Destination,
    pub exn_dest: Destination
656
657
}

qinsoon's avatar
qinsoon committed
658
659
660
661
662
663
impl ResumptionData {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        fmt::format(format_args!("normal: {:?}, exception: {:?}", self.normal_dest.debug_str(ops), self.exn_dest.debug_str(ops)))
    }
}

664
665
666
667
impl fmt::Debug for ResumptionData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "normal: {:?}, exception: {:?}", self.normal_dest, self.exn_dest)
    }
668
669
}

670
#[derive(Clone)]
qinsoon's avatar
qinsoon committed
671
672
673
pub struct Destination {
    pub target: MuTag,
    pub args: Vec<DestArg>
674
675
}

qinsoon's avatar
qinsoon committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
impl Destination {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        let mut ret = fmt::format(format_args!("{}", self.target));
        ret.push('[');
        for i in 0..self.args.len() {
            let ref arg = self.args[i];
            ret.push_str(arg.debug_str(ops).as_str());
            if i != self.args.len() - 1 {
                ret.push_str(", ");
            }
        }
        ret.push(']');
        
        ret
    }
}

693
694
695
696
697
698
699
700
impl fmt::Debug for Destination {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{:?}", self.target, self.args)
    }
}

#[derive(Clone)]
pub enum DestArg {
701
    Normal(OpIndex),
702
703
704
    Freshbound(usize)
}

qinsoon's avatar
qinsoon committed
705
706
707
708
709
710
711
712
713
impl DestArg {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        match self {
            &DestArg::Normal(index) => fmt::format(format_args!("{:?}", ops[index])),
            &DestArg::Freshbound(n) => fmt::format(format_args!("${:?}", n)) 
        }
    }
}

714
715
716
717
718
719
720
impl fmt::Debug for DestArg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &DestArg::Normal(ref pv) => write!(f, "{:?}", pv),
            &DestArg::Freshbound(n) => write!(f, "${}", n)
        }
    }    
qinsoon's avatar
qinsoon committed
721
722
723
724
725
726
727
728
729
730
731
732
}

fn op_vector_str(vec: &Vec<OpIndex>, ops: &Vec<P<TreeNode>>) -> String {
    let mut ret = String::new();
    for i in 0..vec.len() {
        let index = vec[i];
        ret.push_str(fmt::format(format_args!("{:?}", ops[index])).as_str());
        if i != vec.len() - 1 {
            ret.push_str(", ");
        }
    }
    ret
733
}