inst.rs 43.4 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1
// Copyright 2017 The Australian National University
2
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
9 10 11 12 13 14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

qinsoon's avatar
qinsoon committed
15 16 17 18 19
use ir::*;
use ptr::*;
use types::*;
use op::*;

20
use utils::vec_utils;
21 22 23

use std::fmt;

24
/// Instruction represents a Mu instruction
25
#[derive(Debug)] // this implements Clone and Display
26
pub struct Instruction {
qinsoon's avatar
qinsoon committed
27
    pub hdr: MuEntityHeader,
28
    /// the values this instruction holds
qinsoon's avatar
qinsoon committed
29
    pub value: Option<Vec<P<Value>>>,
30 31 32
    /// ops field list all the children nodes,
    /// and in Instruction_, the children nodes are referred by indices
    /// This design makes it easy for the compiler to iterate through all the children
qinsoon's avatar
qinsoon committed
33
    pub ops: Vec<P<TreeNode>>,
34
    /// used for pattern matching
35
    pub v: Instruction_
36 37
}

38
// Instruction implements MuEntity
qinsoon's avatar
qinsoon committed
39 40
impl_mu_entity!(Instruction);

qinsoon's avatar
qinsoon committed
41 42 43
impl Clone for Instruction {
    fn clone(&self) -> Self {
        Instruction {
qinsoon's avatar
qinsoon committed
44
            hdr: self.hdr.clone(),
qinsoon's avatar
qinsoon committed
45
            value: self.value.clone(),
46
            ops: self.ops.clone(),
47
            v: self.v.clone()
qinsoon's avatar
qinsoon committed
48 49 50 51
        }
    }
}

52
impl Instruction {
53 54 55 56 57 58 59
    pub fn clone_with_id(&self, new_id: MuID) -> Instruction {
        let mut clone = self.clone();
        clone.hdr = self.hdr.clone_with_id(new_id);

        clone
    }

qinsoon's avatar
qinsoon committed
60 61
    /// is this instruction the terminal inst of its block?
    /// Terminal instructions end Mu blocks, and Mu block ends with a terminal instruction.
62 63 64 65
    pub fn is_terminal_inst(&self) -> bool {
        use inst::Instruction_::*;

        match self.v {
qinsoon's avatar
qinsoon committed
66 67 68 69 70 71 72 73 74 75
            Return(_) |
            ThreadExit |
            Throw(_) |
            TailCall(_) |
            Branch1(_) |
            Branch2 { .. } |
            Watchpoint { .. } |
            WPBranch { .. } |
            Call { .. } |
            CCall { .. } |
76 77
            SwapStackExc { .. } |
            SwapStackKill { .. } |
qinsoon's avatar
qinsoon committed
78
            Switch { .. } |
79
            ExnInstruction { .. } => true,
qinsoon's avatar
qinsoon committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
            BinOp(_, _, _) |
            BinOpWithStatus(_, _, _, _) |
            CmpOp(_, _, _) |
            ConvOp { .. } |
            ExprCall { .. } |
            ExprCCall { .. } |
            Load { .. } |
            Store { .. } |
            CmpXchg { .. } |
            AtomicRMW { .. } |
            New(_) |
            AllocA(_) |
            NewHybrid(_, _) |
            AllocAHybrid(_, _) |
            NewStack(_) |
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
95
            NewThread { .. } |
qinsoon's avatar
qinsoon committed
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
            NewFrameCursor(_) |
            GetIRef(_) |
            GetFieldIRef { .. } |
            GetElementIRef { .. } |
            ShiftIRef { .. } |
            GetVarPartIRef { .. } |
            Select { .. } |
            Fence(_) |
            CommonInst_GetThreadLocal |
            CommonInst_SetThreadLocal(_) |
            CommonInst_Pin(_) |
            CommonInst_Unpin(_) |
            CommonInst_GetAddr(_) |
            CommonInst_Tr64IsFp(_) |
            CommonInst_Tr64IsInt(_) |
            CommonInst_Tr64IsRef(_) |
            CommonInst_Tr64FromFp(_) |
            CommonInst_Tr64FromInt(_) |
            CommonInst_Tr64FromRef(_, _) |
            CommonInst_Tr64ToFp(_) |
            CommonInst_Tr64ToInt(_) |
            CommonInst_Tr64ToRef(_) |
            CommonInst_Tr64ToTag(_) |
            Move(_) |
            PrintHex(_) |
121 122 123 124
            SetRetval(_) |
            KillStack(_) |
            CurrentStack |
            SwapStackExpr { .. } => false
125 126 127
        }
    }

qinsoon's avatar
qinsoon committed
128
    /// is this instruction a non-terminal instruction of its block?
129 130 131 132
    pub fn is_non_terminal_inst(&self) -> bool {
        !self.is_terminal_inst()
    }

qinsoon's avatar
qinsoon committed
133 134 135
    /// does this instruction has side effect?
    /// An instruction has side effect if it affects something other than its result operands.
    /// e.g. affecting memory, stack, thread, etc.
136 137 138 139 140
    // FIXME: need to check correctness
    pub fn has_side_effect(&self) -> bool {
        use inst::Instruction_::*;

        match self.v {
141 142 143 144 145 146 147 148 149 150 151
            ExprCall { .. } |
            ExprCCall { .. } |
            Load { .. } |
            Store { .. } |
            CmpXchg { .. } |
            AtomicRMW { .. } |
            New(_) |
            AllocA(_) |
            NewHybrid(_, _) |
            AllocAHybrid(_, _) |
            NewStack(_) |
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
152
            NewThread { .. } |
153 154 155 156
            NewFrameCursor(_) |
            Fence(_) |
            Return(_) |
            ThreadExit |
157
            Throw(_) |
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
            TailCall(_) |
            Branch1(_) |
            Branch2 { .. } |
            Watchpoint { .. } |
            WPBranch { .. } |
            Call { .. } |
            CCall { .. } |
            SwapStackExpr { .. } |
            SwapStackExc { .. } |
            SwapStackKill { .. } |
            Switch { .. } |
            ExnInstruction { .. } |
            CommonInst_GetThreadLocal |
            CommonInst_SetThreadLocal(_) |
            CommonInst_Pin(_) |
            CommonInst_Unpin(_) |
            CommonInst_GetAddr(_) |
            PrintHex(_) |
            SetRetval(_) |
177
            KillStack(_) => true,
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            BinOp(_, _, _) |
            BinOpWithStatus(_, _, _, _) |
            CmpOp(_, _, _) |
            ConvOp { .. } |
            GetIRef(_) |
            GetFieldIRef { .. } |
            GetElementIRef { .. } |
            ShiftIRef { .. } |
            GetVarPartIRef { .. } |
            Select { .. } |
            CommonInst_Tr64IsFp(_) |
            CommonInst_Tr64IsInt(_) |
            CommonInst_Tr64IsRef(_) |
            CommonInst_Tr64FromFp(_) |
            CommonInst_Tr64FromInt(_) |
            CommonInst_Tr64FromRef(_, _) |
qinsoon's avatar
qinsoon committed
194 195 196
            CommonInst_Tr64ToFp(_) |
            CommonInst_Tr64ToInt(_) |
            CommonInst_Tr64ToRef(_) |
197
            CommonInst_Tr64ToTag(_) |
198 199
            Move(_) |
            CurrentStack => false
200 201 202
        }
    }

qinsoon's avatar
qinsoon committed
203 204
    /// can this instruction throw exception?
    /// an instruction with an exceptional branch can throw exception
205 206 207 208
    pub fn is_potentially_excepting_instruction(&self) -> bool {
        use inst::Instruction_::*;

        match self.v {
qinsoon's avatar
qinsoon committed
209 210 211
            Watchpoint { .. } |
            Call { .. } |
            CCall { .. } |
212
            SwapStackExc { .. } |
qinsoon's avatar
qinsoon committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
            ExnInstruction { .. } => true,
            BinOp(_, _, _) |
            BinOpWithStatus(_, _, _, _) |
            CmpOp(_, _, _) |
            ConvOp { .. } |
            ExprCall { .. } |
            ExprCCall { .. } |
            Load { .. } |
            Store { .. } |
            CmpXchg { .. } |
            AtomicRMW { .. } |
            New(_) |
            AllocA(_) |
            NewHybrid(_, _) |
            AllocAHybrid(_, _) |
            NewStack(_) |
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
229
            NewThread { .. } |
qinsoon's avatar
qinsoon committed
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
            NewFrameCursor(_) |
            GetIRef(_) |
            GetFieldIRef { .. } |
            GetElementIRef { .. } |
            ShiftIRef { .. } |
            GetVarPartIRef { .. } |
            Fence(_) |
            Return(_) |
            ThreadExit |
            Throw(_) |
            TailCall(_) |
            Branch1(_) |
            Branch2 { .. } |
            Select { .. } |
            WPBranch { .. } |
            Switch { .. } |
            CommonInst_GetThreadLocal |
            CommonInst_SetThreadLocal(_) |
            CommonInst_Pin(_) |
            CommonInst_Unpin(_) |
            CommonInst_GetAddr(_) |
            CommonInst_Tr64IsFp(_) |
            CommonInst_Tr64IsInt(_) |
            CommonInst_Tr64IsRef(_) |
            CommonInst_Tr64FromFp(_) |
            CommonInst_Tr64FromInt(_) |
            CommonInst_Tr64FromRef(_, _) |
            CommonInst_Tr64ToFp(_) |
            CommonInst_Tr64ToInt(_) |
            CommonInst_Tr64ToRef(_) |
            CommonInst_Tr64ToTag(_) |
            Move(_) |
            PrintHex(_) |
263 264 265 266 267
            SetRetval(_) |
            KillStack(_) |
            CurrentStack |
            SwapStackExpr { .. } |
            SwapStackKill { .. } => false
268 269 270
        }
    }

qinsoon's avatar
qinsoon committed
271
    /// does this instruction have an exceptional clause/branch?
272
    pub fn has_exception_clause(&self) -> bool {
273
        self.is_potentially_excepting_instruction()
274 275
    }

qinsoon's avatar
qinsoon committed
276 277
    /// returns exception target(block ID),
    /// returns None if this instruction does not have exceptional branch
278 279 280
    pub fn get_exception_target(&self) -> Option<MuID> {
        use inst::Instruction_::*;
        match self.v {
qinsoon's avatar
qinsoon committed
281 282 283
            Watchpoint { ref resume, .. } |
            Call { ref resume, .. } |
            CCall { ref resume, .. } |
284
            SwapStackExc { ref resume, .. } |
285
            ExnInstruction { ref resume, .. } => Some(resume.exn_dest.target.id()),
qinsoon's avatar
qinsoon committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
            BinOp(_, _, _) |
            BinOpWithStatus(_, _, _, _) |
            CmpOp(_, _, _) |
            ConvOp { .. } |
            ExprCall { .. } |
            ExprCCall { .. } |
            Load { .. } |
            Store { .. } |
            CmpXchg { .. } |
            AtomicRMW { .. } |
            New(_) |
            AllocA(_) |
            NewHybrid(_, _) |
            AllocAHybrid(_, _) |
            NewStack(_) |
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
301
            NewThread { .. } |
qinsoon's avatar
qinsoon committed
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
            NewFrameCursor(_) |
            GetIRef(_) |
            GetFieldIRef { .. } |
            GetElementIRef { .. } |
            ShiftIRef { .. } |
            GetVarPartIRef { .. } |
            Fence(_) |
            Return(_) |
            ThreadExit |
            Throw(_) |
            TailCall(_) |
            Branch1(_) |
            Branch2 { .. } |
            Select { .. } |
            WPBranch { .. } |
            Switch { .. } |
            CommonInst_GetThreadLocal |
            CommonInst_SetThreadLocal(_) |
            CommonInst_Pin(_) |
            CommonInst_Unpin(_) |
            CommonInst_GetAddr(_) |
            CommonInst_Tr64IsFp(_) |
            CommonInst_Tr64IsInt(_) |
            CommonInst_Tr64IsRef(_) |
            CommonInst_Tr64FromFp(_) |
            CommonInst_Tr64FromInt(_) |
            CommonInst_Tr64FromRef(_, _) |
            CommonInst_Tr64ToFp(_) |
            CommonInst_Tr64ToInt(_) |
            CommonInst_Tr64ToRef(_) |
            CommonInst_Tr64ToTag(_) |
            Move(_) |
            PrintHex(_) |
335 336 337 338 339
            SetRetval(_) |
            KillStack(_) |
            CurrentStack |
            SwapStackExpr { .. } |
            SwapStackKill { .. } => None
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
    /// can this instruction throw exception?
    /// (whether or not it containjs a ctach for it)
    pub fn is_potentially_throwing(&self) -> bool {
        use inst::Instruction_::*;

        match self.v {
            // Note: commented out ones are ones where we haven't implemented exceptions yet
            Watchpoint { .. } |
            Call { .. } |
            CCall { .. } |
            SwapStackExc { .. } |
            SwapStackExpr { .. } |
            ExnInstruction { .. } |
            ExprCall { .. } |
            ExprCCall { .. } |
            //Load { .. } |
            //Store { .. } |
            //CmpXchg { .. } |
            //AtomicRMW { .. } |
            //New(_) |
            //NewHybrid(_, _) |
            Throw(_)  => true,

            // BinOp(op, _, _) |
            // BinOpWithStatus(op, _, _, _) if op.may_throw() => true,
            BinOp(_, _, _) |
            BinOpWithStatus(_, _, _, _) |
            CmpOp(_, _, _) |
            ConvOp { .. } |
            AllocA(_) |
            AllocAHybrid(_, _) |
            NewStack(_) |
            NewThread { .. } |
            NewFrameCursor(_) |
            GetIRef(_) |
            GetFieldIRef { .. } |
            GetElementIRef { .. } |
            ShiftIRef { .. } |
            GetVarPartIRef { .. } |
            Fence(_) |
            Return(_) |
            ThreadExit |
            TailCall(_) |
            Branch1(_) |
            Branch2 { .. } |
            Select { .. } |
            WPBranch { .. } |
            Switch { .. } |
            CommonInst_GetThreadLocal |
            CommonInst_SetThreadLocal(_) |
            CommonInst_Pin(_) |
            CommonInst_Unpin(_) |
            CommonInst_GetAddr(_) |
            CommonInst_Tr64IsFp(_) |
            CommonInst_Tr64IsInt(_) |
            CommonInst_Tr64IsRef(_) |
            CommonInst_Tr64FromFp(_) |
            CommonInst_Tr64FromInt(_) |
            CommonInst_Tr64FromRef(_, _) |
            CommonInst_Tr64ToFp(_) |
            CommonInst_Tr64ToInt(_) |
            CommonInst_Tr64ToRef(_) |
            CommonInst_Tr64ToTag(_) |
            Move(_) |
            PrintHex(_) |
            SetRetval(_) |
            KillStack(_) |
            CurrentStack |
            SwapStackKill { .. } => false,

            _ => false
        }
    }

417
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 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
        match &self.v {
            &Instruction_::BinOp(op, op1, op2) => {
                format!("{}<{}> {} {}", op, ops[op1].ty(), ops[op1], ops[op2])
            }
            &Instruction_::BinOpWithStatus(op, status, op1, op2) => {
                format!(
                    "{}{}<{}> {} {}",
                    op,
                    status,
                    ops[op1].ty(),
                    ops[op1],
                    ops[op2]
                )
            }
            &Instruction_::CmpOp(op, op1, op2) => {
                format!("{}<{}> {} {}", op, ops[op1].ty(), ops[op1], ops[op2])
            }
            &Instruction_::ConvOp {
                operation,
                ref from_ty,
                ref to_ty,
                operand
            } => format!("{} <{} {}> {}", operation, from_ty, to_ty, ops[operand]),
            &Instruction_::ExprCall { ref data, is_abort } => {
                if is_abort {
                    panic!("ABORT is not supported");
                }
                format!("CALL{}", data.debug_str(ops))
            }
            &Instruction_::ExprCCall { ref data, is_abort } => {
                if is_abort {
                    panic!("ABORT is not supported");
                }
                format!("CCALL{}", data.debug_str(ops))
            }
            &Instruction_::Load {
                is_ptr,
                mem_loc,
                order
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
                    "LOAD{} {}<{}> {}",
                    ptr,
                    order,
                    ops[mem_loc].ty().get_referent_ty().unwrap(),
                    ops[mem_loc]
                )
            }
            &Instruction_::Store {
                value,
                is_ptr,
                mem_loc,
                order
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
                    "STORE{} {}<{}> {} {}",
                    ptr,
                    order,
                    ops[mem_loc].ty().get_referent_ty().unwrap(),
                    ops[mem_loc],
                    ops[value]
                )
            }
            &Instruction_::CmpXchg {
                is_ptr,
                is_weak,
                success_order,
                fail_order,
                mem_loc,
                expected_value,
                desired_value
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                let weak = select_value!(is_weak, " WEAK", "");
                format!(
                    "CMPXCHG{}{} {} {}<{}> {} {} {}",
                    ptr,
                    weak,
                    success_order,
                    fail_order,
                    ops[mem_loc].ty().get_referent_ty().unwrap(),
                    ops[mem_loc],
                    ops[expected_value],
                    ops[desired_value]
                )
            }
            &Instruction_::AtomicRMW {
                is_ptr,
                order,
                op,
                mem_loc,
                value
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
                    "ATOMICRMW{} {} {}<{}> {} {}",
                    ptr,
                    order,
                    op,
                    ops[mem_loc].ty().get_referent_ty().unwrap(),
                    ops[mem_loc],
                    ops[value]
                )
            }
            &Instruction_::New(ref ty) => format!("NEW<{}>", ty),
            &Instruction_::AllocA(ref ty) => format!("ALLOCA<{}>", ty),
            &Instruction_::NewHybrid(ref ty, len) => {
                format!("NEWHYBRID<{} {}> {}", ty, ops[len].ty(), ops[len])
            }
            &Instruction_::AllocAHybrid(ref ty, len) => {
                format!("ALLOCAHYBRID<{} {}> {}", ty, ops[len].ty(), ops[len])
            }
            &Instruction_::NewStack(func) => {
                format!(
                    "COMMINST @uvm.new_stack<[{}]>({})",
                    ops[func].ty().get_sig().unwrap(),
                    ops[func]
                )
            }
            &Instruction_::NewThread {
                stack,
                thread_local,
                is_exception,
                ref args
            } => {
                let new_stack_clause = format_new_stack_clause(is_exception, args, ops);
                let thread_local = thread_local
                    .map(|t| format!(" THREADLOCAL({})", ops[t]))
                    .unwrap_or("".to_string());
                format!(
                    "NEWSTACK {}{} {}",
                    ops[stack],
                    thread_local,
                    new_stack_clause,
                )
            }
            &Instruction_::NewFrameCursor(stack) => {
                format!("COMMINST @uvm.meta.new_cursor({})", ops[stack])
            }
            &Instruction_::GetIRef(reference) => {
                format!(
                    "GETIREF<{}> {}",
                    ops[reference].ty().get_referent_ty().unwrap(),
                    ops[reference]
                )
            }
            &Instruction_::GetFieldIRef {
                is_ptr,
                base,
                index
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
                    "GETFIELDIREF{}<{} {}> {}",
                    ptr,
                    ops[base].ty().get_referent_ty().unwrap(),
                    index,
                    ops[base]
                )
            }
            &Instruction_::GetElementIRef {
                is_ptr,
                base,
                index
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
                    "GETELEMIREF{}<{} {}>{} {}",
                    ptr,
                    ops[base].ty().get_referent_ty().unwrap(),
                    ops[index].ty(),
                    ops[base],
                    ops[index]
                )
            }
            &Instruction_::ShiftIRef {
                is_ptr,
                base,
                offset
            } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
602
                    "SHIFTIREF{}<{} {}>{} {}",
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
                    ptr,
                    ops[base].ty().get_referent_ty().unwrap(),
                    ops[offset].ty(),
                    ops[base],
                    ops[offset]
                )
            }
            &Instruction_::GetVarPartIRef { is_ptr, base } => {
                let ptr = select_value!(is_ptr, " PTR", "");
                format!(
                    "GETVARPARTIREF{}<{}> {}",
                    ptr,
                    ops[base].ty().get_referent_ty().unwrap(),
                    ops[base]
                )
            }

            &Instruction_::Fence(order) => format!("FENCE {}", order),

            &Instruction_::Return(ref vals) => {
                if vals.len() == 0 {
                    format!("RET")
                } else if vals.len() == 1 {
                    format!("RET {}", ops[vals[0]])
                } else {
                    format!("RET ({})", op_vector_str(vals, ops))
                }
            }
            &Instruction_::ThreadExit => "COMMINST @uvm.thread_exit".to_string(),
            &Instruction_::CurrentStack => "COMMINST @uvm.current_stack".to_string(),
            &Instruction_::KillStack(s) => format!("COMMINST @uvm.kill_stack({})", ops[s]),
            &Instruction_::Throw(exn_obj) => format!("THROW {}", ops[exn_obj]),
            &Instruction_::TailCall(ref call) => format!("TAILCALL{}", call.debug_str(ops)),
            &Instruction_::Branch1(ref dest) => format!("BRANCH {}", dest.debug_str(ops)),
            &Instruction_::Branch2 {
                cond,
                ref true_dest,
                ref false_dest,
                ..
            } => {
                format!(
                    "BRANCH2 {} {} {}",
                    ops[cond],
                    true_dest.debug_str(ops),
                    false_dest.debug_str(ops)
                )
            }
            &Instruction_::Select {
                cond,
                true_val,
                false_val
            } => {
                format!(
                    "SELECT<{} {}> {} {} {}",
                    ops[cond].ty(),
                    ops[true_val].ty(),
                    ops[cond],
                    ops[true_val],
                    ops[false_val]
                )
            }
            &Instruction_::Watchpoint {
                id,
                ref disable_dest,
                ref resume
            } => {
                match id {
                    Some(id) => {
                        format!(
                            // TODO: WPEXC should be optional
                            "WATCHPOINT {}<{}> {} {} WPEXC({})",
                            id,
                            format_value_types(&self.value),
                            disable_dest.as_ref().unwrap().debug_str(ops),
                            resume.normal_dest.debug_str(ops),
                            resume.exn_dest.debug_str(ops)
                        )
                    }
                    //TRAP < Ts > excClause keepAliveClause
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
682 683 684 685 686 687 688
                    None => {
                        format!(
                            "TRAP<{}> {}",
                            format_value_types(&self.value),
                            resume.debug_str(ops)
                        )
                    }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
                }
            }
            &Instruction_::WPBranch {
                wp,
                ref disable_dest,
                ref enable_dest
            } => {
                format!(
                    "WPBRANCH {} {} {}",
                    wp,
                    disable_dest.debug_str(ops),
                    enable_dest.debug_str(ops)
                )
            }
            &Instruction_::Call {
                ref data,
                ref resume
            } => format!("CALL{} {}", data.debug_str(ops), resume.debug_str(ops)),
            &Instruction_::CCall {
                ref data,
                ref resume
            } => format!("CCALL{} {}", data.debug_str(ops), resume.debug_str(ops)),
            &Instruction_::SwapStackExpr {
                stack,
                is_exception,
                ref args
            } => {
                format!(
                    "SWAPSTACK {} RET_WITH<{}> {}",
                    ops[stack],
                    format_value_types(&self.value),
                    format_new_stack_clause(is_exception, args, ops)
                )
            }
            &Instruction_::SwapStackExc {
                stack,
                is_exception,
                ref args,
                ref resume
            } => {
                format!(
                    "SWAPSTACK {} RET_WITH<{}> {} {}",
                    ops[stack],
                    format_value_types(&self.value),
                    format_new_stack_clause(is_exception, args, ops),
                    resume.debug_str(ops)
                )
            }

            &Instruction_::SwapStackKill {
                stack,
                is_exception,
                ref args
            } => {
                format!(
                    "SWAPSTACK {} KILL_OLD {}",
                    ops[stack],
                    format_new_stack_clause(is_exception, args, ops)
                )
            }

            &Instruction_::Switch {
                cond,
                ref default,
                ref branches
            } => {
                //SWITCH < T > opnd default { ( value dest ) rep }
                let mut ret = format!(
                    "SWITCH<{}> {} {} {{",
                    ops[cond].ty(),
                    ops[cond],
                    default.debug_str(ops)
                );
                for i in 0..branches.len() {
                    let (op, ref dest) = branches[i];
                    ret.push_str(format!("{} {}", ops[op], dest.debug_str(ops)).as_str());
                    if i != branches.len() - 1 {
                        ret.push_str(" ");
                    }
                }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
769
                ret.push_str("}");
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

                ret
            }
            &Instruction_::ExnInstruction {
                ref inner,
                ref resume
            } => format!("{} {}", inner.debug_str(ops), resume.debug_str(ops)),

            // common inst
            &Instruction_::CommonInst_GetThreadLocal => format!("COMMINST @uvm.get_threadlocal"),
            &Instruction_::CommonInst_SetThreadLocal(op) => {
                format!("COMMINST @uvm.set_threadlocal({})", ops[op])
            }

            &Instruction_::CommonInst_Pin(op) => {
                format!("COMMINST @uvm.native.pin<{}>({})", ops[op].ty(), ops[op])
            }
            &Instruction_::CommonInst_Unpin(op) => {
                format!("COMMINST @uvm.native.unpin<{}>({})", ops[op].ty(), ops[op])
            }
            &Instruction_::CommonInst_GetAddr(op) => {
                format!(
                    "COMMINST @uvm.native.get_addr<{}>({})",
                    ops[op].ty(),
                    ops[op]
                )
            }
            // Tagerf64
            &Instruction_::CommonInst_Tr64IsFp(op) => {
                format!("COMMINST @uvm.tr64.is_fp({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64IsInt(op) => {
                format!("COMMINST @uvm.tr64.is_int({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64IsRef(op) => {
                format!("COMMINST @uvm.tr64.is_ref({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64FromFp(op) => {
                format!("COMMINST @uvm.tr64.from_fp({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64FromInt(op) => {
                format!("COMMINST @uvm.tr64.from_int({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64FromRef(op1, op2) => {
                format!("COMMINST @uvm.tr64.from_ref({} {})", ops[op1], ops[op2])
            }
            &Instruction_::CommonInst_Tr64ToFp(op) => {
                format!("COMMINST @uvm.tr64.to_fp({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64ToInt(op) => {
                format!("COMMINST @uvm.tr64.to_int({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64ToRef(op) => {
                format!("COMMINST @uvm.tr64.to_ref({})", ops[op])
            }
            &Instruction_::CommonInst_Tr64ToTag(op) => {
                format!("COMMINST @uvm.tr64.to_tag({})", ops[op])
            }

            // move
            &Instruction_::Move(from) => format!("MOVE<{}> {}", ops[from].ty(), ops[from]),
            // print hex
            &Instruction_::PrintHex(i) => format!("PRINTHEX<{}> {}", ops[i].ty(), ops[i]),
            // set retval
            &Instruction_::SetRetval(val) => format!("SETRETVAL {}", ops[val])
        }
836 837 838
    }
}

839 840
const PRINT_INST_NAME: bool = false;

841 842
impl fmt::Display for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
843
        let ref ops = self.ops;
844
        let value = match &self.value {
845 846 847 848 849 850 851
            &Some(ref v) if v.len() == 0 => format!(""),
            &Some(ref v) if v.len() == 1 => format!("{} = ", v[0]),
            &Some(ref v) => format!("({}) = ", vec_utils::as_str_sp(&v)),
            &None => format!("")
        };

        if PRINT_INST_NAME {
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
852
            write!(f, "{}[{}]{}", value, self.hdr, self.debug_str(ops))
853
        } else {
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
854
            write!(f, "{}{}", value, self.debug_str(ops))
855 856 857 858
        }
    }
}

qinsoon's avatar
qinsoon committed
859
/// Instruction_ is used for pattern matching for Instruction
qinsoon's avatar
qinsoon committed
860
#[allow(non_camel_case_types)]
861
#[derive(Debug, Clone)]
862 863
pub enum Instruction_ {
    // non-terminal instruction
qinsoon's avatar
qinsoon committed
864
    /// binary operations
865
    BinOp(BinOp, OpIndex, OpIndex),
qinsoon's avatar
qinsoon committed
866
    /// binary operations with status flag (overflow, sign, etc. )
qinsoon's avatar
qinsoon committed
867 868
    BinOpWithStatus(BinOp, BinOpStatus, OpIndex, OpIndex),

qinsoon's avatar
qinsoon committed
869
    /// comparison operations
870
    CmpOp(CmpOp, OpIndex, OpIndex),
qinsoon's avatar
qinsoon committed
871 872

    /// conversion operations (casting)
qinsoon's avatar
qinsoon committed
873
    ConvOp {
874 875 876
        operation: ConvOp,
        from_ty: P<MuType>,
        to_ty: P<MuType>,
877
        operand: OpIndex
878
    },
879

qinsoon's avatar
qinsoon committed
880
    /// a non-terminating Call instruction (the call does not have an exceptional branch)
qinsoon's avatar
qinsoon committed
881
    /// This instruction is not in the Mu spec, but is documented in the HOL formal spec
qinsoon's avatar
qinsoon committed
882
    ExprCall {
883
        data: CallData,
884
        is_abort: bool // T to abort, F to rethrow
885
    },
886

qinsoon's avatar
qinsoon committed
887
    /// a non-terminating CCall instruction (the call does not have an exceptional branch)
qinsoon's avatar
qinsoon committed
888
    /// This instruction is not in the Mu spec, but is documented in the HOL formal spec
qinsoon's avatar
qinsoon committed
889
    ExprCCall { data: CallData, is_abort: bool },
qinsoon's avatar
qinsoon committed
890

qinsoon's avatar
qinsoon committed
891
    /// load instruction
qinsoon's avatar
qinsoon committed
892
    Load {
893 894
        is_ptr: bool,
        order: MemoryOrder,
895
        mem_loc: OpIndex
896
    },
897

qinsoon's avatar
qinsoon committed
898
    /// store instruction
qinsoon's avatar
qinsoon committed
899
    Store {
900
        is_ptr: bool,
901
        order: MemoryOrder,
902
        mem_loc: OpIndex,
903
        value: OpIndex
904
    },
905

qinsoon's avatar
qinsoon committed
906
    /// compare and exchange, yields a pair value (oldvalue, boolean (T = success, F = failure))
qinsoon's avatar
qinsoon committed
907
    CmpXchg {
908 909 910 911 912 913
        is_ptr: bool,
        is_weak: bool,
        success_order: MemoryOrder,
        fail_order: MemoryOrder,
        mem_loc: OpIndex,
        expected_value: OpIndex,
914
        desired_value: OpIndex
915
    },
916

qinsoon's avatar
qinsoon committed
917
    /// atomic read-modify-write, yields old memory value
qinsoon's avatar
qinsoon committed
918
    AtomicRMW {
919 920 921 922
        is_ptr: bool, // T for iref, F for ptr
        order: MemoryOrder,
        op: AtomicRMWOp,
        mem_loc: OpIndex,
923
        value: OpIndex // operand for op
924
    },
925

qinsoon's avatar
qinsoon committed
926
    /// allocate an object (non hybrid type) in the heap, yields a reference of the type
927
    New(P<MuType>),
928

qinsoon's avatar
qinsoon committed
929
    /// allocate an object (non hybrid type) on the stack, yields an iref of the type
930
    AllocA(P<MuType>),
931

qinsoon's avatar
qinsoon committed
932 933
    /// allocate a hybrid type object in the heap, yields ref
    /// args: the type of the hybrid, hybrid part length
934
    NewHybrid(P<MuType>, OpIndex),
935

qinsoon's avatar
qinsoon committed
936 937
    /// allocate a hybrid type object on the stack, yields iref
    /// args: the type of the hybrid, hybrid part length
938
    AllocAHybrid(P<MuType>, OpIndex),
939

qinsoon's avatar
qinsoon committed
940 941 942
    /// create a new Mu stack, yields stack ref
    /// args: functionref of the entry function
    NewStack(OpIndex),
943

944
    /// kill the given Mu stack
945 946
    KillStack(OpIndex),

947
    /// return stackref for the current stack
948 949
    CurrentStack,

qinsoon's avatar
qinsoon committed
950 951
    /// create a new Mu thread, yields thread reference
    /// args: stackref of a Mu stack, a list of arguments
952 953 954 955 956 957
    NewThread {
        stack: OpIndex,
        thread_local: Option<OpIndex>,
        is_exception: bool,
        args: Vec<OpIndex>
    },
958

qinsoon's avatar
qinsoon committed
959 960
    /// create a frame cursor reference
    /// args: stackref of a Mu stack
961
    NewFrameCursor(OpIndex), // stack
962

qinsoon's avatar
qinsoon committed
963 964
    /// get internal reference of a reference
    /// args: a reference
965
    GetIRef(OpIndex),
966

qinsoon's avatar
qinsoon committed
967
    /// get internal reference of an iref (or uptr) to a struct/hybrid fix part
qinsoon's avatar
qinsoon committed
968
    GetFieldIRef {
969 970
        is_ptr: bool,
        base: OpIndex, // iref or uptr
971
        index: usize   // constant
972
    },
973

qinsoon's avatar
qinsoon committed
974
    /// get internal reference of an element of an iref (or uptr) to an array
qinsoon's avatar
qinsoon committed
975
    GetElementIRef {
976 977
        is_ptr: bool,
        base: OpIndex,
978
        index: OpIndex // can be constant or ssa var
979
    },
980

qinsoon's avatar
qinsoon committed
981
    /// offset an iref (or uptr) (offset is an index)
qinsoon's avatar
qinsoon committed
982
    ShiftIRef {
983 984
        is_ptr: bool,
        base: OpIndex,
985
        offset: OpIndex
986
    },
987

qinsoon's avatar
qinsoon committed
988
    /// get internal reference to an element in hybrid var part
qinsoon's avatar
qinsoon committed
989
    GetVarPartIRef { is_ptr: bool, base: OpIndex },
990

qinsoon's avatar
qinsoon committed
991
    /// a fence of certain memory order
992
    Fence(MemoryOrder),
993

994
    // terminal instruction
qinsoon's avatar
qinsoon committed
995 996
    /// return instruction
    /// args: a list of return values
997
    Return(Vec<OpIndex>),
qinsoon's avatar
qinsoon committed
998 999 1000 1001 1002

    /// thread exit
    ThreadExit,

    /// throw an exception
1003
    Throw(OpIndex),
qinsoon's avatar
qinsoon committed
1004 1005

    /// tail call a function (reuse current frame)
1006
    TailCall(CallData),
qinsoon's avatar
qinsoon committed
1007 1008

    /// unconditional branch
1009
    Branch1(Destination),
qinsoon's avatar
qinsoon committed
1010 1011

    /// conditional branch
qinsoon's avatar
qinsoon committed
1012
    Branch2 {
1013 1014 1015
        cond: OpIndex,
        true_dest: Destination,
        false_dest: Destination,
1016
        true_prob: f32
1017
    },
qinsoon's avatar
qinsoon committed
1018 1019

    /// returns value1 if condition is true, otherwise returns value2
qinsoon's avatar
qinsoon committed
1020
    Select {
qinsoon's avatar
qinsoon committed
1021 1022
        cond: OpIndex,
        true_val: OpIndex,
1023
        false_val: OpIndex
qinsoon's avatar
qinsoon committed
1024
    },
qinsoon's avatar
qinsoon committed
1025 1026

    /// a watchpoint
qinsoon's avatar
qinsoon committed
1027 1028
    /// * Watchpoint NONE ResumptionData: serves as an unconditional trap.
    ///   Trap to client, and resume with ResumptionData
qinsoon's avatar
qinsoon committed
1029 1030 1031
    /// * Watchpoint (WPID dest) ResumptionData:
    ///   * when disabled, jump to dest
    ///   * when enabled, trap to client and resume
qinsoon's avatar
qinsoon committed
1032
    Watchpoint {
1033 1034
        id: Option<WPID>,
        disable_dest: Option<Destination>,
1035
        resume: ResumptionData
1036
    },
qinsoon's avatar
qinsoon committed
1037 1038

    /// a watchpoint branch, branch to different destinations based on enabled/disabled
qinsoon's avatar
qinsoon committed
1039
    WPBranch {
1040
        wp: WPID,
1041
        disable_dest: Destination,
1042
        enable_dest: Destination
1043
    },
qinsoon's avatar
qinsoon committed
1044 1045

    /// a call instruction that may throw an exception
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1046 1047
    Call {
        data: CallData,
1048
        resume: ResumptionData
1049 1050
    },

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1051 1052 1053 1054 1055
    /// a ccall instruction that may throw an exception
    CCall {
        data: CallData,
        resume: ResumptionData
    },
1056

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1057 1058 1059 1060 1061 1062 1063
    /// A swap stack with an exception clause (i.e. uses the RET_WITH form)
    SwapStackExc {
        stack: OpIndex,
        is_exception: bool,
        args: Vec<OpIndex>,
        resume: ResumptionData
    },
1064

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1065 1066 1067 1068 1069 1070 1071
    /// A swap stack without an exception clause that is not a terminator
    /// (i.e. uses the RET_WITH form)
    SwapStackExpr {
        stack: OpIndex,
        is_exception: bool,
        args: Vec<OpIndex>
    },
1072

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1073 1074 1075 1076 1077 1078
    /// A swapstack without an exception clause that is a terminator (i.e. one with KILL_OLD)
    SwapStackKill {
        stack: OpIndex,
        is_exception: bool,
        args: Vec<OpIndex>
    },
1079

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1080 1081 1082 1083 1084 1085
    /// a multiway branch
    Switch {
        cond: OpIndex,
        default: Destination,
        branches: Vec<(OpIndex, Destination)>
    },
1086

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1087 1088 1089 1090 1091 1092
    /// a wrapper for any instruction that may throw an exception
    //  This is not used at the moment
    ExnInstruction {
        inner: Box<Instruction>,
        resume: ResumptionData
    },
1093

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1094 1095 1096 1097
    /// common inst: get thread local
    CommonInst_GetThreadLocal,
    /// common inst: set thread local
    CommonInst_SetThreadLocal(OpIndex),
1098

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1099 1100 1101 1102 1103 1104
    /// common inst: pin an object (prevent it being moved and reclaimed by GC), yields a uptr
    CommonInst_Pin(OpIndex),
    /// common inst: unpin an object (the object is automatically managed by GC)
    CommonInst_Unpin(OpIndex),
    /// common inst: get address of a global cell or a pinned object
    CommonInst_GetAddr(OpIndex),
1105

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    /// common inst: is the tagref a floating point?
    CommonInst_Tr64IsFp(OpIndex),
    /// common inst: is the tagref an int?
    CommonInst_Tr64IsInt(OpIndex),
    /// common inst: is the tagref a ref?
    CommonInst_Tr64IsRef(OpIndex),
    /// common inst: creates a tagref from floating point (double)
    CommonInst_Tr64FromFp(OpIndex),
    /// common inst: creates a tagref from int<52>
    CommonInst_Tr64FromInt(OpIndex),
    /// common inst: creates a tagref from reference (a ref-void typed ref, 6 bits tag)
    CommonInst_Tr64FromRef(OpIndex, OpIndex),
    /// common inst: converts a tagref to floating point (double)
    CommonInst_Tr64ToFp(OpIndex),
    /// common inst: converts a tagref to integer (int<52>)
    CommonInst_Tr64ToInt(OpIndex),
    /// common inst: converts a tagref to reference
    CommonInst_Tr64ToRef(OpIndex),
    /// common inst: converts a tagref to a tag (int<64>)
    CommonInst_Tr64ToTag(OpIndex),
1126

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1127 1128 1129 1130 1131 1132 1133
    /// internal use: move from value to value
    Move(OpIndex),
    /// internal use: print op as hex value
    PrintHex(OpIndex),
    /// internal use: set return value for main
    SetRetval(OpIndex)
}
1134

Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
fn format_value_types(value: &Option<Vec<P<Value>>>) -> String {
    match value {
        &Some(ref v) => {
            let mut tys = format!("");
            for i in 0..v.len() {
                tys.push_str(format!("{}", v[i].ty).as_str());
                if i != v.len() - 1 {
                    tys.push_str(" ");
                }
            }
            tys
1146
        }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1147
        &None => "".to_string()
1148
    }
1149
}
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1150

1151 1152 1153 1154 1155
fn format_new_stack_clause(
    is_exception: bool,
    args: &Vec<OpIndex>,
    ops: &Vec<P<TreeNode>>
) -> String {
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
    if is_exception {
        assert!(args.len() == 1);
        format!("THROW_EXC {}", ops[args[0]])
    } else {
        let mut arg_tys = format!("");
        let mut arg_vals = format!("");
        for i in 0..args.len() {
            let ref op = ops[args[i]];
            arg_tys.push_str(format!("{}", op.ty()).as_str());
            arg_vals.push_str(format!("{}", op).as_str());
            if i != args.len() - 1 {
                arg_tys.push_str(" ");
                arg_vals.push_str(" ");
            }
        }
        format!("PASS_VALUES<{}>({})", arg_tys, arg_vals)
    }
}
qinsoon's avatar
qinsoon committed
1174
/// BinOpStatus represents status flags from a binary operation
1175
#[derive(Copy, Clone)]
qinsoon's avatar
qinsoon committed
1176
pub struct BinOpStatus {
qinsoon's avatar
qinsoon committed
1177
    /// negative flag
qinsoon's avatar
qinsoon committed
1178
    pub flag_n: bool,
qinsoon's avatar
qinsoon committed
1179
    /// zero flag
qinsoon's avatar
qinsoon committed
1180
    pub flag_z: bool,
qinsoon's avatar
qinsoon committed
1181
    /// carry flag
qinsoon's avatar
qinsoon committed
1182
    pub flag_c: bool,
qinsoon's avatar
qinsoon committed
1183
    /// overflow flag
1184
    pub flag_v: bool
qinsoon's avatar
qinsoon committed
1185
}
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
impl fmt::Display for BinOpStatus {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[")?;
        if self.flag_n {
            write!(f, "#N ")?;
        }
        if self.flag_z {
            write!(f, "#Z ")?;
        }
        if self.flag_c {
            write!(f, "#C ")?;
        }
        if self.flag_v {
            write!(f, "#V ")?;
        }
        Ok(())
    }
}

qinsoon's avatar
qinsoon committed
1205 1206

impl BinOpStatus {
1207
    pub fn none() -> BinOpStatus {
qinsoon's avatar
qinsoon committed
1208 1209 1210 1211
        BinOpStatus {
            flag_n: false,
            flag_z: false,
            flag_c: false,
1212
            flag_v: false
qinsoon's avatar
qinsoon committed
1213
        }
1214 1215
    }

qinsoon's avatar
qinsoon committed
1216
    pub fn n() -> BinOpStatus {
qinsoon's avatar
qinsoon committed
1217 1218 1219 1220
        BinOpStatus {
            flag_n: true,
            flag_z: false,
            flag_c: false,
1221
            flag_v: false
qinsoon's avatar
qinsoon committed
1222
        }
qinsoon's avatar
qinsoon committed
1223 1224 1225
    }

    pub fn z() -> BinOpStatus {
qinsoon's avatar
qinsoon committed
1226 1227 1228 1229
        BinOpStatus {
            flag_n: false,
            flag_z: true,
            flag_c: false,
1230
            flag_v: false
qinsoon's avatar
qinsoon committed
1231
        }
qinsoon's avatar
qinsoon committed
1232 1233 1234
    }

    pub fn c() -> BinOpStatus {
qinsoon's avatar
qinsoon committed
1235 1236 1237 1238
        BinOpStatus {
            flag_n: false,
            flag_z: false,
            flag_c: true,
1239
            flag_v: false
qinsoon's avatar
qinsoon committed
1240
        }
qinsoon's avatar
qinsoon committed
1241 1242 1243
    }

    pub fn v() -> BinOpStatus {
qinsoon's avatar
qinsoon committed
1244 1245 1246 1247
        BinOpStatus {
            flag_n: false,
            flag_z: false,
            flag_c: false,
1248
            flag_v: true
qinsoon's avatar
qinsoon committed
1249
        }
qinsoon's avatar
qinsoon committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    }
}

impl fmt::Debug for BinOpStatus {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.flag_n {
            write!(f, "#N").unwrap();
        }
        if self.flag_z {
            write!(f, "#Z").unwrap();
        }
        if self.flag_c {
            write!(f, "#C").unwrap();
        }
        if self.flag_v {
            write!(f, "#V").unwrap();
        }
        Ok(())
    }
}

1271
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
1272 1273 1274 1275 1276 1277 1278
pub enum MemoryOrder {
    NotAtomic,
    Relaxed,
    Consume,
    Acquire,
    Release,
    AcqRel,
1279
    SeqCst
1280 1281
}

1282 1283 1284
impl fmt::Display for MemoryOrder {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::MemoryOrder::*;
1285 1286 1287
        write!(
            f,
            "{}",
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
            match *self {
                NotAtomic => "",
                Relaxed => "RELAXED",
                Consume => "CONSUME",
                Acquire => "ACQUIRE",
                Release => "RELEASE",
                AcqRel => "ACQ_REL",
                SeqCst => "SEQ_CST"
            }
        )
    }
}

1301 1302 1303
pub const C_CALL_CONVENTION: CallConvention = CallConvention::Foreign(ForeignFFI::C);
pub const MU_CALL_CONVENTION: CallConvention = CallConvention::Mu;

1304
#[derive(Copy, Clone, PartialEq, Debug)]
1305 1306
pub enum CallConvention {
    Mu,
1307
    Foreign(ForeignFFI)
1308
}
1309 1310 1311 1312
impl fmt::Display for CallConvention {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if *self == C_CALL_CONVENTION {
            write!(f, "#DEFAULT")
1313
        } else if *self == MU_CALL_CONVENTION {
1314 1315 1316 1317 1318 1319
            write!(f, "#MU")
        } else {
            unimplemented!()
        }
    }
}
1320

1321
#[derive(Copy, Clone, Debug, PartialEq)]
1322
pub enum ForeignFFI {
1323
    C
1324 1325
}

1326
#[derive(Clone, Debug)]
1327 1328 1329
pub struct CallData {
    pub func: OpIndex,
    pub args: Vec<OpIndex>,
1330
    pub convention: CallConvention
1331 1332 1333 1334
}

impl CallData {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
1335
        let func = &ops[self.func];
1336 1337 1338 1339 1340
        let conv = if self.convention == CallConvention::Mu {
            "".to_string()
        } else {
            format!(" {}", self.convention)
        };
qinsoon's avatar
qinsoon committed
1341
        format!(
1342 1343 1344 1345
            "{}<{}> {} ({})",
            conv,
            func.ty().get_sig().unwrap(),
            func,
qinsoon's avatar
qinsoon committed
1346 1347
            op_vector_str(&self.args, ops)
        )
1348 1349 1350
    }
}

1351
#[derive(Clone, Debug)]
1352 1353
pub struct ResumptionData {
    pub normal_dest: Destination,
1354
    pub exn_dest: Destination
1355 1356 1357 1358
}

impl ResumptionData {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
qinsoon's avatar
qinsoon committed
1359
        format!(
1360
            "EXC ({} {})",
qinsoon's avatar
qinsoon committed
1361 1362 1363
            self.normal_dest.debug_str(ops),
            self.exn_dest.debug_str(ops)
        )
1364 1365 1366
    }
}

1367
#[derive(Clone, Debug)]
1368
pub struct Destination {
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1369
    pub target: MuEntityRef,
1370
    pub args: Vec<DestArg>
1371 1372 1373 1374
}

impl Destination {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
1375 1376
        let mut ret = format!("{}", self.target);
        ret.push('(');
1377 1378 1379 1380
        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 {
1381
                ret.push_str(" ");
1382 1383
            }
        }
1384
        ret.push(')');
1385

1386 1387
        ret
    }
1388 1389

    pub fn get_arguments_as_node(&self, ops: &Vec<P<TreeNode>>) -> Vec<P<TreeNode>> {
qinsoon's avatar
qinsoon committed
1390 1391
        vec_utils::map(&self.args, |x| match x {
            &DestArg::Normal(i) => ops[i].clone(),
1392
            &DestArg::Freshbound(_) => unimplemented!()
qinsoon's avatar
qinsoon committed
1393
        })
1394 1395
    }

1396
    pub fn get_arguments(&self, ops: &Vec<P<TreeNode>>) -> Vec<P<Value>> {
qinsoon's avatar
qinsoon committed
1397 1398
        vec_utils::map(&self.args, |x| match x {
            &DestArg::Normal(i) => ops[i].clone_value(),
1399
            &DestArg::Freshbound(_) => unimplemented!()
1400 1401
        })
    }
1402 1403
}

1404
#[derive(Clone, Debug)]
1405
pub enum DestArg {
qinsoon's avatar
qinsoon committed
1406
    /// a normal destination argument is an SSA value (appears in the ops field of the instruction)
1407
    Normal(OpIndex),
qinsoon's avatar
qinsoon committed
1408
    /// a freshbound argument is an undeclared/anonymous value (currently not support this)
1409
    Freshbound(usize)
1410 1411 1412 1413 1414 1415
}

impl DestArg {
    fn debug_str(&self, ops: &Vec<P<TreeNode>>) -> String {
        match self {
            &DestArg::Normal(index) => format!("{}", ops[index]),
1416
            &DestArg::Freshbound(n) => format!("${}", n)
1417 1418
        }
    }
1419
}
1420 1421 1422 1423 1424 1425 1426

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(format!("{}", ops[index]).as_str());
        if i != vec.len() - 1 {
1427
            ret.push_str(" ");
1428 1429 1430
        }
    }
    ret
qinsoon's avatar
qinsoon committed
1431
}