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

3
use compiler::backend;
4 5
use compiler::backend::AOT_EMIT_CONTEXT_FILE;
use compiler::backend::AOT_EMIT_DIR;
qinsoon's avatar
qinsoon committed
6
use compiler::backend::RegGroup;
qinsoon's avatar
qinsoon committed
7
use utils::ByteSize;
8
use compiler::backend::x86_64;
9
use compiler::backend::x86_64::CodeGenerator;
qinsoon's avatar
qinsoon committed
10
use compiler::machine_code::MachineCode;
qinsoon's avatar
qinsoon committed
11
use vm::VM;
qinsoon's avatar
qinsoon committed
12
use runtime::ValueLocation;
13

qinsoon's avatar
qinsoon committed
14
use utils::vec_utils;
15
use utils::string_utils;
16 17 18
use ast::ptr::P;
use ast::ir::*;

19 20
use std::collections::HashMap;
use std::str;
21
use std::usize;
22
use std::slice::Iter;
23
use std::ops;
24 25

struct ASMCode {
qinsoon's avatar
qinsoon committed
26
    name: MuName, 
27 28
    code: Vec<ASM>,
    reg_defines: HashMap<MuID, Vec<ASMLocation>>,
29 30
    reg_uses: HashMap<MuID, Vec<ASMLocation>>,
    
qinsoon's avatar
qinsoon committed
31 32
    mem_op_used: HashMap<usize, bool>,
    
33 34 35
    preds: Vec<Vec<usize>>,
    succs: Vec<Vec<usize>>,
    
qinsoon's avatar
qinsoon committed
36 37 38 39
    idx_to_blk: HashMap<usize, MuName>,
    blk_to_idx: HashMap<MuName, usize>,
    cond_branches: HashMap<usize, MuName>,
    branches: HashMap<usize, MuName>,
40
    
qinsoon's avatar
qinsoon committed
41 42 43
    blocks: Vec<MuName>,
    block_start: HashMap<MuName, usize>,
    block_range: HashMap<MuName, ops::Range<usize>>,
44
    
qinsoon's avatar
qinsoon committed
45 46
    block_livein: HashMap<MuName, Vec<MuID>>,
    block_liveout: HashMap<MuName, Vec<MuID>>
47 48
}

qinsoon's avatar
qinsoon committed
49 50 51
unsafe impl Send for ASMCode {} 
unsafe impl Sync for ASMCode {}

52 53 54 55
impl MachineCode for ASMCode {
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }
56
    
57 58 59 60 61 62 63 64
    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
65 66 67 68
    fn is_using_mem_op(&self, index: usize) -> bool {
        *self.mem_op_used.get(&index).unwrap()
    }
    
qinsoon's avatar
qinsoon committed
69 70 71 72 73 74 75 76
    fn get_succs(&self, index: usize) -> &Vec<usize> {
        &self.succs[index]
    }
    
    fn get_preds(&self, index: usize) -> &Vec<usize> {
        &self.preds[index]
    }
    
77
    fn get_inst_reg_uses(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
78
        &self.code[index].uses
79 80
    }
    
81
    fn get_inst_reg_defines(&self, index: usize) -> &Vec<MuID> {
qinsoon's avatar
qinsoon committed
82
        &self.code[index].defines
83
    }
84
    
85
    fn replace_reg(&mut self, from: MuID, to: MuID) {
86 87 88 89
        let to_reg_tag : MuName = match backend::all_regs().get(&to) {
            Some(reg) => reg.name().unwrap(),
            None => panic!("expecting a machine register, but we are required to replace to {}", to)
        };
90
        let to_reg_string = "%".to_string() + &to_reg_tag;
91 92 93 94 95 96 97 98 99 100 101 102
        
        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 => {}
        }
103

104 105 106 107 108 109
        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());
110
                    }
111 112 113 114 115
                }
            },
            None => {}
        }
    }
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

    fn replace_reg_for_inst(&mut self, from: MuID, to: MuID, inst: usize) {
        let to_reg_string : MuName = match backend::all_regs().get(&to) {
            Some(ref machine_reg) => {
                let name = machine_reg.name().unwrap();
                "%".to_string() + &name
            },
            None => REG_PLACEHOLDER.clone()
        };

        {
            let asm = &mut self.code[inst];
            // if this reg is defined, replace the define
            if asm.defines.contains(&from) {
                vec_utils::remove_value(&mut asm.defines, from);
                asm.defines.push(to);
            }
            // if this reg is used, replace the use
            if asm.uses.contains(&from) {
                vec_utils::remove_value(&mut asm.uses, from);
                asm.uses.push(to);
            }
        }

        // replace the define
        // replace code
        match self.reg_defines.get(&from) {
            Some(defines) => {
                for loc in defines {
                    if loc.line == inst {
                        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 => {}
        }
        // replace info
        let replaced_define = match self.reg_defines.get_mut(&from) {
            Some(defines) => {
                Some(vec_utils::remove_value_if_true(defines, |x| {x.line == inst}))
            },
            None => None
        };
        match replaced_define {
            Some(mut defines) => {
                if self.reg_defines.contains_key(&to) {
                    self.reg_defines.get_mut(&to).unwrap().append(&mut defines);
                } else {
                    self.reg_defines.insert(to, defines);
                }
            }
            None => {}
        };

        // replace the use
        // replace code
        match self.reg_uses.get(&from) {
            Some(uses) => {
                for loc in uses {
                    if loc.line == inst {
                        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 => {}
        }
        // replace info
        let replaced_use = match self.reg_uses.get_mut(&from) {
            Some(uses) => {
                Some(vec_utils::remove_value_if_true(uses, |x| {x.line == inst}))
            },
            None => None
        };
        match replaced_use {
            Some(mut uses) => {
                if self.reg_uses.contains_key(&to) {
                    self.reg_uses.get_mut(&to).unwrap().append(&mut uses);
                } else {
                    self.reg_uses.insert(to, uses);
                }
            }
            None => {}
        };
    }
206
    
207
    fn set_inst_nop(&mut self, index: usize) {
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
        // FIXME: changing these info is inefficient - plus we probably do not need to

        // remove any reg use of this instruction
        // clone the vec otherwise since we need to borrow 'self' again
        for reg in self.get_inst_reg_uses(index).to_vec() {
            let mut locs = self.reg_uses.get_mut(&reg).unwrap();
            let mut new_locs : Vec<ASMLocation> = vec![];

            while !locs.is_empty() {
                let loc = locs.pop().unwrap();
                if loc.line != index {
                    new_locs.push(loc);
                }
            }

            debug_assert!(locs.is_empty());
            locs.append(&mut new_locs);
        }

        // remove any reg define of this instruction
        for reg in self.get_inst_reg_defines(index).to_vec() {
            let mut locs = self.reg_defines.get_mut(&reg).unwrap();
            let mut new_locs : Vec<ASMLocation> = vec![];

            while !locs.is_empty() {
                let loc = locs.pop().unwrap();
                if loc.line != index {
                    new_locs.push(loc);
                }
            }

            debug_assert!(locs.is_empty());
            locs.append(&mut new_locs);
        }

        // nop doesnt use memop
        self.mem_op_used.insert(index, false);

246 247 248 249
        self.code.remove(index);
        self.code.insert(index, ASM::nop());
    }
    
250 251 252 253 254 255 256 257 258 259 260
    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
    }
    
261 262
    fn trace_mc(&self) {
        trace!("");
263

264 265
        trace!("code for {}: \n", self.name);
        
266 267
        let n_insts = self.code.len();
        for i in 0..n_insts {
268
            self.trace_inst(i);
269 270
        }
        
271 272 273 274 275 276 277
        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]);
278
    }
279
    
280 281
    fn get_ir_block_livein(&self, block: &str) -> Option<&Vec<MuID>> {
        self.block_livein.get(&block.to_string())
282 283
    }
    
284 285
    fn get_ir_block_liveout(&self, block: &str) -> Option<&Vec<MuID>> {
        self.block_liveout.get(&block.to_string())
286 287
    }
    
288 289 290 291 292 293 294 295
    fn set_ir_block_livein(&mut self, block: &str, set: Vec<MuID>) {
        self.block_livein.insert(block.to_string(), set);
    }
    
    fn set_ir_block_liveout(&mut self, block: &str, set: Vec<MuID>) {
        self.block_liveout.insert(block.to_string(), set);
    }
    
qinsoon's avatar
qinsoon committed
296
    fn get_all_blocks(&self) -> &Vec<MuName> {
297 298 299
        &self.blocks
    }
    
300 301
    fn get_block_range(&self, block: &str) -> Option<ops::Range<usize>> {
        match self.block_range.get(&block.to_string()) {
302 303 304 305
            Some(r) => Some(r.clone()),
            None => None
        }
    }
306 307 308 309 310 311
}

struct ASM {
    code: String,
    defines: Vec<MuID>,
    uses: Vec<MuID>
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
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![]
        }
    }
338 339 340 341 342 343 344 345
    
    fn nop() -> ASM {
        ASM {
            code: "".to_string(),
            defines: vec![],
            uses: vec![]
        }
    }
346 347
}

348
#[derive(Clone, Debug)]
349 350 351 352 353 354 355
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize
}

impl ASMLocation {
356 357
    /// the 'line' field will be updated later
    fn new(index: usize, len: usize) -> ASMLocation {
358
        ASMLocation{
359
            line: usize::MAX,
360 361 362 363 364 365
            index: index,
            len: len
        }
    }
}

366
pub struct ASMCodeGen {
367
    cur: Option<Box<ASMCode>>
368 369
}

370
const REG_PLACEHOLDER_LEN : usize = 5;
371 372 373 374 375 376
lazy_static! {
    pub static ref REG_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];
        
        format!("%{}", str::from_utf8(&blank_spaces).unwrap())
    };
377 378 379 380
}

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
381
        ASMCodeGen {
382
            cur: None
383 384 385 386 387 388 389 390 391 392 393
        }
    }
    
    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }
    
    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }
    
394 395 396 397
    fn line(&self) -> usize {
        self.cur().code.len()
    }
    
398 399 400 401 402
    fn add_asm_label(&mut self, code: String) {
        let l = self.line();
        self.cur_mut().code.push(ASM::symbolic(code));
    }
    
403
    fn add_asm_block_label(&mut self, code: String, block_name: MuName) {
404 405 406
        let l = self.line();
        self.cur_mut().code.push(ASM::symbolic(code));
        
407
        self.cur_mut().idx_to_blk.insert(l, block_name.clone());
408 409 410
        self.cur_mut().blk_to_idx.insert(block_name, l);
    }
    
411 412 413 414
    fn add_asm_symbolic(&mut self, code: String){
        self.cur_mut().code.push(ASM::symbolic(code));
    }
    
415 416 417 418
    fn prepare_machine_regs(&self, regs: Iter<P<Value>>) -> Vec<MuID> {
        regs.map(|x| self.prepare_machine_reg(x)).collect()
    } 
    
419
    fn add_asm_call(&mut self, code: String) {
qinsoon's avatar
qinsoon committed
420
        // a call instruction will use all the argument registers
421 422
        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()));
qinsoon's avatar
qinsoon committed
423 424

        // defines: return registers
425 426
        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()));
qinsoon's avatar
qinsoon committed
427 428 429
        // defines: caller saved registers
        vec_utils::append_unique(&mut defines, &mut self.prepare_machine_regs(x86_64::CALLER_SAVED_GPRs.iter()));
        vec_utils::append_unique(&mut defines, &mut self.prepare_machine_regs(x86_64::CALLER_SAVED_FPRs.iter()));
430
          
qinsoon's avatar
qinsoon committed
431
        self.add_asm_inst(code, defines, vec![], uses, vec![], false);
432 433 434
    }
    
    fn add_asm_ret(&mut self, code: String) {
435 436 437
        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()));
        
qinsoon's avatar
qinsoon committed
438
        self.add_asm_inst(code, vec![], vec![], uses, vec![], false);
439 440
    }
    
441
    fn add_asm_branch(&mut self, code: String, target: MuName) {
442 443
        let l = self.line();
        self.cur_mut().branches.insert(l, target);
qinsoon's avatar
qinsoon committed
444 445
        
        self.add_asm_inst(code, vec![], vec![], vec![], vec![], false);
446 447
    }
    
448
    fn add_asm_branch2(&mut self, code: String, target: MuName) {
449 450
        let l = self.line();
        self.cur_mut().cond_branches.insert(l, target);
qinsoon's avatar
qinsoon committed
451 452
        
        self.add_asm_inst(code, vec![], vec![], vec![], vec![], false);
453 454 455 456 457 458
    }
    
    fn add_asm_inst(
        &mut self, 
        code: String, 
        defines: Vec<MuID>,
459
        mut define_locs: Vec<ASMLocation>, 
460
        uses: Vec<MuID>,
qinsoon's avatar
qinsoon committed
461 462
        mut use_locs: Vec<ASMLocation>,
        is_using_mem_op: bool) 
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
        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) {
494
                mc.reg_uses.get_mut(&id).unwrap().push(loc.clone());
495
            } else {
496
                mc.reg_uses.insert(id, vec![loc.clone()]);
497 498
            }
        }
499
       
500 501
        // put the instruction
        mc.code.push(ASM::inst(code, defines, uses));
qinsoon's avatar
qinsoon committed
502
        mc.mem_op_used.insert(line, is_using_mem_op);
503 504 505 506
    }
    
    fn define_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
507
        
508 509 510 511 512 513 514
        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]);
        } 
515 516 517 518 519 520
    }
    
    fn use_reg(&mut self, reg: &P<Value>, loc: ASMLocation) {
        let id = reg.extract_ssa_id().unwrap();
        
        let code = self.cur_mut();
521 522 523
        if code.reg_uses.contains_key(&id) {
            let reg_uses = code.reg_uses.get_mut(&id).unwrap();
            reg_uses.push(loc);
524
        } else {
525
            code.reg_uses.insert(id, vec![loc]);
526 527 528
        } 
    }
    
529
    fn prepare_reg(&self, op: &P<Value>, loc: usize) -> (String, MuID, ASMLocation) {
530 531 532 533 534 535 536
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting register op")
            }
        }
        
537 538 539 540 541 542
        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 {
543 544 545 546 547 548 549
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting machine register op")
            }
        }        
        
550
        op.extract_ssa_id().unwrap()
551
    }
552
    
553 554
    #[allow(unused_assignments)]
    fn prepare_mem(&self, op: &P<Value>, loc: usize) -> (String, Vec<MuID>, Vec<ASMLocation>) {
555 556 557 558 559 560 561
        if cfg!(debug_assertions) {
            match op.v {
                Value_::Memory(_) => {},
                _ => panic!("expecting register op")
            }
        }        
        
562 563 564 565
        let mut ids : Vec<MuID> = vec![];
        let mut locs : Vec<ASMLocation> = vec![];
        let mut result_str : String = "".to_string();
        
566
        let mut loc_cursor : usize = loc;
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 637 638 639 640 641 642 643 644 645 646 647 648
        
        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;
            },
649 650
            Value_::Memory(MemoryLocation::Symbolic{ref base, ref label}) => {
                result_str.push_str(&symbol(label.clone()));
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
                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)
    }
    
673 674
    fn asm_reg_op(&self, op: &P<Value>) -> String {
        let id = op.extract_ssa_id().unwrap();
qinsoon's avatar
qinsoon committed
675
        if id < MACHINE_ID_END {
676
            // machine reg
677
            format!("%{}", op.name().unwrap())
678 679 680 681 682 683
        } else {
            // virtual register, use place holder
            REG_PLACEHOLDER.clone()
        }
    }
    
qinsoon's avatar
qinsoon committed
684
    fn asm_block_label(&self, label: MuName) -> String {
685
        symbol(format!("{}_{}", self.cur().name, label))
686
    }
687 688 689 690 691 692 693 694 695 696 697 698 699 700
    
    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 {
701 702
                    trace!("inst {}: not a block start", i);
                    trace!("inst {}: set PREDS as previous inst {}", i, i-1);
703 704 705 706 707 708 709 710 711 712 713 714
                    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();
715 716
                trace!("inst {}: is a branch to {}", i, target);
                                
717
                let target_n = code.blk_to_idx.get(target).unwrap();
718
                trace!("inst {}: branch target index is {}", i, target_n);
719 720
                
                // cur inst's succ is target
721
                trace!("inst {}: set SUCCS as branch target {}", i, target_n);
722 723 724
                code.succs[i].push(*target_n);
                
                // target's pred is cur
725
                trace!("inst {}: set PREDS as branch source {}", target_n, i);
726 727 728 729 730 731
                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();
732 733
                    trace!("inst {}: is a cond branch to {}", i, target);
                    
734
                    let target_n = code.blk_to_idx.get(target).unwrap();
735
                    trace!("inst {}: branch target index is {}", i, target_n);
736 737 738
                    
                    // cur insts' succ is target and next inst
                    code.succs[i].push(*target_n);
739
                    trace!("inst {}: set SUCCS as branch target {}", i, target_n);
740
                    if i < n_insts - 1 {
741
                        trace!("inst {}: set SUCCS as next inst", i + 1);                        
742 743 744 745 746
                        code.succs[i].push(i + 1);
                    }
                    
                    // target's pred is cur
                    code.preds[*target_n].push(i);
747
                    trace!("inst {}: set PREDS as {}", *target_n, i);
748 749
                } else {
                    // not branch nor cond branch, succ is next inst
750
                    trace!("inst {}: not a branch inst", i);
751
                    if i < n_insts - 1 {
752
                        trace!("inst {}: set SUCCS as next inst {}", i, i + 1);
753 754 755 756 757 758 759 760 761 762 763 764 765
                        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);
            }
        }        
    }
766 767 768
}

impl CodeGenerator for ASMCodeGen {
qinsoon's avatar
qinsoon committed
769
    fn start_code(&mut self, func_name: MuName) -> ValueLocation {
770
        self.cur = Some(Box::new(ASMCode {
771
                name: func_name.clone(),
772
                code: vec![],
773
                reg_defines: HashMap::new(),
774 775
                reg_uses: HashMap::new(),
                
qinsoon's avatar
qinsoon committed
776 777
                mem_op_used: HashMap::new(),
                
778 779 780 781 782 783
                preds: vec![],
                succs: vec![],
                
                idx_to_blk: HashMap::new(),
                blk_to_idx: HashMap::new(),
                cond_branches: HashMap::new(),
784 785
                branches: HashMap::new(),
                
786 787 788 789
                blocks: vec![],
                block_start: HashMap::new(),
                block_range: HashMap::new(),
                
790 791
                block_livein: HashMap::new(),
                block_liveout: HashMap::new()
792
            }));
793
        
qinsoon's avatar
qinsoon committed
794
        // to link with C sources via gcc
qinsoon's avatar
qinsoon committed
795 796 797 798
        let func_symbol = symbol(func_name.clone());
        self.add_asm_symbolic(directive_globl(func_symbol.clone()));
        self.add_asm_symbolic(format!("{}:", func_symbol.clone()));
        
799
        ValueLocation::Relocatable(RegGroup::GPR, func_name)
800 801
    }
    
802
    fn finish_code(&mut self, func_name: MuName) -> (Box<MachineCode + Sync + Send>, ValueLocation) {
803 804
        let func_end = {
            let mut symbol = func_name.clone();
qinsoon's avatar
qinsoon committed
805 806 807
            symbol.push_str("_end");
            symbol
        };
808 809
        self.add_asm_symbolic(directive_globl(symbol(func_end.clone())));
        self.add_asm_symbolic(format!("{}:", symbol(func_end.clone())));
qinsoon's avatar
qinsoon committed
810
        
811
        self.control_flow_analysis();
qinsoon's avatar
qinsoon committed
812 813 814
        
        (
            self.cur.take().unwrap(),
815
            ValueLocation::Relocatable(RegGroup::GPR, func_end)
qinsoon's avatar
qinsoon committed
816
        )
817
    }
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

    fn start_code_sequence(&mut self) {
        self.cur = Some(Box::new(ASMCode {
            name: "snippet".to_string(),
            code: vec![],
            reg_defines: HashMap::new(),
            reg_uses: HashMap::new(),

            mem_op_used: HashMap::new(),

            preds: vec![],
            succs: vec![],

            idx_to_blk: HashMap::new(),
            blk_to_idx: HashMap::new(),
            cond_branches: HashMap::new(),
            branches: HashMap::new(),

            blocks: vec![],
            block_start: HashMap::new(),
            block_range: HashMap::new(),

            block_livein: HashMap::new(),
            block_liveout: HashMap::new()
        }));
    }

    fn finish_code_sequence(&mut self) -> Box<MachineCode + Sync + Send> {
        self.cur.take().unwrap()
    }

849 850 851 852 853 854 855
    fn print_cur_code(&self) {
        println!("");
        
        if self.cur.is_some() {
            let code = self.cur.as_ref().unwrap();
            
            println!("code for {}: ", code.name);
856 857 858 859
            let n_insts = code.code.len();
            for i in 0..n_insts {
                let ref line = code.code[i];
                println!("#{}\t{}", i, line.code);
860 861 862 863 864 865 866 867
            }
        } else {
            println!("no current code");
        }
        
        println!("");
    }
    
qinsoon's avatar
qinsoon committed
868
    fn start_block(&mut self, block_name: MuName) {
869 870 871
        let label = format!("{}:", self.asm_block_label(block_name.clone()));        
        self.add_asm_block_label(label, block_name.clone());
        self.cur_mut().blocks.push(block_name.clone());
872 873 874 875 876
        
        let start = self.line();
        self.cur_mut().block_start.insert(block_name, start);
    }
    
qinsoon's avatar
qinsoon committed
877
    fn start_exception_block(&mut self, block_name: MuName) -> ValueLocation {
878 879 880
        let block = self.asm_block_label(block_name.clone());
        self.add_asm_symbolic(directive_globl(symbol(block.clone())));
        self.add_asm_symbolic(format!("{}:", symbol(block.clone())));
qinsoon's avatar
qinsoon committed
881 882 883
        
        self.start_block(block_name);
        
884
        ValueLocation::Relocatable(RegGroup::GPR, block)
qinsoon's avatar
qinsoon committed
885 886
    }
    
qinsoon's avatar
qinsoon committed
887
    fn end_block(&mut self, block_name: MuName) {
888 889 890 891
        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));
892 893
    }
    
qinsoon's avatar
qinsoon committed
894
    fn set_block_livein(&mut self, block_name: MuName, live_in: &Vec<P<Value>>) {
895 896 897 898
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_livein.contains_key(&block_name) {
899
                cur.block_livein.insert(block_name.clone(), vec![]);
900 901 902 903 904 905 906 907 908 909 910 911
            } 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());
        }
    }
    
qinsoon's avatar
qinsoon committed
912
    fn set_block_liveout(&mut self, block_name: MuName, live_out: &Vec<P<Value>>) {
913 914 915 916
        let cur = self.cur_mut();
        
        let mut res = {
            if !cur.block_liveout.contains_key(&block_name) {
917
                cur.block_liveout.insert(block_name.clone(), vec![]);
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
            } 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 => {}
            }
        }        
    }
    
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    fn emit_nop(&mut self, bytes: usize) {
        trace!("emit: nop ({} bytes)", bytes);
        
        let asm = String::from("nop");
        
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![],
            vec![],
            false
        );
    }
    
948
    fn emit_cmp_r64_r64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
949
        trace!("emit: cmp {} {}", op1, op2);
950
        
951 952
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(op2, 4 + 1 + reg1.len() + 1);
953
        
qinsoon's avatar
qinsoon committed
954
        let asm = format!("cmpq {},{}", reg1, reg2);
955
        
956 957 958 959 960
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
961 962
            vec![loc1, loc2],
            false
963
        );
964 965
    }
    
966
    fn emit_cmp_r64_imm32(&mut self, op1: &P<Value>, op2: i32) {
qinsoon's avatar
qinsoon committed
967
        trace!("emit: cmp {} {}", op1, op2);
968
        
969
        let (reg1, id1, loc1) = self.prepare_reg(op1, 4 + 1 + 1 + op2.to_string().len() + 1);
970
        
qinsoon's avatar
qinsoon committed
971
        let asm = format!("cmpq ${},{}", op2, reg1);
972
        
973 974 975 976 977
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            vec![id1],
qinsoon's avatar
qinsoon committed
978 979
            vec![loc1],
            false
980
        )
981 982 983
    }
    
    fn emit_cmp_r64_mem64(&mut self, op1: &P<Value>, op2: &P<Value>) {
qinsoon's avatar
qinsoon committed
984
        trace!("emit: cmp {} {}", op1, op2);
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        
        let (reg, id1, loc1) = self.prepare_reg(op1, 4 + 1);
        let (mem, mut id2, mut loc2) = self.prepare_mem(op2, 4 + 1 + reg.len() + 1);
        
        let asm = format!("cmpq {},{}", reg, mem);
        
        // merge use vec
        id2.push(id1);
        loc2.push(loc1);
        
        self.add_asm_inst(
            asm,
            vec![],
            vec![],
            id2,
            loc2,
            true
        )
1003 1004
    }
    
1005
    fn emit_mov_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
qinsoon's avatar
qinsoon committed
1006
        trace!("emit: mov {} -> {}", src, dest);
1007
        
1008
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
1009
        
qinsoon's avatar
qinsoon committed
1010
        let asm = format!("movq ${},{}", src, reg1);
1011
        
1012 1013 1014
        self.add_asm_inst(
            asm,
            vec![id1],
1015 1016
            vec![loc1],
            vec![],
qinsoon's avatar
qinsoon committed
1017 1018
            vec![],
            false
1019
        )
1020 1021
    }
    
1022
    // load
1023
    fn emit_mov_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
qinsoon's avatar
qinsoon committed
1024
        trace!("emit: mov {} -> {}", src, dest);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        
        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,
qinsoon's avatar
qinsoon committed
1036 1037
            loc1,
            true
1038 1039 1040
        )
    }
    
1041
    // store
1042 1043 1044 1045 1046 1047 1048
    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'
1049
        // use the vec from mem as 'use' (push use reg from src to it)
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
        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,
qinsoon's avatar
qinsoon committed
1060 1061
            loc2,
            true
1062 1063 1064
        )
    }
    
1065
    fn emit_mov_mem64_imm32(&mut self, dest: &P<Value>, src: i32) {
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
        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,
qinsoon's avatar
qinsoon committed
1077 1078
            loc,
            true
1079
        )
qinsoon's avatar
qinsoon committed
1080 1081 1082 1083
    }
    
    fn emit_mov_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: mov {} -> {}", src, dest);
1084
        
1085 1086
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
1087
        
qinsoon's avatar
qinsoon committed
1088
        let asm = format!("movq {},{}", reg1, reg2);
1089
        
1090 1091 1092
        self.add_asm_inst(
            asm,
            vec![id2],
1093 1094
            vec![loc2],
            vec![id1],
qinsoon's avatar
qinsoon committed
1095 1096
            vec![loc1],
            false
1097
        )
qinsoon's avatar
qinsoon committed
1098 1099 1100 1101
    }
    
    fn emit_add_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
1102
        
1103 1104
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
1105
        
qinsoon's avatar
qinsoon committed
1106
        let asm = format!("addq {},{}", reg1, reg2);
1107
        
1108 1109
        self.add_asm_inst(
            asm,
1110 1111
            vec![id2],
            vec![loc2.clone()],
1112
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
1113 1114
            vec![loc1, loc2],
            false
1115
        )
qinsoon's avatar
qinsoon committed
1116 1117
    }
    
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    fn emit_lea_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: lea {} -> {}", src, dest);
        
        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!("leaq {},{}", mem, reg);
        
        self.add_asm_inst(
            asm,
            vec![id2],
            vec![loc2],
            id1,
            loc1,
            true
        ) 
    }
    
1136
    fn emit_and_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        trace!("emit: and {}, {} -> {}", src, dest, dest);
        
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);

        let asm = format!("andq ${},{}", src, reg1);
        
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
            vec![loc1],
            false
        )
    }
    
    fn emit_and_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: and {}, {} -> {}", src, dest, dest);
        
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1); 

        let asm = format!("andq {},{}", reg1, reg2);
        
        self.add_asm_inst(
            asm,
            vec![id2],
            vec![loc2.clone()],
            vec![id1, id2],
            vec![loc1, loc2],
            false
        )
    }    
    
qinsoon's avatar
qinsoon committed
1171 1172
    fn emit_add_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: add {}, {} -> {}", dest, src, dest);
1173
        unimplemented!()
qinsoon's avatar
qinsoon committed
1174 1175
    }
    
1176
    fn emit_add_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
qinsoon's avatar
qinsoon committed
1177
        trace!("emit: add {}, {} -> {}", dest, src, dest);
1178
        
1179
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
1180
        
1181
        let asm = format!("addq ${},{}", src, reg1);
1182
        
1183 1184 1185 1186 1187
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
qinsoon's avatar
qinsoon committed
1188 1189
            vec![loc1],
            false
1190
        )
qinsoon's avatar
qinsoon committed
1191 1192 1193 1194
    }
    
    fn emit_sub_r64_r64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
1195
        
1196 1197
        let (reg1, id1, loc1) = self.prepare_reg(src, 4 + 1);
        let (reg2, id2, loc2) = self.prepare_reg(dest, 4 + 1 + reg1.len() + 1);
1198
        
qinsoon's avatar
qinsoon committed
1199
        let asm = format!("subq {},{}", reg1, reg2);
1200
        
1201 1202
        self.add_asm_inst(
            asm,
1203 1204
            vec![id2],
            vec![loc2.clone()],
1205
            vec![id1, id2],
qinsoon's avatar
qinsoon committed
1206 1207
            vec![loc1, loc2],
            false
1208
        )        
qinsoon's avatar
qinsoon committed
1209 1210 1211 1212
    }
    
    fn emit_sub_r64_mem64(&mut self, dest: &P<Value>, src: &P<Value>) {
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
1213
        unimplemented!()
qinsoon's avatar
qinsoon committed
1214 1215
    }
    
1216
    fn emit_sub_r64_imm32(&mut self, dest: &P<Value>, src: i32) {
qinsoon's avatar
qinsoon committed
1217
        trace!("emit: sub {}, {} -> {}", dest, src, dest);
1218
        
1219
        let (reg1, id1, loc1) = self.prepare_reg(dest, 4 + 1 + 1 + src.to_string().len() + 1);
1220
        
qinsoon's avatar
qinsoon committed
1221
        let asm = format!("subq ${},{}", src, reg1);
1222
        
1223 1224 1225 1226 1227
        self.add_asm_inst(
            asm,
            vec![id1],
            vec![loc1.clone()],
            vec![id1],
qinsoon's avatar
qinsoon committed
1228 1229
            vec![loc1],
            false
1230
        )        
qinsoon's avatar
qinsoon committed
1231 1232
    }
    
1233
    fn emit_mul_r64(&mut self, src: &P<Value>) {
1234
        trace!("emit: mul rax, {} -> (rdx, rax)", src);
1235
        
1236
        let (reg, id, loc) = self.prepare_reg(src, 3 + 1);
1237 1238
        let rax = self.prepare_machine_reg(&x86_64::RAX);
        let rdx = self.prepare_machine_reg(&x86_64::RDX);
1239 1240 1241
        
        let asm = format!("mul {}", reg);
        
1242 1243 1244 1245 1246
        self.add_asm_inst(
            asm,
            vec![rax, rdx],
            vec![],
            vec![id, rax],
qinsoon's avatar
qinsoon committed
1247 1248
            vec![loc],
            false
1249
        )
1250 1251 1252 1253
    }
    
    fn emit_mul_mem64(&mut self, src: &P<Value>) {
        trace!("emit: mul rax, {} -> rax", src);
1254
        unimplemented!()
1255 1256
    }
    
1257
    fn emit_jmp(&mut self, dest_name: MuName) {
qinsoon's avatar
qinsoon committed
1258
        trace!("emit: jmp {}", dest_name);
1259 1260
        
        // symbolic label, we dont need to patch it
1261
        let asm = format!("jmp {}", self.asm_block_label(dest_name.clone()));
qinsoon's avatar
qinsoon committed
1262
        self.add_asm_branch(asm, dest_name)
qinsoon's avatar
qinsoon committed
1263 1264
    }
    
1265
    fn emit_je(&mut self, dest_name: MuName) {
qinsoon's avatar
qinsoon committed
1266
        trace!("emit: je {}", dest_name);
1267
        
1268
        let asm = format!("je {}", self.asm_block_label(dest_name.clone()));
qinsoon's avatar
qinsoon committed
1269
        self.add_asm_branch2(asm, dest_name);        
qinsoon's avatar
qinsoon committed
1270 1271
    }
    
1272
    fn emit_jne(&mut self, dest_name: MuName) {
qinsoon's avatar
qinsoon committed
1273
        trace!("emit: jne {}", dest_name);
1274
        
1275
        let asm = format!("jne {}", self.asm_block_label(dest_name.clone()));
qinsoon's avatar
qinsoon committed
1276
        self.add_asm_branch2(asm, dest_name);
qinsoon's avatar
qinsoon committed
1277 1278
    }
    
1279
    fn emit_ja(&mut self, dest_name: MuName) {