asm_backend.rs 31.3 KB
Newer Older
1 2
#![allow(unused_variables)]

3
use compiler::backend;
4
use compiler::backend::x86_64;
5
use compiler::backend::x86_64::CodeGenerator;
6
use vm::machine_code::MachineCode;
7

8 9
use utils::string_utils;

10 11
use ast::ptr::P;
use ast::ir::*;
qinsoon's avatar
qinsoon committed
12
use ast::inst::*;
13

14 15
use std::collections::HashMap;
use std::str;
16
use std::usize;
17
use std::slice::Iter;
18
use std::ops;
19 20 21

struct ASMCode {
    name: MuTag, 
22 23
    code: Vec<ASM>,
    reg_defines: HashMap<MuID, Vec<ASMLocation>>,
24 25 26 27 28 29 30 31
    reg_uses: HashMap<MuID, Vec<ASMLocation>>,
    
    preds: Vec<Vec<usize>>,
    succs: Vec<Vec<usize>>,
    
    idx_to_blk: HashMap<usize, MuTag>,
    blk_to_idx: HashMap<MuTag, usize>,
    cond_branches: HashMap<usize, MuTag>,
32 33
    branches: HashMap<usize, MuTag>,
    
34 35 36 37
    blocks: Vec<MuTag>,
    block_start: HashMap<MuTag, usize>,
    block_range: HashMap<MuTag, ops::Range<usize>>,
    
38 39
    block_livein: HashMap<MuTag, Vec<MuID>>,
    block_liveout: HashMap<MuTag, Vec<MuID>>
40 41
}

42 43 44 45
impl MachineCode for ASMCode {
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }
46
    
47 48 49 50 51 52 53 54
    fn is_move(&self, index: usize) -> bool {
        let inst = self.code.get(index);
        match inst {
            Some(inst) => inst.code.starts_with("mov"),
            None => false
        }
    }
    
qinsoon's avatar
qinsoon committed
55 56 57 58 59 60 61 62
    fn get_succs(&self, index: usize) -> &Vec<usize> {
        &self.succs[index]
    }
    
    fn get_preds(&self, index: usize) -> &Vec<usize> {
        &self.preds[index]
    }
    
63
    fn get_inst_reg_uses(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
64
        &self.code[index].uses
65 66
    }
    
67
    fn get_inst_reg_defines(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
68
        &self.code[index].defines
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
    fn replace_reg(&mut self, from: MuID, to: MuID) {
        let to_reg_tag : MuTag = backend::all_regs()[to].tag;
        let to_reg_string = "%".to_string() + to_reg_tag;
        
        match self.reg_defines.get(&from) {
            Some(defines) => {
                for loc in defines {
                    let ref mut inst_to_patch = self.code[loc.line];
                    for i in 0..loc.len {
                        string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
                    }
                }
            },
            None => {}
        }
        
        match self.reg_uses.get(&from) {
            Some(uses) => {
                for loc in uses {
                    let ref mut inst_to_patch = self.code[loc.line];
                    for i in 0..loc.len {
                        string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
                    }   
                }
            },
            None => {}
        }
    }
    
100 101 102 103 104
    fn set_inst_nop(&mut self, index: usize) {
        self.code.remove(index);
        self.code.insert(index, ASM::nop());
    }
    
105 106 107 108 109 110 111 112 113 114 115
    fn emit(&self) -> Vec<u8> {
        let mut ret = vec![];
        
        for inst in self.code.iter() {
            ret.append(&mut inst.code.clone().into_bytes());
            ret.append(&mut "\n".to_string().into_bytes());
        }
        
        ret
    }
    
116 117
    fn trace_mc(&self) {
        trace!("");
118

119 120
        trace!("code for {}: \n", self.name);
        
121 122
        let n_insts = self.code.len();
        for i in 0..n_insts {
123
            self.trace_inst(i);
124 125
        }
        
126 127 128 129 130 131 132
        trace!("")      
    }
    
    fn trace_inst(&self, i: usize) {
        trace!("#{}\t{:30}\t\tdefine: {:?}\tuses: {:?}\tpred: {:?}\tsucc: {:?}", 
            i, self.code[i].code, self.get_inst_reg_defines(i), self.get_inst_reg_uses(i),
            self.preds[i], self.succs[i]);
133
    }
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    
    fn get_ir_block_livein(&self, block: MuTag) -> Option<&Vec<MuID>> {
        self.block_livein.get(&block)
    }
    
    fn get_ir_block_liveout(&self, block: MuTag) -> Option<&Vec<MuID>> {
        self.block_liveout.get(&block)
    }
    
    fn get_all_blocks(&self) -> &Vec<MuTag> {
        &self.blocks
    }
    
    fn get_block_range(&self, block: MuTag) -> Option<ops::Range<usize>> {
        match self.block_range.get(&block) {
            Some(r) => Some(r.clone()),
            None => None
        }
    }
153 154 155 156 157 158
}

struct ASM {
    code: String,
    defines: Vec<MuID>,
    uses: Vec<MuID>
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
impl ASM {
    fn symbolic(line: String) -> ASM {
        ASM {
            code: line,
            defines: vec![],
            uses: vec![]
        }
    }
    
    fn inst(inst: String, defines: Vec<MuID>, uses: Vec<MuID>) -> ASM {
        ASM {
            code: inst,
            defines: defines,
            uses: uses
        }
    }
    
    fn branch(line: String) -> ASM {
        ASM {
            code: line,
            defines: vec![],
            uses: vec![]
        }
    }
185 186 187 188 189 190 191 192
    
    fn nop() -> ASM {
        ASM {
            code: "".to_string(),
            defines: vec![],
            uses: vec![]
        }
    }
193 194
}

195
#[derive(Clone, Debug)]
196 197 198 199 200 201 202
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize
}

impl ASMLocation {
203 204
    /// the 'line' field will be updated later
    fn new(index: usize, len: usize) -> ASMLocation {
205
        ASMLocation{
206
            line: usize::MAX,
207 208 209 210 211 212
            index: index,
            len: len
        }
    }
}

213
pub struct ASMCodeGen {
214
    cur: Option<Box<ASMCode>>
215 216
}

217
const REG_PLACEHOLDER_LEN : usize = 5;
218 219 220 221 222 223
lazy_static! {
    pub static ref REG_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];
        
        format!("%{}", str::from_utf8(&blank_spaces).unwrap())
    };
224 225 226 227
}

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
228
        ASMCodeGen {
229
            cur: None
230 231 232 233 234 235 236 237 238 239 240
        }
    }
    
    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }
    
    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }
    
241 242 243 244 245 246 247 248 249 250 251 252
    fn line(&self) -> usize {
        self.cur().code.len()
    }
    
    fn add_asm_block_label(&mut self, code: String, block_name: &'static str) {
        let l = self.line();
        self.cur_mut().code.push(ASM::symbolic(code));
        
        self.cur_mut().idx_to_blk.insert(l, block_name);
        self.cur_mut().blk_to_idx.insert(block_name, l);
    }
    
253 254 255 256
    fn add_asm_symbolic(&mut self, code: String){
        self.cur_mut().code.push(ASM::symbolic(code));
    }
    
257 258 259 260
    fn prepare_machine_regs(&self, regs: Iter<P<Value>>) -> Vec<MuID> {
        regs.map(|x| self.prepare_machine_reg(x)).collect()
    } 
    
261
    fn add_asm_call(&mut self, code: String) {
262 263 264 265 266 267 268
        let mut uses : Vec<MuID> = self.prepare_machine_regs(x86_64::ARGUMENT_GPRs.iter());
        uses.append(&mut self.prepare_machine_regs(x86_64::ARGUMENT_FPRs.iter()));
        
        let mut defines : Vec<MuID> = self.prepare_machine_regs(x86_64::RETURN_GPRs.iter());
        defines.append(&mut self.prepare_machine_regs(x86_64::RETURN_FPRs.iter()));
          
        self.add_asm_inst(code, defines, vec![], uses, vec![]);
269 270 271
    }
    
    fn add_asm_ret(&mut self, code: String) {
272 273 274 275
        let mut uses : Vec<MuID> = self.prepare_machine_regs(x86_64::RETURN_GPRs.iter());
        uses.append(&mut self.prepare_machine_regs(x86_64::RETURN_FPRs.iter()));
        
        self.add_asm_inst(code, vec![], vec![], uses, vec![]);
276 277 278 279
    }
    
    fn add_asm_branch(&mut self, code: String, target: &'static str) {
        let l = self.line();
280
        self.cur_mut().code.push(ASM::branch(code));
281 282 283 284 285 286 287 288 289
        
        self.cur_mut().branches.insert(l, target);
    }
    
    fn add_asm_branch2(&mut self, code: String, target: &'static str) {
        let l = self.line();
        self.cur_mut().code.push(ASM::branch(code));
        
        self.cur_mut().cond_branches.insert(l, target);
290 291 292 293 294 295
    }
    
    fn add_asm_inst(
        &mut self, 
        code: String, 
        defines: Vec<MuID>,
296
        mut define_locs: Vec<ASMLocation>, 
297
        uses: Vec<MuID>,
298
        mut use_locs: Vec<ASMLocation>) 
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
        let line = self.line();
        
        trace!("asm: {}", code);
        trace!("     defines: {:?}, def_locs: {:?}", defines, define_locs);
        trace!("     uses: {:?}, use_locs: {:?}", uses, use_locs);
        let mc = self.cur_mut();
       
        // add locations of defined registers
        for i in 0..define_locs.len() {
            let id = defines[i];
            
            // update line in location
            let ref mut loc = define_locs[i];
            loc.line = line;
            
            if mc.reg_defines.contains_key(&id) {
                mc.reg_defines.get_mut(&id).unwrap().push(loc.clone());
            } else {
                mc.reg_defines.insert(id, vec![loc.clone()]);
            }
        }
       
        for i in 0..use_locs.len() {
            let id = uses[i];
            
            // update line in location
            let ref mut loc = use_locs[i];
            loc.line = line;
            
            if mc.reg_uses.contains_key(&id) {
330
                mc.reg_uses.get_mut(&id).unwrap().push(loc.clone());
331
            } else {
332
                mc.reg_uses.insert(id, vec![loc.clone()]);
333 334
            }
        }
335
       
336 337
        // put the instruction
        mc.code.push(ASM::inst(code, defines, uses));
338 339 340 341
    }
    
    fn define_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
342
        
343 344 345 346 347 348 349
        let code = self.cur_mut();
        if code.reg_defines.contains_key(&id) {
            let regs = code.reg_defines.get_mut(&id).unwrap();
            regs.push(loc);
        } else {
            code.reg_defines.insert(id, vec![loc]);
        } 
350 351 352 353 354 355
    }
    
    fn use_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
        
        let code = self.cur_mut();
356 357 358
        if code.reg_uses.contains_key(&id) {
            let reg_uses = code.reg_uses.get_mut(&id).unwrap();
            reg_uses.push(loc);
359
        } else {
360
            code.reg_uses.insert(id, vec![loc]);
361 362 363
        } 
    }
    
364
    fn prepare_reg(&self, op: &P<Value>, loc: usize) -> (String, MuID, ASMLocation) {
365 366 367 368 369 370 371
        let str = self.asm_reg_op(op);
        let len = str.len();
        (str, op.extract_ssa_id().unwrap(), ASMLocation::new(loc, len)) 
    }
    
    fn prepare_machine_reg(&self, op: &P<Value>) -> MuID {
        op.extract_ssa_id().unwrap()
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
    #[allow(unused_assignments)]
    fn prepare_mem(&self, op: &P<Value>, loc: usize) -> (String, Vec<MuID>, Vec<ASMLocation>) {
        let mut ids : Vec<MuID> = vec![];
        let mut locs : Vec<ASMLocation> = vec![];
        let mut result_str : String = "".to_string();
        
        let mut loc_cursor : usize = 0;
        
        match op.v {
            // offset(base,index,scale)
            Value_::Memory(MemoryLocation::Address{ref base, ref offset, ref index, scale}) => {
                // deal with offset
                if offset.is_some() {
                    let offset = offset.as_ref().unwrap();
                    
                    match offset.v {
                        Value_::SSAVar(id) => {
                            // temp as offset
                            let (str, id, loc) = self.prepare_reg(offset, 0);
                            
                            result_str.push_str(&str);
                            ids.push(id);
                            locs.push(loc);
                            
                            loc_cursor += str.len();
                        },
                        Value_::Constant(Constant::Int(val)) => {
                            let str = val.to_string();
                            
                            result_str.push_str(&str);
                            loc_cursor += str.len();
                        },
                        _ => panic!("unexpected offset type: {:?}", offset)
                    }
                }
                
                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 index (ssa or constant)
                if index.is_some() {
                    result_str.push(',');
                    loc_cursor += 1; // plus 1 for ,                    
                    
                    let index = index.as_ref().unwrap();
                    
                    match index.v {
                        Value_::SSAVar(id) => {
                            // temp as offset
                            let (str, id, loc) = self.prepare_reg(index, loc_cursor);
                            
                            result_str.push_str(&str);
                            ids.push(id);
                            locs.push(loc);
                            
                            loc_cursor += str.len();
                        },
                        Value_::Constant(Constant::Int(val)) => {
                            let str = val.to_string();
                            
                            result_str.push_str(&str);
                            loc_cursor += str.len();
                        },
                        _ => panic!("unexpected index type: {:?}", index)
                    }
                    
                    // scale
                    if scale.is_some() {
                        result_str.push(',');
                        loc_cursor += 1;
                        
                        let scale = scale.unwrap();
                        let str = scale.to_string();
                        
                        result_str.push_str(&str);
                        loc_cursor += str.len();
                    }
                }
                
                result_str.push(')');
                loc_cursor += 1;
            },
            Value_::Memory(MemoryLocation::Symbolic{ref base, label}) => {
                result_str.push_str(label);
                loc_cursor += label.len();
                
                if base.is_some() {
                    result_str.push('(');
                    loc_cursor += 1;
                    
                    let (str, id, loc) = self.prepare_reg(base.as_ref().unwrap(), loc_cursor);
                    result_str.push_str(&str);
                    ids.push(id);
                    locs.push(loc);
                    loc_cursor += str.len();
                    
                    result_str.push(')');
                    loc_cursor += 1;                    
                }
            },
            _ => panic!("expect mem location as value")
        }
        
        (result_str, ids, locs)
    }
    
487 488 489 490 491 492 493 494 495 496 497 498 499
    fn asm_reg_op(&self, op: &P<Value>) -> String {
        let id = op.extract_ssa_id().unwrap();
        if id < RESERVED_NODE_IDS_FOR_MACHINE {
            // machine reg
            format!("%{}", op.tag)
        } else {
            // virtual register, use place holder
            REG_PLACEHOLDER.clone()
        }
    }
    
    fn asm_block_label(&self, label: MuTag) -> String {
        format!("{}_{}", self.cur().name, label)
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
    
    fn control_flow_analysis(&mut self) {
        // control flow analysis
        let n_insts = self.line();
        
        let code = self.cur_mut();
        code.preds = vec![vec![]; n_insts];
        code.succs = vec![vec![]; n_insts];
        
        for i in 0..n_insts {
            // determine predecessor - if cur is not block start, its predecessor is previous insts
            let is_block_start = code.idx_to_blk.get(&i);
            if is_block_start.is_none() {
                if i > 0 {
                    code.preds[i].push(i - 1);
                }
            } else {
                // if cur is a branch target, we already set its predecessor
                // if cur is a fall-through block, we set it in a sanity check pass
            }
            
            // determine successor
            let is_branch = code.branches.get(&i);
            if is_branch.is_some() {
                // branch to target
                let target = is_branch.unwrap();
                let target_n = code.blk_to_idx.get(target).unwrap();
                
                // cur inst's succ is target
                code.succs[i].push(*target_n);
                
                // target's pred is cur
                code.preds[*target_n].push(i);
            } else {
                let is_cond_branch = code.cond_branches.get(&i);
                if is_cond_branch.is_some() {
                    // branch to target
                    let target = is_cond_branch.unwrap();
                    let target_n = code.blk_to_idx.get(target).unwrap();
                    
                    // cur insts' succ is target and next inst
                    code.succs[i].push(*target_n);
                    if i < n_insts - 1 {
                        code.succs[i].push(i + 1);
                    }
                    
                    // target's pred is cur
                    code.preds[*target_n].push(i);
                } else {
                    // not branch nor cond branch, succ is next inst
                    if i < n_insts - 1 {
                        code.succs[i].push(i + 1);
                    }
                }
            } 
        }
        
        // a sanity check for fallthrough blocks
        for i in 0..n_insts {
            if i != 0 && code.preds[i].len() == 0 {
                code.preds[i].push(i - 1);
            }
        }        
    }
565 566 567
}

impl CodeGenerator for ASMCodeGen {
568
    fn start_code(&mut self, func_name: MuTag) {
569
        self.cur = Some(Box::new(ASMCode {
570 571
                name: func_name,
                code: vec![],
572
                reg_defines: HashMap::new(),
573 574 575 576 577 578 579 580
                reg_uses: HashMap::new(),
                
                preds: vec![],
                succs: vec![],
                
                idx_to_blk: HashMap::new(),
                blk_to_idx: HashMap::new(),
                cond_branches: HashMap::new(),
581 582
                branches: HashMap::new(),
                
583 584 585 586
                blocks: vec![],
                block_start: HashMap::new(),
                block_range: HashMap::new(),
                
587 588
                block_livein: HashMap::new(),
                block_liveout: HashMap::new()
589
            }));
590
        
qinsoon's avatar
qinsoon committed
591
        // to link with C sources via gcc
592
        self.add_asm_symbolic(format!(".globl {}", func_name));
qinsoon's avatar
qinsoon committed
593 594 595
        self.add_asm_symbolic(format!(".globl _{}", func_name));
        self.add_asm_symbolic(format!("{}:", func_name));
        self.add_asm_symbolic(format!("_{}:", func_name));
596 597
    }
    
598 599 600
    fn finish_code(&mut self) -> Box<MachineCode> {
        self.control_flow_analysis();
        self.cur.take().unwrap()
601 602 603 604 605 606 607 608 609
    }
    
    fn print_cur_code(&self) {
        println!("");
        
        if self.cur.is_some() {
            let code = self.cur.as_ref().unwrap();
            
            println!("code for {}: ", code.name);
610 611 612 613
            let n_insts = code.code.len();
            for i in 0..n_insts {
                let ref line = code.code[i];
                println!("#{}\t{}", i, line.code);
614 615 616 617 618 619 620 621 622
            }
        } else {
            println!("no current code");
        }
        
        println!("");
    }
    
    fn start_block(&mut self, block_name: MuTag) {
623 624
        let label = format!("{}:", self.asm_block_label(block_name));        
        self.add_asm_block_label(label, block_name);
625 626 627 628 629 630 631 632 633 634 635
        self.cur_mut().blocks.push(block_name);
        
        let start = self.line();
        self.cur_mut().block_start.insert(block_name, start);
    }
    
    fn end_block(&mut self, block_name: MuTag) {
        let start : usize = *self.cur().block_start.get(&block_name).unwrap();
        let end : usize = self.line();
        
        self.cur_mut().block_range.insert(block_name, (start..end));
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
    fn set_block_livein(&mut self, block_name: MuTag, live_in: &Vec<P<Value>>) {
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_livein.contains_key(&block_name) {
                cur.block_livein.insert(block_name, vec![]);
            } else {
                panic!("seems we are inserting livein to block {} twice", block_name);
            }
            
            cur.block_livein.get_mut(&block_name).unwrap()
        };
        
        for value in live_in {
            res.push(value.extract_ssa_id().unwrap());
        }
    }
    
    fn set_block_liveout(&mut self, block_name: MuTag, live_out: &Vec<P<Value>>) {
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_liveout.contains_key(&block_name) {
                cur.block_liveout.insert(block_name, vec![]);
            } else {
                panic!("seems we are inserting livein to block {} twice", block_name);
            }
            
            cur.block_liveout.get_mut(&block_name).unwrap()
        };
        
        for value in live_out {
            match value.extract_ssa_id() {
                Some(id) => res.push(id),
                None => {}
            }
        }        
    }
    
677
    fn emit_cmp_r64_r64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
678
        trace!("emit: cmp {} {}", op1, op2);
679
        
680 681
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(op2, 4 + 1 + reg1.len() + 1);
682
        
qinsoon's avatar
qinsoon committed
683
        let asm = format!("cmpq {},{}", reg1, reg2);
684
        
685 686 687 688 689 690 691
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1, id2],
            vec![loc1, loc2]
        );
692 693
    }
    
qinsoon's avatar
qinsoon committed
694 695
    fn emit_cmp_r64_imm32(&mut self, op1: &P<Value>, op2: u32) {
        trace!("emit: cmp {} {}", op1, op2);
696
        
697
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1 + 1 + op2.to_string().len() + 1);
698
        
qinsoon's avatar
qinsoon committed
699
        let asm = format!("cmpq ${},{}", op2, reg1);
700
        
701 702 703 704 705 706 707
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1],
            vec![loc1]
        )
708 709 710
    }
    
    fn emit_cmp_r64_mem64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
711
        trace!("emit: cmp {} {}", op1, op2);
712
        unimplemented!()
713 714
    }
    
qinsoon's avatar
qinsoon committed
715 716
    fn emit_mov_r64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: mov {} -> {}", src, dest);
717
        
718
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
719
        
qinsoon's avatar
qinsoon committed
720
        let asm = format!("movq ${},{}", src, reg1);
721
        
722 723 724
        self.add_asm_inst(
            asm,
            vec![id1],
725 726 727
            vec![loc1],
            vec![],
            vec![]
728
        )
729 730 731
    }
    
    fn emit_mov_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
qinsoon's avatar
qinsoon committed
732
        trace!("emit: mov {} -> {}", src, dest);
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 769 770 771 772 773 774 775 776 777 778 779 780 781 782
        
        let (mem, id1, loc1) = self.prepare_mem(src, 4 + 1);
        let (reg, id2, loc2) = self.prepare_reg(dest, 4 + 1 + mem.len() + 1);
        
        let asm = format!("movq {},{}", mem, reg);
        
        self.add_asm_inst(
            asm,
            vec![id2],
            vec![loc2],
            id1,
            loc1
        )
    }
    
    fn emit_mov_mem64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: mov {} -> {}", src, dest);
        
        let (reg, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (mem, mut id2, mut loc2) = self.prepare_mem(dest, 4 + 1 + reg.len() + 1);
        
        // the register we used for the memory location is counted as 'use'
        id2.push(id1);
        loc2.push(loc1);
        
        let asm = format!("movq {},{}", reg, mem);
        
        self.add_asm_inst(
            asm,
            vec![], // not defining anything (write to memory)
            vec![],
            id2,
            loc2
        )
    }
    
    fn emit_mov_mem64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: mov {} -> {}", src, dest);
        
        let (mem, id, loc) = self.prepare_mem(dest, 4 + 1 + 1 + src.to_string().len() + 1);
        
        let asm = format!("movq ${},{}", src, mem);
        
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            id,
            loc
        )
qinsoon's avatar
qinsoon committed
783 784 785 786
    }
    
    fn emit_mov_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: mov {} -> {}", src, dest);
787
        
788 789
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
790
        
qinsoon's avatar
qinsoon committed
791
        let asm = format!("movq {},{}", reg1, reg2);
792
        
793 794 795
        self.add_asm_inst(
            asm,
            vec![id2],
796 797 798
            vec![loc2],
            vec![id1],
            vec![loc1]
799
        )
qinsoon's avatar
qinsoon committed
800 801 802 803
    }
    
    fn emit_add_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
804
        
805 806
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
807
        
qinsoon's avatar
qinsoon committed
808
        let asm = format!("addq {},{}", reg1, reg2);
809
        
810 811
        self.add_asm_inst(
            asm,
812 813
            vec![id2],
            vec![loc2.clone()],
814 815 816
            vec![id1, id2],
            vec![loc1, loc2]
        )
qinsoon's avatar
qinsoon committed
817 818 819 820
    }
    
    fn emit_add_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
821
        unimplemented!()
qinsoon's avatar
qinsoon committed
822 823 824 825
    }
    
    fn emit_add_r64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
826
        
827
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1);
828
        
qinsoon's avatar
qinsoon committed
829
        let asm = format!("addq {},${}", src, reg1);
830
        
831 832 833 834 835 836 837
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
            vec![loc1]
        )
qinsoon's avatar
qinsoon committed
838 839 840 841
    }
    
    fn emit_sub_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
842
        
843 844
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
845
        
qinsoon's avatar
qinsoon committed
846
        let asm = format!("subq {},{}", reg1, reg2);
847
        
848 849
        self.add_asm_inst(
            asm,
850 851
            vec![id2],
            vec![loc2.clone()],
852 853 854
            vec![id1, id2],
            vec![loc1, loc2]
        )        
qinsoon's avatar
qinsoon committed
855 856 857 858
    }
    
    fn emit_sub_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
859
        unimplemented!()
qinsoon's avatar
qinsoon committed
860 861 862 863
    }
    
    fn emit_sub_r64_imm32(&mut self, dest: &P<Value>, src: u32) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
864
        
865
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
866
        
qinsoon's avatar
qinsoon committed
867
        let asm = format!("subq ${},{}", src, reg1);
868
        
869 870 871 872 873 874 875
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
            vec![loc1]
        )        
qinsoon's avatar
qinsoon committed
876 877
    }
    
878
    fn emit_mul_r64(&mut self, src: &P<Value>) {
879
        trace!("emit: mul rax, {} -> (rdx, rax)", src);
880
        
881
        let (reg, id, loc) = self.prepare_reg(src, 3 + 1);
882 883
        let rax = self.prepare_machine_reg(&x86_64::RAX);
        let rdx = self.prepare_machine_reg(&x86_64::RDX);
884 885 886
        
        let asm = format!("mul {}", reg);
        
887 888 889 890 891 892 893
        self.add_asm_inst(
            asm,
            vec![rax, rdx],
            vec![],
            vec![id, rax],
            vec![loc]
        )
894 895 896 897
    }
    
    fn emit_mul_mem64(&mut self, src: &P<Value>) {
        trace!("emit: mul rax, {} -> rax", src);
898
        unimplemented!()
899 900
    }
    
qinsoon's avatar
qinsoon committed
901 902
    fn emit_jmp(&mut self, dest: &Destination) {
        trace!("emit: jmp {}", dest.target);
903 904 905
        
        // symbolic label, we dont need to patch it
        let asm = format!("jmp {}", self.asm_block_label(dest.target));
906
        self.add_asm_branch(asm, dest.target)
qinsoon's avatar
qinsoon committed
907 908 909 910
    }
    
    fn emit_je(&mut self, dest: &Destination) {
        trace!("emit: je {}", dest.target);
911 912
        
        let asm = format!("je {}", self.asm_block_label(dest.target));
913
        self.add_asm_branch2(asm, dest.target);        
qinsoon's avatar
qinsoon committed
914 915 916 917
    }
    
    fn emit_jne(&mut self, dest: &Destination) {
        trace!("emit: jne {}", dest.target);
918 919
        
        let asm = format!("jne {}", self.asm_block_label(dest.target));
920
        self.add_asm_branch2(asm, dest.target);
qinsoon's avatar
qinsoon committed
921 922 923 924
    }
    
    fn emit_ja(&mut self, dest: &Destination) {
        trace!("emit: ja {}", dest.target);
925 926
        
        let asm = format!("ja {}", self.asm_block_label(dest.target));
927
        self.add_asm_branch2(asm, dest.target);
qinsoon's avatar
qinsoon committed
928 929 930 931
    }
    
    fn emit_jae(&mut self, dest: &Destination) {
        trace!("emit: jae {}", dest.target);
932 933
        
        let asm = format!("jae {}", self.asm_block_label(dest.target));
934
        self.add_asm_branch2(asm, dest.target);        
qinsoon's avatar
qinsoon committed
935 936 937 938
    }
    
    fn emit_jb(&mut self, dest: &Destination) {
        trace!("emit: jb {}", dest.target);
939 940
        
        let asm = format!("jb {}", self.asm_block_label(dest.target));
941
        self.add_asm_branch2(asm, dest.target);
qinsoon's avatar
qinsoon committed
942 943 944 945
    }
    
    fn emit_jbe(&mut self, dest: &Destination) {
        trace!("emit: jbe {}", dest.target);
946 947
        
        let asm = format!("jbe {}", self.asm_block_label(dest.target));
948
        self.add_asm_branch2(asm, dest.target);        
qinsoon's avatar
qinsoon committed
949 950
    }
    
951 952
    fn emit_jg(&mut self, dest: &Destination) {
        trace!("emit: jg {}", dest.target);
953 954
        
        let asm = format!("jg {}", self.asm_block_label(dest.target));
955
        self.add_asm_branch2(asm, dest.target);        
956 957 958 959
    }
    
    fn emit_jge(&mut self, dest: &Destination) {
        trace!("emit: jge {}", dest.target);
960 961
        
        let asm = format!("jge {}", self.asm_block_label(dest.target));
962
        self.add_asm_branch2(asm, dest.target);        
963 964 965 966
    }
    
    fn emit_jl(&mut self, dest: &Destination) {
        trace!("emit: jl {}", dest.target);
967 968
        
        let asm = format!("jl {}", self.asm_block_label(dest.target));
969
        self.add_asm_branch2(asm, dest.target);        
970 971 972 973
    }
    
    fn emit_jle(&mut self, dest: &Destination) {
        trace!("emit: jle {}", dest.target);
974 975
        
        let asm = format!("jle {}", self.asm_block_label(dest.target));
976
        self.add_asm_branch2(asm, dest.target);        
977 978
    }    
    
979 980
    fn emit_call_near_rel32(&mut self, func: MuTag) {
        trace!("emit: call {}", func);
981 982
        
        let asm = format!("call {}", func);
983
        self.add_asm_call(asm);
984 985
        
        // FIXME: call interferes with machine registers
986 987 988 989
    }
    
    fn emit_call_near_r64(&mut self, func: &P<Value>) {
        trace!("emit: call {}", func);
990
        unimplemented!()
991 992 993
    }
    
    fn emit_call_near_mem64(&mut self, func: &P<Value>) {
qinsoon's avatar
qinsoon committed
994
        trace!("emit: call {}", func);
995
        unimplemented!()
qinsoon's avatar
qinsoon committed
996 997 998 999
    }
    
    fn emit_ret(&mut self) {
        trace!("emit: ret");
1000 1001
        
        let asm = format!("ret");
1002
        self.add_asm_ret(asm);
1003
    }
1004
    
1005
    fn emit_push_r64(&mut self, src: &P<Value>) {
1006
        trace!("emit: push {}", src);
1007
        
1008
        let (reg, id, loc) = self.prepare_reg(src, 5 + 1);
1009
        let rsp = self.prepare_machine_reg(&x86_64::RSP);
1010 1011 1012
        
        let asm = format!("pushq {}", reg);
        
1013 1014
        self.add_asm_inst(
            asm,
1015
            vec![rsp],
1016 1017 1018
            vec![],
            vec![id, rsp],
            vec![loc]
1019
        )
1020 1021
    }
    
1022
    fn emit_pop_r64(&mut self, dest: &P<Value>) {
1023
        trace!("emit: pop {}", dest);
1024
        
1025
        let (reg, id, loc) = self.prepare_reg(dest, 4 + 1);
1026
        let rsp = self.prepare_machine_reg(&x86_64::RSP);
1027 1028 1029
        
        let asm = format!("popq {}", reg);
        
1030 1031
        self.add_asm_inst(
            asm,
1032
            vec![id, rsp],
1033
            vec![loc.clone()],
1034 1035
            vec![rsp],
            vec![]
1036
        )        
1037
    }    
1038
}