asm_backend.rs 119 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
use compiler::backend::AOT_EMIT_CONTEXT_FILE;
use compiler::backend::RegGroup;
use utils::ByteSize;
use utils::Address;
use utils::POINTER_SIZE;
use compiler::backend::aarch64::*;

use compiler::backend::{Reg, Mem};
use compiler::machine_code::MachineCode;
use vm::VM;
use runtime::ValueLocation;

use utils::vec_utils;
use utils::string_utils;
use utils::LinkedHashMap;

use ast::ptr::P;
use ast::ir::*;

use std::str;
use std::usize;
use std::ops;
23
use std::collections::HashSet;
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

struct ASMCode {
    name: MuName,
    code: Vec<ASMInst>,

    entry:  MuName,
    blocks: LinkedHashMap<MuName, ASMBlock>,

    frame_size_patchpoints: Vec<ASMLocation>
}

unsafe impl Send for ASMCode {}
unsafe impl Sync for ASMCode {}

impl ASMCode {
    fn get_use_locations(&self, reg: MuID) -> Vec<ASMLocation> {
        let mut ret = vec![];

        for inst in self.code.iter() {
            match inst.uses.get(&reg) {
                Some(ref locs) => {
                    ret.append(&mut locs.to_vec());
                },
                None => {}
            }
        }

        ret
    }

    fn get_define_locations(&self, reg: MuID) -> Vec<ASMLocation> {
        let mut ret = vec![];

        for inst in self.code.iter() {
            match inst.defines.get(&reg) {
                Some(ref locs) => {
                    ret.append(&mut locs.to_vec());
                },
                None => {}
            }
        }

        ret
    }

    fn is_block_start(&self, inst: usize) -> bool {
        for block in self.blocks.values() {
            if block.start_inst == inst {
                return true;
            }
        }
        false
    }

    fn is_last_inst_in_block(&self, inst: usize) -> bool {
        for block in self.blocks.values() {
            if block.end_inst == inst + 1 {
                return true;
            }
        }
        false
    }

    fn get_block_by_inst(&self, inst: usize) -> (&String, &ASMBlock) {
        for (name, block) in self.blocks.iter() {
            if inst >= block.start_inst && inst < block.end_inst {
                return (name, block);
            }
        }

        panic!("didnt find any block for inst {}", inst)
    }

    fn rewrite_insert(
        &self,
        insert_before: LinkedHashMap<usize, Vec<Box<ASMCode>>>,
        insert_after: LinkedHashMap<usize, Vec<Box<ASMCode>>>) -> Box<ASMCode>
    {
        trace!("insert spilling code");
        let mut ret = ASMCode {
            name: self.name.clone(),
            entry: self.entry.clone(),
            code: vec![],
            blocks: linked_hashmap!{},
            frame_size_patchpoints: vec![]
        };

        // iterate through old machine code
        let mut inst_offset = 0;    // how many instructions has been inserted
        let mut cur_block_start = usize::MAX;

        // inst N in old machine code is N' in new machine code
        // this map stores the relationship
        let mut location_map : LinkedHashMap<usize, usize> = LinkedHashMap::new();

        for i in 0..self.number_of_insts() {
            trace!("Inst{}", i);

            if self.is_block_start(i) {
                cur_block_start = i + inst_offset;
                trace!("  block start is shifted to {}", cur_block_start);
            }

            // insert code before this instruction
            if insert_before.contains_key(&i) {
                for insert in insert_before.get(&i).unwrap() {
                    ret.append_code_sequence_all(insert);
                    inst_offset += insert.number_of_insts();
                    trace!("  inserted {} insts before", insert.number_of_insts());
                }
            }

            // copy this instruction
            let mut inst = self.code[i].clone();

            // old ith inst is now the (i + inst_offset)th instruction
            location_map.insert(i, i + inst_offset);
            trace!("  Inst{} is now Inst{}", i, i + inst_offset);

            // this instruction has been offset by several instructions('inst_offset')
            // update its info
            // 1. fix defines and uses
            for locs in inst.defines.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line += inst_offset;
                }
            }
            for locs in inst.uses.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line += inst_offset;
                }
            }
            // 2. we need to delete existing preds/succs - CFA is required later
            inst.preds.clear();
            inst.succs.clear();
            // 3. add the inst
            ret.code.push(inst);


            // insert code after this instruction
            if insert_after.contains_key(&i) {
                for insert in insert_after.get(&i).unwrap() {
                    ret.append_code_sequence_all(insert);
                    inst_offset += insert.number_of_insts();
                    trace!("  inserted {} insts after", insert.number_of_insts());
                }
            }

            if self.is_last_inst_in_block(i) {
                let cur_block_end = i + 1 + inst_offset;

                // copy the block
                let (name, block) = self.get_block_by_inst(i);

                let new_block = ASMBlock{
                    start_inst: cur_block_start,
                    end_inst: cur_block_end,

                    livein: vec![],
                    liveout: vec![]
                };

                trace!("  old block: {:?}", block);
                trace!("  new block: {:?}", new_block);

                cur_block_start = usize::MAX;

                // add to the new code
                ret.blocks.insert(name.clone(), new_block);
            }
        }

        // fix patchpoint
        for patchpoint in self.frame_size_patchpoints.iter() {
            let new_patchpoint = ASMLocation {
                line: *location_map.get(&patchpoint.line).unwrap(),
                index: patchpoint.index,
                len: patchpoint.len,
                oplen: patchpoint.oplen
            };

            ret.frame_size_patchpoints.push(new_patchpoint);
        }

        ret.control_flow_analysis();

        Box::new(ret)
    }

    fn append_code_sequence(
        &mut self,
        another: &Box<ASMCode>,
        start_inst: usize,
        n_insts: usize)
    {
        let base_line = self.number_of_insts();

        for i in 0..n_insts {
            let cur_line_in_self = base_line + i;
            let cur_line_from_copy = start_inst + i;

            let mut inst = another.code[cur_line_from_copy].clone();

            // fix info
            for locs in inst.defines.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line = cur_line_in_self;
                }
            }
            for locs in inst.uses.values_mut() {
                for loc in locs {
                    debug_assert!(loc.line == i);
                    loc.line = cur_line_in_self;
                }
            }
            // ignore preds/succs

            // add to self
            self.code.push(inst);
        }
    }

    fn append_code_sequence_all(&mut self, another: &Box<ASMCode>) {
        let n_insts = another.number_of_insts();
        self.append_code_sequence(another, 0, n_insts)
    }

    fn control_flow_analysis(&mut self) {
        const TRACE_CFA : bool = true;

        // control flow analysis
        let n_insts = self.number_of_insts();

        let ref mut asm = self.code;

        for i in 0..n_insts {
            if TRACE_CFA {
                trace!("---inst {}---", i);
            }

            // skip symbol
            if asm[i].is_symbol {
                continue;
            }

            // determine predecessor

            // we check if it is a fallthrough block
            if i != 0 {
                let last_inst = ASMCode::find_prev_inst(i, asm);

                match last_inst {
                    Some(last_inst) => {
                        let last_inst_branch = asm[last_inst].branch.clone();
                        match last_inst_branch {
                            // if it is a fallthrough, we set its preds as last inst
                            ASMBranchTarget::None => {
                                if !asm[i].preds.contains(&last_inst) {
                                    asm[i].preds.push(last_inst);

                                    if TRACE_CFA {
                                        trace!("inst {}: set PREDS as previous inst - fallthrough {}", i, last_inst);
                                    }
                                }
                            }
                            // otherwise do nothing
                            _ => {}
                        }
                    }
                    None => {}
                }
            }

            // determine successor
            let branch = asm[i].branch.clone();
            match branch {
                ASMBranchTarget::Unconditional(ref target) => {
                    // branch to target
                    let target_n = self.blocks.get(target).unwrap().start_inst;

                    // cur inst's succ is target
                    asm[i].succs.push(target_n);

                    // target's pred is cur
                    asm[target_n].preds.push(i);

                    if TRACE_CFA {
                        trace!("inst {}: is a branch to {}", i, target);
                        trace!("inst {}: branch target index is {}", i, target_n);
                        trace!("inst {}: set SUCCS as branch target {}", i, target_n);
                        trace!("inst {}: set PREDS as branch source {}", target_n, i);
                    }
                },
                ASMBranchTarget::Conditional(ref target) => {
                    // branch to target
                    let target_n = self.blocks.get(target).unwrap().start_inst;

                    // cur insts' succ is target
                    asm[i].succs.push(target_n);

                    if TRACE_CFA {
                        trace!("inst {}: is a cond branch to {}", i, target);
                        trace!("inst {}: branch target index is {}", i, target_n);
                        trace!("inst {}: set SUCCS as branch target {}", i, target_n);
                    }

                    // target's pred is cur
                    asm[target_n].preds.push(i);
                    if TRACE_CFA {
                        trace!("inst {}: set PREDS as {}", target_n, i);
                    }

                    if let Some(next_inst) = ASMCode::find_next_inst(i, asm) {
                        // cur succ is next inst
                        asm[i].succs.push(next_inst);

                        // next inst's pred is cur
                        asm[next_inst].preds.push(i);

                        if TRACE_CFA {
                            trace!("inst {}: SET SUCCS as c-branch fallthrough target {}", i, next_inst);
                        }
                    } else {
                        panic!("conditional branch does not have a fallthrough target");
                    }
                },
                ASMBranchTarget::PotentiallyExcepting(ref target) => {
                    // may trigger exception and jump to target - similar as conditional branch
                    let target_n = self.blocks.get(target).unwrap().start_inst;

                    // cur inst's succ is target
                    asm[i].succs.push(target_n);

                    if TRACE_CFA {
                        trace!("inst {}: is potentially excepting to {}", i, target);
                        trace!("inst {}: excepting target index is {}", i, target_n);
                        trace!("inst {}: set SUCCS as excepting target {}", i, target_n);
                    }

                    asm[target_n].preds.push(i);

                    if let Some(next_inst) = ASMCode::find_next_inst(i, asm) {
                        // cur succ is next inst
                        asm[i].succs.push(next_inst);

                        // next inst's pred is cur
                        asm[next_inst].preds.push(i);

                        if TRACE_CFA {
                            trace!("inst {}: SET SUCCS as PEI fallthrough target {}", i, next_inst);
                        }
                    } else {
                        panic!("PEI does not have a fallthrough target");
                    }
                },
                ASMBranchTarget::Return => {
                    if TRACE_CFA {
                        trace!("inst {}: is a return", i);
                        trace!("inst {}: has no successor", i);
                    }
                }
                ASMBranchTarget::None => {
                    // not branch nor cond branch, succ is next inst
                    if TRACE_CFA {
                        trace!("inst {}: not a branch inst", i);
                    }
                    if let Some(next_inst) = ASMCode::find_next_inst(i, asm) {
                        if TRACE_CFA {
                            trace!("inst {}: set SUCCS as next inst {}", i, next_inst);
                        }
                        asm[i].succs.push(next_inst);
                    }
                }
                ASMBranchTarget::UnconditionalReg(id) => {
                    if TRACE_CFA {
                        trace!("inst {}: is an unconditional branch to reg {}", i, id);
                        trace!("inst {}: has no successor", i);
                    }
                }
            }
        }
    }

    fn find_prev_inst(i: usize, asm: &Vec<ASMInst>) -> Option<usize> {
        if i == 0 {
            None
        } else {
            let mut cur = i - 1;
            while cur != 0 {
                if !asm[cur].is_symbol {
                    return Some(cur);
                }

                if cur == 0 {
                    return None;
                } else {
                    cur -= 1;
                }
            }

            None
        }
    }

    fn find_next_inst(i: usize, asm: &Vec<ASMInst>) -> Option<usize> {
        if i >= asm.len() - 1 {
            None
        } else {
            let mut cur = i + 1;
            while cur < asm.len() {
                if !asm[cur].is_symbol {
                    return Some(cur);
                }

                cur += 1;
            }

            None
        }
    }

    fn find_last_inst(i: usize, asm: &Vec<ASMInst>) -> Option<usize> {
        if i == 0 {
            None
        } else {
            let mut cur = i;
            loop {
                if !asm[cur].is_symbol {
                    return Some(cur);
                }

                if cur == 0 {
                    return None;
                } else {
                    cur -= 1;
                }
            }
        }
    }

    fn add_frame_size_patchpoint(&mut self, patchpoint: ASMLocation) {
        self.frame_size_patchpoints.push(patchpoint);
    }
}

use std::any::Any;

impl MachineCode for ASMCode {
    fn as_any(&self) -> &Any {
        self
    }
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }

    fn is_move(&self, index: usize) -> bool {
        let inst = self.code.get(index);
        match inst {
            Some(inst) => {
                let ref inst = inst.code;

                if inst.starts_with("MOV ") || inst.starts_with("FMOV ") {
                    // normal mov
                    true
                } else {
                    false
                }
            },
            None => false
        }
    }

    fn is_using_mem_op(&self, index: usize) -> bool {
        self.code[index].is_mem_op_used
    }

    fn is_jmp(&self, index: usize) -> Option<MuName> {
        let inst = self.code.get(index);
        match inst {
506 507
            Some(inst) if inst.code.starts_with("B.") || inst.code.starts_with("B ") => {
                // Destination is the first argument
508 509 510
                let split : Vec<&str> = inst.code.split(' ').collect();
                Some(ASMCodeGen::unmangle_block_label(self.name.clone(), String::from(split[1])))
            }
511 512 513 514 515 516 517 518 519 520 521
            Some(inst) if inst.code.starts_with("CBNZ ")  || inst.code.starts_with("CBZ ") => {
                // Destination is the second argument
                let split : Vec<&str> = inst.code.split(',').collect();
                Some(ASMCodeGen::unmangle_block_label(self.name.clone(), String::from(split[1])))
            }
            Some(inst) if inst.code.starts_with("TBNZ ")  || inst.code.starts_with("TBZ ") => {
                // Destination is the third argument
                let split : Vec<&str> = inst.code.split(',').collect();
                Some(ASMCodeGen::unmangle_block_label(self.name.clone(), String::from(split[2])))
            }

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 602 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
            _ => None
        }
    }

    fn is_label(&self, index: usize) -> Option<MuName> {
        let inst = self.code.get(index);
        match inst {
            Some(inst) if inst.code.ends_with(':') => {
                let split : Vec<&str> = inst.code.split(':').collect();

                Some(ASMCodeGen::unmangle_block_label(self.name.clone(), String::from(split[0])))
            }
            _ => None
        }
    }

    fn is_spill_load(&self, index: usize) -> Option<P<Value>> {
        if let Some(inst) = self.code.get(index) {
            match inst.spill_info {
                Some(SpillMemInfo::Load(ref p)) => Some(p.clone()),
                _ => None
            }
        } else {
            None
        }
    }

    fn is_spill_store(&self, index: usize) -> Option<P<Value>> {
        if let Some(inst) = self.code.get(index) {
            match inst.spill_info {
                Some(SpillMemInfo::Store(ref p)) => Some(p.clone()),
                _ => None
            }
        } else {
            None
        }
    }

    fn get_succs(&self, index: usize) -> &Vec<usize> {
        &self.code[index].succs
    }

    fn get_preds(&self, index: usize) -> &Vec<usize> {
        &self.code[index].preds
    }

    fn get_inst_reg_uses(&self, index: usize) -> Vec<MuID> {
        self.code[index].uses.keys().map(|x| *x).collect()
    }

    fn get_inst_reg_defines(&self, index: usize) -> Vec<MuID> {
        self.code[index].defines.keys().map(|x| *x).collect()
    }

    fn replace_reg(&mut self, from: MuID, to: MuID) {
        for loc in self.get_define_locations(from) {
            let ref mut inst_to_patch = self.code[loc.line];

            // pick the right reg based on length
            let to_reg = get_alias_for_length(to, loc.oplen);
            let to_reg_string = to_reg.name().unwrap();

            string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
        }

        for loc in self.get_use_locations(from) {
            let ref mut inst_to_patch = self.code[loc.line];

            // pick the right reg based on length
            let to_reg = get_alias_for_length(to, loc.oplen);
            let to_reg_string = to_reg.name().unwrap();

            string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
        }
    }

    fn replace_define_tmp_for_inst(&mut self, from: MuID, to: MuID, inst: usize) {
        let to_reg_string : MuName = REG_PLACEHOLDER.clone();

        let asm = &mut self.code[inst];
        // if this reg is defined, replace the define
        if asm.defines.contains_key(&from) {
            let define_locs = asm.defines.get(&from).unwrap().to_vec();
            // replace temps
            for loc in define_locs.iter() {
                string_utils::replace(&mut asm.code, loc.index, &to_reg_string, to_reg_string.len());
            }

            // remove old key, insert new one
            asm.defines.remove(&from);
            asm.defines.insert(to, define_locs);
        }
    }

    fn replace_use_tmp_for_inst(&mut self, from: MuID, to: MuID, inst: usize) {
        let to_reg_string : MuName = REG_PLACEHOLDER.clone();

        let asm = &mut self.code[inst];

        // if this reg is used, replace the use
        if asm.uses.contains_key(&from) {
            let use_locs = asm.uses.get(&from).unwrap().to_vec();
            // replace temps
            for loc in use_locs.iter() {
                string_utils::replace(&mut asm.code, loc.index, &to_reg_string, to_reg_string.len());
            }

            // remove old key, insert new one
            asm.uses.remove(&from);
            asm.uses.insert(to, use_locs);
        }
    }

    fn set_inst_nop(&mut self, index: usize) {
        self.code[index].code.clear();
637 638
        //        self.code.remove(index);
        //        self.code.insert(index, ASMInst::nop());
639 640
    }

641
    fn remove_unnecessary_callee_saved(&mut self, used_callee_saved: Vec<MuID>) -> HashSet<MuID> {
642
        // every push pair (STP)/and pop pair (LDP) will use/define SP
643
        let fp = FP.extract_ssa_id().unwrap();
644

645 646
        // Note: this version assumes only 1 callee is pushed or poped
        let find_op_other_than_fp = |inst: &ASMInst| -> MuID {
647
            for id in inst.defines.keys() {
648 649
                if *id != fp {
                    return *id;
650 651 652
                }
            }
            for id in inst.uses.keys() {
653 654
                if *id != fp {
                    return *id;
655 656 657
                }
            }

658
            panic!("Expected to find a used register other than the FP");
659 660 661
        };

        let mut inst_to_remove = vec![];
662
        let mut regs_to_remove = HashSet::new();
663 664 665 666

        for i in 0..self.number_of_insts() {
            let ref inst = self.code[i];

667 668 669 670 671 672
            match inst.spill_info {
                Some(SpillMemInfo::CalleeSaved) => {
                    let reg = find_op_other_than_fp(inst);
                    if !used_callee_saved.contains(&reg) {
                        inst_to_remove.push(i);
                        regs_to_remove.insert(reg);
673 674
                    }
                }
675
                _ => {}
676 677 678 679 680 681
            }
        }

        for i in inst_to_remove {
            self.set_inst_nop(i);
        }
682
        regs_to_remove
683 684
    }

685
    fn patch_frame_size(&mut self, size: usize) {
686 687 688 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
        debug_assert!(size % 16 == 0);

        let size = size.to_string();

        debug_assert!(size.len() <= FRAME_SIZE_PLACEHOLDER_LEN);

        for loc in self.frame_size_patchpoints.iter() {
            let ref mut inst = self.code[loc.line];

            string_utils::replace(&mut inst.code, loc.index, &size, size.len());
        }
    }

    fn emit(&self) -> Vec<u8> {
        let mut ret = vec![];

        for inst in self.code.iter() {
            if !inst.is_symbol {
                ret.append(&mut "\t".to_string().into_bytes());
            }

            ret.append(&mut inst.code.clone().into_bytes());
            ret.append(&mut "\n".to_string().into_bytes());
        }

        ret
    }

    fn emit_inst(&self, index: usize) -> Vec<u8> {
        let mut ret = vec![];

        let ref inst = self.code[index];

        if !inst.is_symbol {
            ret.append(&mut "\t".to_string().into_bytes());
        }

        ret.append(&mut inst.code.clone().into_bytes());

        ret
    }

    fn trace_mc(&self) {
        trace!("");

        trace!("code for {}: \n", self.name);

        let n_insts = self.code.len();
        for i in 0..n_insts {
            self.trace_inst(i);
        }

        trace!("")
    }

    fn trace_inst(&self, i: usize) {
        trace!("#{}\t{:30}\t\tdefine: {:?}\tuses: {:?}\tpred: {:?}\tsucc: {:?}",
743 744
        i, self.code[i].code, self.get_inst_reg_defines(i), self.get_inst_reg_uses(i),
        self.code[i].preds, self.code[i].succs);
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
    }

    fn get_ir_block_livein(&self, block: &str) -> Option<&Vec<MuID>> {
        match self.blocks.get(block) {
            Some(ref block) => Some(&block.livein),
            None => None
        }
    }

    fn get_ir_block_liveout(&self, block: &str) -> Option<&Vec<MuID>> {
        match self.blocks.get(block) {
            Some(ref block) => Some(&block.liveout),
            None => None
        }
    }

    fn set_ir_block_livein(&mut self, block: &str, set: Vec<MuID>) {
        let block = self.blocks.get_mut(block).unwrap();
        block.livein = set;
    }

    fn set_ir_block_liveout(&mut self, block: &str, set: Vec<MuID>) {
        let block = self.blocks.get_mut(block).unwrap();
        block.liveout = set;
    }

771
    fn get_all_blocks(&self) -> Vec<MuName> { self.blocks.keys().map(|x| x.clone()).collect() }
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

    fn get_entry_block(&self) -> MuName {
        self.entry.clone()
    }

    fn get_block_range(&self, block: &str) -> Option<ops::Range<usize>> {
        match self.blocks.get(block) {
            Some(ref block) => Some(block.start_inst..block.end_inst),
            None => None
        }
    }

    fn get_block_for_inst(&self, index: usize) -> Option<MuName> {
        for (name, block) in self.blocks.iter() {
            if index >= block.start_inst && index < block.end_inst {
                return Some(name.clone());
            }
        }

        None
    }

    fn get_next_inst(&self, index: usize) -> Option<usize> {
        ASMCode::find_next_inst(index, &self.code)
    }

    fn get_last_inst(&self, index: usize) -> Option<usize> {
        ASMCode::find_last_inst(index, &self.code)
    }
}

#[derive(Clone, Debug)]
enum ASMBranchTarget {
    None,
    Conditional(MuName),
    Unconditional(MuName),
    PotentiallyExcepting(MuName),
    Return,
    UnconditionalReg(MuID)
}

#[derive(Clone, Debug)]
enum SpillMemInfo {
    Load(P<Value>),
816 817
    Store(P<Value>),
    CalleeSaved, // Callee saved record
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
}

#[derive(Clone, Debug)]
struct ASMInst {
    code: String,

    defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
    uses: LinkedHashMap<MuID, Vec<ASMLocation>>,

    is_mem_op_used: bool,
    is_symbol: bool,

    preds: Vec<usize>,
    succs: Vec<usize>,
    branch: ASMBranchTarget,

    spill_info: Option<SpillMemInfo>
}

impl ASMInst {
    fn symbolic(line: String) -> ASMInst {
        ASMInst {
            code: line,
            defines: LinkedHashMap::new(),
            uses: LinkedHashMap::new(),
            is_mem_op_used: false,
            is_symbol: true,
            preds: vec![],
            succs: vec![],
            branch: ASMBranchTarget::None,

            spill_info: None
        }
    }

    fn inst(
        inst: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_mem_op_used: bool,
        target: ASMBranchTarget,
        spill_info: Option<SpillMemInfo>
    ) -> ASMInst
    {
        ASMInst {
            code: inst,
            defines: defines,
            uses: uses,
            is_symbol: false,
            is_mem_op_used: is_mem_op_used,
            preds: vec![],
            succs: vec![],
            branch: target,

            spill_info: spill_info
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize,
    oplen: usize,
}

impl ASMLocation {
    fn new(line: usize, index: usize, len: usize, oplen: usize) -> ASMLocation {
        ASMLocation{
            line: line,
            index: index,
            len: len,
            oplen: oplen
        }
    }
}

#[derive(Clone, Debug)]
/// [start_inst, end_inst)
struct ASMBlock {
    start_inst: usize,
    end_inst: usize,

    livein: Vec<MuID>,
    liveout: Vec<MuID>
}

impl ASMBlock {
    fn new() -> ASMBlock {
        ASMBlock {
            start_inst: usize::MAX,
            end_inst: usize::MAX,
            livein: vec![],
            liveout: vec![]
        }
    }
}

pub struct ASMCodeGen {
    cur: Option<Box<ASMCode>>
}

const REG_PLACEHOLDER_LEN : usize = 5;
lazy_static! {
    pub static ref REG_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];

        format!("{}", str::from_utf8(&blank_spaces).unwrap())
    };
}

const FRAME_SIZE_PLACEHOLDER_LEN : usize = 10; // a frame is smaller than 1 << 10
lazy_static! {
    pub static ref FRAME_SIZE_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; FRAME_SIZE_PLACEHOLDER_LEN];
        format!("{}", str::from_utf8(&blank_spaces).unwrap())
    };
}

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
        ASMCodeGen {
            cur: None
        }
    }

    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }

    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }

    fn line(&self) -> usize {
        self.cur().code.len()
    }

    fn add_asm_block_label(&mut self, code: String, block_name: MuName) {
        trace!("emit: [{}]{}", block_name, code);
        self.cur_mut().code.push(ASMInst::symbolic(code));
    }

962
    fn add_asm_symbolic(&mut self, code: String) {
963 964 965 966 967 968 969
        trace!("emit: {}", code);
        self.cur_mut().code.push(ASMInst::symbolic(code));
    }

    fn add_asm_call(&mut self, code: String, potentially_excepting: Option<MuName>, target: Option<(MuID, ASMLocation)>) {
        // a call instruction will use all the argument registers
        // do not need
970
        let mut uses: LinkedHashMap<MuID, Vec<ASMLocation>> = LinkedHashMap::new();
971 972 973 974
        if target.is_some() {
            let (id, loc) = target.unwrap();
            uses.insert(id, vec![loc]);
        }
975 976 977 978 979 980
        //        for reg in ARGUMENT_GPRs.iter() {
        //            uses.insert(reg.id(), vec![]);
        //        }
        //        for reg in ARGUMENT_FPRs.iter() {
        //            uses.insert(reg.id(), vec![]);
        //        }
981 982

        // defines: return registers
983
        let mut defines: LinkedHashMap<MuID, Vec<ASMLocation>> = LinkedHashMap::new();
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        for reg in RETURN_GPRs.iter() {
            defines.insert(reg.id(), vec![]);
        }
        for reg in RETURN_FPRs.iter() {
            defines.insert(reg.id(), vec![]);
        }
        for reg in CALLER_SAVED_GPRs.iter() {
            if !defines.contains_key(&reg.id()) {
                defines.insert(reg.id(), vec![]);
            }
        }
        for reg in CALLER_SAVED_FPRs.iter() {
            if !defines.contains_key(&reg.id()) {
                defines.insert(reg.id(), vec![]);
            }
        }

        self.add_asm_inst_internal(code, defines, uses, false, {
            if potentially_excepting.is_some() {
                ASMBranchTarget::PotentiallyExcepting(potentially_excepting.unwrap())
            } else {
                ASMBranchTarget::None
            }
        }, None)
    }

    fn add_asm_inst(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool
    ) {
        self.add_asm_inst_internal(code, defines, uses, is_using_mem_op, ASMBranchTarget::None, None)
    }

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    fn add_asm_inst_with_callee_saved(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool,
    ) {
        self.add_asm_inst_internal(code, defines, uses, is_using_mem_op, ASMBranchTarget::None, Some(SpillMemInfo::CalleeSaved))
    }

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    fn add_asm_inst_with_spill(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool,
        spill_info: SpillMemInfo
    ) {
        self.add_asm_inst_internal(code, defines, uses, is_using_mem_op, ASMBranchTarget::None, Some(spill_info))
    }

    fn add_asm_inst_internal(
        &mut self,
        code: String,
        defines: LinkedHashMap<MuID, Vec<ASMLocation>>,
        uses: LinkedHashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool,
        target: ASMBranchTarget,
        spill_info: Option<SpillMemInfo>)
    {
        trace!("asm: {}", code);
        trace!("     defines: {:?}", defines);
        trace!("     uses: {:?}", uses);
        let mc = self.cur_mut();

        // put the instruction
        mc.code.push(ASMInst::inst(code, defines, uses, is_using_mem_op, target, spill_info));
    }

    fn prepare_reg(&self, op: &P<Value>, loc: usize) -> (String, MuID, ASMLocation) {
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting register op")
            }
        }

        let str = self.asm_reg_op(op);
        let len = str.len();
        (str, op.extract_ssa_id().unwrap(), ASMLocation::new(self.line(), loc, len, check_op_len(&op.ty)))
    }

1072
    fn prepare_mem(&self, op: &P<Value>, loc: usize) -> (String, LinkedHashMap<MuID, Vec<ASMLocation>>) {
1073 1074 1075 1076 1077 1078 1079
        if cfg!(debug_assertions) {
            match op.v {
                Value_::Memory(_) => {},
                _ => panic!("expecting memory op")
            }
        }

1080 1081 1082
        let mut ids: Vec<MuID> = vec![];
        let mut locs: Vec<ASMLocation> = vec![];
        let mut result_str: String = "".to_string();
1083

1084
        let mut loc_cursor: usize = loc;
1085 1086
        match op.v {
            // offset(base,index,scale)
1087
            Value_::Memory(MemoryLocation::Address { ref base, ref offset, shift, signed }) => {
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
                result_str.push('[');
                loc_cursor += 1;
                // deal with base, base is ssa
                let (str, id, loc) = self.prepare_reg(base, loc_cursor);
                result_str.push_str(&str);
                ids.push(id);
                locs.push(loc);
                loc_cursor += str.len();

                // deal with offset
                if offset.is_some() {
                    result_str.push(',');
                    loc_cursor += 1;

                    let offset = offset.as_ref().unwrap();
                    match offset.v {
                        Value_::SSAVar(_) => {
                            // temp as offset
                            let (str, id, loc) = self.prepare_reg(offset, loc_cursor);

                            result_str.push_str(&str);
                            ids.push(id);
                            locs.push(loc);

                            result_str.push_str(",");
                            let n = offset.ty.get_int_length().unwrap();
                            let shift_type =
1115 1116 1117
                                     if n == 64 { if signed { "SXTX" } else { "LSL"  } }
                                else if n == 32 { if signed { "SXTW" } else { "UXTW" } }
                                else            { panic!("Unexpected size for offset register") };
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

                            result_str.push_str(&shift_type);
                            result_str.push_str(" #");
                            let shift_str = shift.to_string();
                            result_str.push_str(&shift_str);
                        },
                        Value_::Constant(Constant::Int(val)) => {
                            let str = (val as i32).to_string();

                            result_str.push('#');
                            result_str.push_str(&str);
                        },
1130 1131 1132 1133
                        Value_::Constant(Constant::ExternSym(ref name)) => {
                            result_str.push('#');
                            result_str.push_str(name.as_str());
                        }
1134 1135 1136 1137 1138
                        _ => panic!("unexpected offset type: {:?}", offset)
                    }
                }

                // scale (for LSL type)
1139
                if shift != 0 {}
1140 1141 1142 1143

                result_str.push(']');
            },

1144
            Value_::Memory(MemoryLocation::Symbolic { ref label, is_global }) => {
1145
                let label =
1146 1147
                    if is_global { format!(":got:{}", label.clone()) }
                        else { label.clone() };
1148 1149
                result_str.push_str(label.as_str());
            },
1150 1151 1152 1153

            Value_::Memory(MemoryLocation::VirtualAddress {..}) => {
                panic!("Can't directly use a virtual adress (try calling emit_mem first)");
            }
1154 1155 1156
            _ => panic!("expect mem location as value")
        }

1157 1158
        let uses: LinkedHashMap<MuID, Vec<ASMLocation>> = {
            let mut map: LinkedHashMap<MuID, Vec<ASMLocation>> = linked_hashmap! {};
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
            for i in 0..ids.len() {
                let id = ids[i];
                let loc = locs[i].clone();

                if map.contains_key(&id) {
                    map.get_mut(&id).unwrap().push(loc);
                } else {
                    map.insert(id, vec![loc]);
                }
            }
            map
        };


        (result_str, uses)
    }

    fn asm_reg_op(&self, op: &P<Value>) -> String {
        let id = op.extract_ssa_id().unwrap();
        if id < MACHINE_ID_END {
            // machine reg
            format!("{}", op.name().unwrap())
        } else {
            // virtual register, use place holder
            REG_PLACEHOLDER.clone()
        }
    }

    fn mangle_block_label(&self, label: MuName) -> String {
        format!("{}_{}", self.cur().name, label)
    }

    fn unmangle_block_label(fn_name: MuName, label: String) -> MuName {
        // input: _fn_name_BLOCK_NAME
        // return BLOCK_NAME
1194 1195 1196 1197 1198 1199 1200
        let split: Vec<&str> = label.splitn(2, &(fn_name.clone() + "_")).collect();
        // TODO: Why was this if statetment unnecesary on x86 (perhaps block names are wrong)
        if split.len() == 0 {
            trace!("unmangle_block_label: fn_name '{}', label '{}', split ", fn_name, label);
        } else if split.len() == 1 {
            trace!("unmangle_block_label: fn_name '{}', label '{}', split '{}'", fn_name, label, split[0]);
        };
1201 1202 1203 1204 1205 1206 1207
        String::from(split[1])
    }

    fn finish_code_sequence_asm(&mut self) -> Box<ASMCode> {
        self.cur.take().unwrap()
    }

1208
    fn internal_simple(&mut self, inst: &str) {
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        let inst = inst.to_string();
        trace!("emit: \t{}", inst);

        let asm = inst;

        self.add_asm_inst(
            asm,
            linked_hashmap! {},
            linked_hashmap! {},
            false
        )
    }

1222
    fn internal_simple_imm(&mut self, inst: &str, val: u64) {
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
        let inst = inst.to_string();
        trace!("emit: \t{} {}", inst, val);

        let asm = format!("{} #{}", inst, val);

        self.add_asm_inst(
            asm,
            linked_hashmap! {},
            linked_hashmap! {},
            false
        )
    }

1236
    fn internal_simple_str(&mut self, inst: &str, option: &str) {
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
        let inst = inst.to_string();
        let option = option.to_string();
        trace!("emit: \t{} {}", inst, option);

        let asm = format!("{} {}", inst, option);

        self.add_asm_inst(
            asm,
            linked_hashmap! {},
            linked_hashmap! {},
            false
        )
    }

1251
    // A system instruction
1252
    fn internal_system(&mut self, inst: &str, option: &str, src: &P<Value>) {
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        let inst = inst.to_string();
        let option = option.to_string();
        trace!("emit: \t{} {} {}", inst, option, src);

        let (reg1, id1, loc1) = self.prepare_reg(src, inst.len() + 1 + option.len() + 1);

        let asm = format!("{} {},{}", inst, option, reg1);

        self.add_asm_inst(
            asm,
1263
            linked_hashmap! {},
1264
            ignore_zero_register(id1, vec![loc1]),
1265 1266 1267 1268
            false
        )
    }

1269
    fn internal_branch_op(&mut self, inst: &str, src: &P<Value>, dest_name: MuName) {
1270 1271 1272 1273
        trace!("emit: \t{} {}, {}", inst, src, dest_name);

        let (reg1, id1, loc1) = self.prepare_reg(src, inst.len() + 1);
        // symbolic label, we dont need to patch it
1274 1275
        let asm = format!("{} {},{}", inst, reg1, self.mangle_block_label(dest_name.clone()));
        self.add_asm_inst_internal(asm, linked_hashmap! {}, linked_hashmap! { id1 => vec![loc1]}, false, ASMBranchTarget::Conditional(dest_name), None);
1276 1277
    }

1278
    fn internal_branch_op_imm(&mut self, inst: &str, src1: &P<Value>, src2: u8, dest_name: MuName) {
1279 1280 1281 1282
        trace!("emit: \t{} {},{},{}", inst, src1, src2, dest_name);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);
        // symbolic label, we dont need to patch it
1283 1284
        let asm = format!("{} {},#{},{}", inst, reg1, src2, self.mangle_block_label(dest_name.clone()));
        self.add_asm_inst_internal(asm, linked_hashmap! {}, linked_hashmap! { id1 => vec![loc1]}, false, ASMBranchTarget::Conditional(dest_name), None);
1285 1286
    }

1287 1288
    // Same as inetnral_binop except extends the second source register
    fn internal_binop_ext(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: &P<Value>, signed: bool, shift: u8) {
1289 1290 1291
        let inst = inst.to_string();
        let ext_s = if signed { "S" } else { "U" };
        let ext_p = match src2.ty.get_int_length() {
1292
            Some(8) => "B",
1293 1294 1295
            Some(16) => "H",
            Some(32) => "W",
            Some(64) => "X",
1296
            _ => panic!("op size: {} dose not support extension", src2.ty.get_int_length().unwrap())
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
        };
        let ext = ext_s.to_string() + "XT" + ext_p;

        trace!("emit: \t{} {}, {} {} {} -> {}", inst, src1, src2, ext, shift, dest);


        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);
        let (reg3, id3, loc3) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1);

        let asm =
1308
            if shift == 0 { format!("{} {},{},{},{}", inst, reg1, reg2, reg3, ext) } else { format!("{} {},{},{},{} #{}", inst, reg1, reg2, reg3, ext, shift) };
1309 1310 1311 1312


        self.add_asm_inst(
            asm,
1313 1314
            ignore_zero_register(id1, vec![loc1]),
            create_hash_map(vec![(id2, loc2), (id3, loc3)]),
1315 1316 1317 1318
            false
        )
    }

1319
    fn internal_binop_imm(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: u64, shift: u8) {
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {} LSL {} -> {}", inst, src1, src2, shift, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);

        let asm = if shift == 0 {
            format!("{} {},{},#{}", inst, reg1, reg2, src2)
        } else {
            format!("{} {},{},#{},LSL #{}", inst, reg1, reg2, src2, shift)
        };

        self.add_asm_inst(
            asm,
1334 1335
            ignore_zero_register(id1, vec![loc1]),
            ignore_zero_register(id2, vec![loc2]),
1336 1337 1338 1339
            false
        )
    }

1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    fn internal_binop_str(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: &str) {
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {} -> {}", inst, src1, src2, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},#{}", inst, reg1, reg2, src2);

        self.add_asm_inst(
            asm,
            ignore_zero_register(id1, vec![loc1]),
            ignore_zero_register(id2, vec![loc2]),
            false
        )
    }

1357
    // dest <= inst(src1, src2)
1358
    fn internal_unop_shift(&mut self, inst: &str, dest: &P<Value>, src: &P<Value>, shift: &str, amount: u8) {
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {} {} -> {}", inst, src, shift, amount, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},{} #{}", inst, reg1, reg2, shift, amount);

        self.add_asm_inst(
            asm,
1369 1370
            ignore_zero_register(id1, vec![loc1]),
            ignore_zero_register(id2, vec![loc2]),
1371 1372 1373 1374
            false
        )
    }

1375
    // dest <= inst(src)
1376
    fn internal_unop(&mut self, inst: &str, dest: &P<Value>, src: &P<Value>) {
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
        let inst = inst.to_string();
        trace!("emit: \t{} {} -> {}", inst, src, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{}", inst, reg1, reg2);

        self.add_asm_inst(
            asm,
1387 1388
            ignore_zero_register(id1, vec![loc1]),
            ignore_zero_register(id2, vec![loc2]),
1389 1390 1391 1392 1393
            false
        )
    }

    // Note: different instructions have different allowed src values
1394
    fn internal_unop_imm(&mut self, inst: &str, dest: &P<Value>, src: u64, shift: u8) {
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        debug_assert!(shift == 0 || shift == 16 || shift == 32 || shift == 48);
        let inst = inst.to_string();
        trace!("emit: \t{} {} LSL {} -> {}", inst, src, shift, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let asm = if shift == 0 {
            format!("{} {},#{}", inst, reg1, src)
        } else {
            format!("{} {},#{},LSL #{}", inst, reg1, src, shift)
        };

        self.add_asm_inst(
            asm,
1408
            ignore_zero_register(id1, vec![loc1]),
1409
            linked_hashmap! {},
1410 1411 1412 1413 1414
            false
        )
    }


1415
    // dest <= inst(src1, src2)
1416
    fn internal_binop(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: &P<Value>) {
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {} -> {}", inst, src1, src2, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);
        let (reg3, id3, loc3) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1);

        let asm = format!("{} {},{},{}", inst, reg1, reg2, reg3);

        self.add_asm_inst(
            asm,
1428 1429
            ignore_zero_register(id1, vec![loc1]),
            create_hash_map(vec![(id2, loc2), (id3, loc3)]),
1430 1431 1432 1433
            false
        )
    }

1434
    // dest <= inst(src1, src2)
1435
    fn internal_binop_shift(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: &P<Value>, shift: &str, amount: u8) {
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {}, {} {} -> {}", inst, src1, src2, shift, amount, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);
        let (reg3, id3, loc3) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1);

        let asm = format!("{} {},{},{},{} #{}", inst, reg1, reg2, reg3, shift, amount);

        self.add_asm_inst(
            asm,
1447 1448
            ignore_zero_register(id1, vec![loc1]),
            create_hash_map(vec![(id2, loc2), (id3, loc3)]),
1449 1450 1451 1452
            false
        )
    }

1453 1454
    // dest <= inst(src1, src2, src3)
    fn internal_ternop(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: &P<Value>, src3: &P<Value>) {
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {}, {} -> {}", inst, src3, src1, src2, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);
        let (reg3, id3, loc3) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1);
        let (reg4, id4, loc4) = self.prepare_reg(src3, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1 + reg3.len() + 1);

        let asm = format!("{} {},{},{},{}", inst, reg1, reg2, reg3, reg4);

        self.add_asm_inst(
            asm,
1467 1468
            ignore_zero_register(id1, vec![loc1]),
            create_hash_map(vec![(id2, loc2), (id3, loc3), (id4, loc4)]),
1469 1470 1471 1472
            false
        )
    }

1473
    fn internal_ternop_imm(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: u64, src3: u64) {
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {}, {} -> {}", inst, src1, src2, src3, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},#{},#{}", inst, reg1, reg2, src2, src3);

        self.add_asm_inst(
            asm,
1484 1485
            ignore_zero_register(id1, vec![loc1]),
            ignore_zero_register(id2, vec![loc2]),
1486 1487 1488 1489
            false
        )
    }

1490
    // PSTATE.<NZCV> = inst(src1, src2)
1491
    fn internal_cmpop(&mut self, inst: &str, src1: &P<Value>, src2: &P<Value>)
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    {
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {}", inst, src1, src2);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{}", inst, reg1, reg2);

        self.add_asm_inst(
            asm,
1503
            linked_hashmap! {},
1504
            create_hash_map(vec![(id1, loc1), (id2, loc2)]),
1505 1506 1507 1508
            false
        )
    }

1509
    // dest <= inst(src1, src2)
1510
    fn internal_cmpop_shift(&mut self, inst: &str, src1: &P<Value>, src2: &P<Value>, shift: &str, amount: u8) {
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
        let inst = inst.to_string();
        trace!("emit: \t{} {},{}, {} {}", inst, src1, src2, shift, amount);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},{} #{}", inst, reg1, reg2, shift, amount);

        self.add_asm_inst(
            asm,
1521
            linked_hashmap! {},
1522
            create_hash_map(vec![(id1, loc1), (id2, loc2)]),
1523 1524 1525 1526
            false
        )
    }

1527 1528
    // Same as inetnral_binop except extends the second source register
    fn internal_cmpop_ext(&mut self, inst: &str, src1: &P<Value>, src2: &P<Value>, signed: bool, shift: u8) {
1529 1530 1531
        let inst = inst.to_string();
        let ext_s = if signed { "S" } else { "U" };
        let ext_p = match src2.ty.get_int_length() {
1532
            Some(8) => "B",
1533 1534 1535
            Some(16) => "H",
            Some(32) => "W",
            Some(64) => "X",
1536
            _ => panic!("op size: {} dose not support extension", src2.ty.get_int_length().unwrap())
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
        };
        let ext = ext_s.to_string() + "XT" + ext_p;

        trace!("emit: \t{} {}, {} {} {}", inst, src1, src2, ext, shift);


        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},{} #{}", inst, reg1, reg2, ext, shift);

        self.add_asm_inst(
            asm,
1550
            linked_hashmap! {},
1551
            create_hash_map(vec![(id1, loc1), (id2, loc2)]),
1552 1553 1554
            false
        )
    }
1555
    // PSTATE.<NZCV> = inst(src1, src2 [<< 12])
1556
    fn internal_cmpop_imm(&mut self, inst: &str, src1: &P<Value>, src2: u64, shift: u8)
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
    {
        let inst = inst.to_string();
        trace!("emit: \t{} {}, {} LSL {}", inst, src1, src2, shift);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);

        let asm = if shift == 0 {
            format!("{} {},#{}", inst, reg1, src2)
        } else {
            format!("{} {},#{},LSL #{}", inst, reg1, src2, shift)
        };

        self.add_asm_inst(
            asm,
1571
            linked_hashmap! { },
1572
            ignore_zero_register(id1, vec![loc1]),
1573 1574 1575 1576
            false
        )
    }

1577
    // PSTATE.<NZCV> = inst(src1, 0.0)
1578
    fn internal_cmpop_f0(&mut self, inst: &str, src1: &P<Value>)
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
    {
        let inst = inst.to_string();
        trace!("emit: \t{} {}, 0.0", inst, src1);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);

        let asm = format!("{} {},#0.0", inst, reg1);

        self.add_asm_inst(
            asm,
1589
            linked_hashmap! { },
1590
            ignore_zero_register(id1, vec![loc1]),
1591 1592 1593 1594
            false
        )
    }

1595
    // dest <= inst<cond>()
1596
    fn internal_cond_op(&mut self, inst: &str, dest: &P<Value>, cond: &str) {
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
        let inst = inst.to_string();
        let cond = cond.to_string();
        trace!("emit: \t{} {} -> {}", inst, cond, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);

        let asm = format!("{} {},{}", inst, reg1, cond);

        self.add_asm_inst(
            asm,
1607
            ignore_zero_register(id1, vec![loc1]),
1608
            linked_hashmap! {},
1609 1610 1611 1612
            false
        )
    }

1613
    // dest <= inst<cond>(src)
1614
    fn internal_cond_unop(&mut self, inst: &str, dest: &P<Value>, src: &P<Value>, cond: &str) {
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
        let inst = inst.to_string();
        let cond = cond.to_string();
        trace!("emit: \t{} {} {} -> {}", inst, cond, src, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},{}", inst, reg1, reg2, cond);

        self.add_asm_inst(
            asm,
1626 1627
            ignore_zero_register(id1, vec![loc1]),
            ignore_zero_register(id2, vec![loc2]),
1628 1629 1630 1631
            false
        )
    }

1632
    // dest <= inst<cond>(src1, src2)
1633
    fn internal_cond_binop(&mut self, inst: &str, dest: &P<Value>, src1: &P<Value>, src2: &P<Value>, cond: &str) {
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
        let inst = inst.to_string();
        let cond = cond.to_string();
        trace!("emit: \t{} {}, {}, {} -> {}", inst, cond, src1, src2, dest);

        let (reg1, id1, loc1) = self.prepare_reg(dest, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src1, inst.len() + 1 + reg1.len() + 1);
        let (reg3, id3, loc3) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1);

        let asm = format!("{} {},{},{},{}", inst, reg1, reg2, reg3, cond);

        self.add_asm_inst(
            asm,
1646 1647
            ignore_zero_register(id1, vec![loc1]),
            create_hash_map(vec![(id2, loc2), (id3, loc3)]),
1648 1649 1650 1651
            false
        )
    }

1652
    // PSTATE.<NZCV> = inst<cond>(src1, src2, flags)
1653
    fn internal_cond_cmpop(&mut self, inst: &str, src1: &P<Value>, src2: &P<Value>, flags: u8, cond: &str)
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
    {
        let inst = inst.to_string();
        let cond = cond.to_string();
        trace!("emit: \t{} {}, {}, {}, {}", inst, src1, src2, flags, cond);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(src2, inst.len() + 1 + reg1.len() + 1);

        let asm = format!("{} {},{},#{},{}", inst, reg1, reg2, flags, cond);

        self.add_asm_inst(
            asm,
1666
            linked_hashmap! {},
1667
            create_hash_map(vec![(id1, loc1), (id2, loc2)]),
1668 1669 1670 1671
            false
        )
    }

1672
    // PSTATE.<NZCV> = inst<cond>(src1, src2, flags)
1673
    fn internal_cond_cmpop_imm(&mut self, inst: &str, src1: &P<Value>, src2: u8, flags: u8, cond: &str)
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    {
        let inst = inst.to_string();
        let cond = cond.to_string();
        trace!("emit: \t{} {}, {}, {}, {}", inst, src1, src2, flags, cond);

        let (reg1, id1, loc1) = self.prepare_reg(src1, inst.len() + 1);

        let asm = format!("{} {},#{},#{},{}", inst, reg1, src2, flags, cond);

        self.add_asm_inst(
            asm,
1685
            linked_hashmap! { },
1686
            ignore_zero_register(id1, vec![loc1]),
1687 1688 1689 1690
            false
        )
    }

1691
    fn internal_load(&mut self, inst: &str, dest: &P<Value>, src: Mem, signed: bool, is_spill_related: bool, is_callee_saved: bool)
1692 1693 1694 1695 1696 1697 1698 1699
    {
        let op_len = primitive_byte_size(&dest.ty);
        let inst = inst.to_string() + if signed {
            match op_len {
                1 => "SB",
                2 => "SH",
                4 => "SW",
                8 => "",
1700
                _ => panic!("unexpected op size: {}", op_len)
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
            }
        } else {
            match op_len {
                1 => "B",
                2 => "H",
                4 => "",
                8 => "",
                _ => panic!("unexpected op size: {}", op_len)
            }
        };

        trace!("emit: \t{} {} -> {}", inst, src, dest);

        let (reg, id, loc) = self.prepare_reg(dest, inst.len() + 1);
1715
        let (mem, uses) = self.prepare_mem(src, inst.len() + 1 + reg.len() + 1);
1716 1717 1718

        let asm = format!("{} {},{}", inst, reg, mem);

1719 1720 1721 1722 1723 1724 1725 1726
        if is_callee_saved {
            self.add_asm_inst_with_callee_saved(
                asm,
                ignore_zero_register(id, vec![loc]),
                uses,
                true,
            )
        } else if is_spill_related {
1727 1728
            self.add_asm_inst_with_spill(
                asm,
1729
                ignore_zero_register(id, vec![loc]),
1730 1731 1732 1733 1734 1735 1736
                uses,
                true,
                SpillMemInfo::Load(src.clone())
            )
        } else {
            self.add_asm_inst(
                asm,
1737
                ignore_zero_register(id, vec![loc]),
1738 1739 1740 1741 1742 1743 1744
                uses,
                true
            )
        }
    }

    // TODO: What to do when src1/src2/stack are the same???
1745
    fn internal_load_pair(&mut self, inst: &str, dest1: &P<Value>, dest2: &P<Value>, src: &P<Value>) {
1746 1747 1748
        let inst = inst.to_string();
        trace!("emit: \t{} {} -> {},{}", inst, src, dest1, dest2);

1749 1750
        let (reg1, id1, loc1) = self.prepare_reg(dest1, inst.len() + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest2, inst.len() + 1 + reg1.len() + 1);
1751
        let (mem, uses) = self.prepare_mem(src, inst.len() + 1 + reg1.len() + 1 + reg2.len() + 1);
1752 1753 1754 1755 1756

        let asm = format!("{} {},{},{}", inst, reg1, reg2, mem);

        self.add_asm_inst(
            asm,
1757
            create_hash_map(vec![(id1, loc1), (id2, loc2)]),
1758 1759 1760 1761 1762
            uses,
            true
        )
    }

1763
    fn internal_store(&mut self, inst: &str, dest: Mem, src: &P<Value>, is_spill_related: bool, is_callee_saved: bool)
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    {
        let op_len = primitive_byte_size(&src.ty);
        let inst = inst.to_string() + match op_len {
            1 => "B",
            2 => "H",
            4 => "",
            8 => "",
            _ => panic!("unexpected op size: {}", op_len)
        };

        trace!("emit: \t{} {} -> {}", inst, src, dest);

        let (reg, id1, loc1) = self.prepare_reg(src, inst.len() + 1);
1777
        let (mem, mut uses) = self.prepare_mem(dest, inst.len() + 1 + reg.len() + 1);
1778 1779 1780

        // the register we used for the memory location is counted as 'use'
        // use the vec from mem as 'use' (push use reg from src to it)
1781 1782 1783
        if is_zero_register_id(id1) {
            // zero register, ignore
        } else if uses.contains_key(&id1) {
1784 1785
            let mut locs = uses.get_mut(&id1).unwrap();
            vec_utils::add_unique(locs, loc1);
1786

1787 1788 1789 1790 1791 1792
        } else {
            uses.insert(id1, vec![loc1]);
        }

        let asm = format!("{} {},{}", inst, reg, mem);

1793 1794 1795
        if is_callee_saved {
            self.add_asm_inst_with_callee_saved(
                asm,
1796
                linked_hashmap! {},
1797 1798 1799 1800
                uses,
                true,
            )
        } else if is_spill_related {
1801 1802
            self.add_asm_inst_with_spill(
                asm,
1803
                linked_hashmap! {},
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
                uses,
                true,
                SpillMemInfo::Store(dest.clone())
            )
        } else {
            self.add_asm_inst(
                asm,
                linked_hashmap! {},
                uses,
                true
            )
        }
    }

1818
    fn internal_store_exclusive(&mut self, inst: &str, dest: Mem, status: &P<Value>, src: &P<Value>)
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
    {
        let inst = inst.to_string();
        let op_len = primitive_byte_size(&src.ty);
        let suffix = match op_len {
            1 => "B",
            2 => "H",
            4 => "",
            8 => "",
            _ => panic!(