asm_backend.rs 50 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, 
qinsoon's avatar
qinsoon committed
27
    code: Vec<ASMInst>,
28
    
qinsoon's avatar
qinsoon committed
29 30
    idx_to_blk: HashMap<usize, MuName>,
    blk_to_idx: HashMap<MuName, usize>,
31
    
qinsoon's avatar
qinsoon committed
32 33 34
    blocks: Vec<MuName>,
    block_start: HashMap<MuName, usize>,
    block_range: HashMap<MuName, ops::Range<usize>>,
35
    
qinsoon's avatar
qinsoon committed
36 37
    block_livein: HashMap<MuName, Vec<MuID>>,
    block_liveout: HashMap<MuName, Vec<MuID>>
38 39
}

qinsoon's avatar
qinsoon committed
40 41 42
unsafe impl Send for ASMCode {} 
unsafe impl Sync for ASMCode {}

43
impl ASMCode {
qinsoon's avatar
qinsoon committed
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
    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
    }

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
    fn rewrite_insert(
        &self,
        insert_before: HashMap<usize, Vec<Box<ASMCode>>>,
        insert_after: HashMap<usize, Vec<Box<ASMCode>>>) -> Box<ASMCode>
    {
        let mut ret = ASMCode {
            name: self.name.clone(),
            code: vec![],
            idx_to_blk: HashMap::new(),
            blk_to_idx: HashMap::new(),
            blocks: vec![],
            block_start: HashMap::new(),
            block_range: HashMap::new(),
            block_livein: HashMap::new(),
            block_liveout: HashMap::new()
        };

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

        for i in 0..self.number_of_insts() {
            // 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();
                }
            }

            // copy this instruction


            // insert code after this instruction
            if insert_after.contains_key(&i) {

            }
        }

        unimplemented!()
    }

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

    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)
    }
}

use std::any::Any;

133
impl MachineCode for ASMCode {
134 135 136
    fn as_any(&self) -> &Any {
        self
    }
137 138 139
    fn number_of_insts(&self) -> usize {
        self.code.len()
    }
140
    
141 142 143 144 145 146 147 148
    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
149
    fn is_using_mem_op(&self, index: usize) -> bool {
qinsoon's avatar
qinsoon committed
150
        self.code[index].is_mem_op_used
qinsoon's avatar
qinsoon committed
151 152
    }
    
qinsoon's avatar
qinsoon committed
153
    fn get_succs(&self, index: usize) -> &Vec<usize> {
qinsoon's avatar
qinsoon committed
154
        &self.code[index].succs
qinsoon's avatar
qinsoon committed
155 156 157
    }
    
    fn get_preds(&self, index: usize) -> &Vec<usize> {
qinsoon's avatar
qinsoon committed
158
        &self.code[index].preds
qinsoon's avatar
qinsoon committed
159 160
    }
    
qinsoon's avatar
qinsoon committed
161 162
    fn get_inst_reg_uses(&self, index: usize) -> Vec<MuID> {
        self.code[index].uses.keys().map(|x| *x).collect()
163 164
    }
    
qinsoon's avatar
qinsoon committed
165 166
    fn get_inst_reg_defines(&self, index: usize) -> Vec<MuID> {
        self.code[index].defines.keys().map(|x| *x).collect()
167
    }
168
    
169
    fn replace_reg(&mut self, from: MuID, to: MuID) {
170 171 172 173
        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)
        };
174
        let to_reg_string = "%".to_string() + &to_reg_tag;
qinsoon's avatar
qinsoon committed
175 176 177 178 179 180 181

        for loc in self.get_define_locations(from) {
            let ref mut inst_to_patch = self.code[loc.line];
            for i in 0..loc.len {
                // FIXME: why loop here?
                string_utils::replace(&mut inst_to_patch.code, loc.index, &to_reg_string, to_reg_string.len());
            }
182
        }
183

qinsoon's avatar
qinsoon committed
184 185 186 187 188
        for loc in self.get_use_locations(from) {
            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());
            }
189 190
        }
    }
191

192
    fn replace_tmp_for_inst(&mut self, from: MuID, to: MuID, inst: usize) {
193 194 195 196 197 198 199 200
        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()
        };

qinsoon's avatar
qinsoon committed
201 202 203 204 205 206 207 208 209
        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() {
                for i in 0..loc.len {
                    string_utils::replace(&mut asm.code, loc.index, &to_reg_string, to_reg_string.len());
                }
210 211
            }

qinsoon's avatar
qinsoon committed
212 213 214
            // remove old key, insert new one
            asm.defines.remove(&from);
            asm.defines.insert(from, define_locs);
215
        }
qinsoon's avatar
qinsoon committed
216 217 218 219 220 221 222 223

        // 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() {
                for i in 0..loc.len {
                    string_utils::replace(&mut asm.code, loc.index, &to_reg_string, to_reg_string.len());
224 225 226
                }
            }

qinsoon's avatar
qinsoon committed
227 228 229
            // remove old key, insert new one
            asm.uses.remove(&from);
            asm.uses.insert(from, use_locs);
230 231
        }
    }
232
    
233 234
    fn set_inst_nop(&mut self, index: usize) {
        self.code.remove(index);
qinsoon's avatar
qinsoon committed
235
        self.code.insert(index, ASMInst::nop());
236 237
    }
    
238 239 240 241 242 243 244 245 246 247 248
    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
    }
    
249 250
    fn trace_mc(&self) {
        trace!("");
251

252 253
        trace!("code for {}: \n", self.name);
        
254 255
        let n_insts = self.code.len();
        for i in 0..n_insts {
256
            self.trace_inst(i);
257 258
        }
        
259 260 261 262 263 264
        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),
qinsoon's avatar
qinsoon committed
265
            self.code[i].preds, self.code[i].succs);
266
    }
267
    
268 269
    fn get_ir_block_livein(&self, block: &str) -> Option<&Vec<MuID>> {
        self.block_livein.get(&block.to_string())
270 271
    }
    
272 273
    fn get_ir_block_liveout(&self, block: &str) -> Option<&Vec<MuID>> {
        self.block_liveout.get(&block.to_string())
274 275
    }
    
276 277 278 279 280 281 282 283
    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
284
    fn get_all_blocks(&self) -> &Vec<MuName> {
285 286 287
        &self.blocks
    }
    
288 289
    fn get_block_range(&self, block: &str) -> Option<ops::Range<usize>> {
        match self.block_range.get(&block.to_string()) {
290 291 292 293
            Some(r) => Some(r.clone()),
            None => None
        }
    }
294 295
}

qinsoon's avatar
qinsoon committed
296 297 298 299 300 301 302 303
#[derive(Clone, Debug)]
enum ASMBranchTarget {
    None,
    Conditional(MuName),
    Unconditional(MuName)
}

struct ASMInst {
304
    code: String,
qinsoon's avatar
qinsoon committed
305 306 307 308 309 310 311 312

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

    is_mem_op_used: bool,
    preds: Vec<usize>,
    succs: Vec<usize>,
    branch: ASMBranchTarget
313 314
}

qinsoon's avatar
qinsoon committed
315 316 317
impl ASMInst {
    fn symbolic(line: String) -> ASMInst {
        ASMInst {
318
            code: line,
qinsoon's avatar
qinsoon committed
319 320 321 322 323 324
            defines: HashMap::new(),
            uses: HashMap::new(),
            is_mem_op_used: false,
            preds: vec![],
            succs: vec![],
            branch: ASMBranchTarget::None
325 326 327
        }
    }
    
qinsoon's avatar
qinsoon committed
328 329 330 331 332 333 334 335 336
    fn inst(
        inst: String,
        defines: HashMap<MuID, Vec<ASMLocation>>,
        uses: HashMap<MuID, Vec<ASMLocation>>,
        is_mem_op_used: bool,
        target: ASMBranchTarget
    ) -> ASMInst
    {
        ASMInst {
337 338
            code: inst,
            defines: defines,
qinsoon's avatar
qinsoon committed
339 340 341 342 343
            uses: uses,
            is_mem_op_used: is_mem_op_used,
            preds: vec![],
            succs: vec![],
            branch: target
344 345
        }
    }
346
    
qinsoon's avatar
qinsoon committed
347 348
    fn nop() -> ASMInst {
        ASMInst {
349
            code: "".to_string(),
qinsoon's avatar
qinsoon committed
350 351 352 353 354 355
            defines: HashMap::new(),
            uses: HashMap::new(),
            is_mem_op_used: false,
            preds: vec![],
            succs: vec![],
            branch: ASMBranchTarget::None
356 357
        }
    }
358 359
}

360
#[derive(Clone, Debug)]
361 362 363 364 365 366 367
struct ASMLocation {
    line: usize,
    index: usize,
    len: usize
}

impl ASMLocation {
qinsoon's avatar
qinsoon committed
368
    fn new(line: usize, index: usize, len: usize) -> ASMLocation {
369
        ASMLocation{
qinsoon's avatar
qinsoon committed
370
            line: line,
371 372 373 374 375 376
            index: index,
            len: len
        }
    }
}

377
pub struct ASMCodeGen {
378
    cur: Option<Box<ASMCode>>
379 380
}

381
const REG_PLACEHOLDER_LEN : usize = 5;
382 383 384 385 386 387
lazy_static! {
    pub static ref REG_PLACEHOLDER : String = {
        let blank_spaces = [' ' as u8; REG_PLACEHOLDER_LEN];
        
        format!("%{}", str::from_utf8(&blank_spaces).unwrap())
    };
388 389 390 391
}

impl ASMCodeGen {
    pub fn new() -> ASMCodeGen {
392
        ASMCodeGen {
393
            cur: None
394 395 396 397 398 399 400 401 402 403 404
        }
    }
    
    fn cur(&self) -> &ASMCode {
        self.cur.as_ref().unwrap()
    }
    
    fn cur_mut(&mut self) -> &mut ASMCode {
        self.cur.as_mut().unwrap()
    }
    
405 406 407 408
    fn line(&self) -> usize {
        self.cur().code.len()
    }
    
409 410
    fn add_asm_label(&mut self, code: String) {
        let l = self.line();
qinsoon's avatar
qinsoon committed
411
        self.cur_mut().code.push(ASMInst::symbolic(code));
412 413
    }
    
414
    fn add_asm_block_label(&mut self, code: String, block_name: MuName) {
415
        let l = self.line();
qinsoon's avatar
qinsoon committed
416
        self.cur_mut().code.push(ASMInst::symbolic(code));
417
        
418
        self.cur_mut().idx_to_blk.insert(l, block_name.clone());
419 420 421
        self.cur_mut().blk_to_idx.insert(block_name, l);
    }
    
422
    fn add_asm_symbolic(&mut self, code: String){
qinsoon's avatar
qinsoon committed
423
        self.cur_mut().code.push(ASMInst::symbolic(code));
424 425
    }
    
426 427
    fn prepare_machine_regs(&self, regs: Iter<P<Value>>) -> Vec<MuID> {
        regs.map(|x| self.prepare_machine_reg(x)).collect()
qinsoon's avatar
qinsoon committed
428
    }
429
    
430
    fn add_asm_call(&mut self, code: String) {
qinsoon's avatar
qinsoon committed
431
        // a call instruction will use all the argument registers
qinsoon's avatar
qinsoon committed
432 433 434 435 436 437 438
        let mut uses : HashMap<MuID, Vec<ASMLocation>> = HashMap::new();
        for reg in x86_64::ARGUMENT_GPRs.iter() {
            uses.insert(reg.id(), vec![]);
        }
        for reg in x86_64::ARGUMENT_FPRs.iter() {
            uses.insert(reg.id(), vec![]);
        }
qinsoon's avatar
qinsoon committed
439 440

        // defines: return registers
qinsoon's avatar
qinsoon committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
        let mut defines : HashMap<MuID, Vec<ASMLocation>> = HashMap::new();
        for reg in x86_64::RETURN_GPRs.iter() {
            defines.insert(reg.id(), vec![]);
        }
        for reg in x86_64::RETURN_FPRs.iter() {
            defines.insert(reg.id(), vec![]);
        }
        for reg in x86_64::CALLER_SAVED_GPRs.iter() {
            if !defines.contains_key(&reg.id()) {
                defines.insert(reg.id(), vec![]);
            }
        }
        for reg in x86_64::CALLER_SAVED_FPRs.iter() {
            if !defines.contains_key(&reg.id()) {
                defines.insert(reg.id(), vec![]);
            }
        }
458
          
qinsoon's avatar
qinsoon committed
459
        self.add_asm_inst(code, defines, uses, false);
460 461 462
    }
    
    fn add_asm_ret(&mut self, code: String) {
qinsoon's avatar
qinsoon committed
463 464 465 466 467 468 469 470 471 472
        let mut uses : HashMap<MuID, Vec<ASMLocation>> = {
            let mut ret = HashMap::new();
            for reg in x86_64::RETURN_GPRs.iter() {
                ret.insert(reg.id(), vec![]);
            }
            for reg in x86_64::RETURN_FPRs.iter() {
                ret.insert(reg.id(), vec![]);
            }
            ret
        };
473
        
qinsoon's avatar
qinsoon committed
474
        self.add_asm_inst(code, hashmap!{}, uses, false);
475 476
    }
    
477
    fn add_asm_branch(&mut self, code: String, target: MuName) {
qinsoon's avatar
qinsoon committed
478
        self.add_asm_inst_internal(code, hashmap!{}, hashmap!{}, false, ASMBranchTarget::Unconditional(target));
479 480
    }
    
481
    fn add_asm_branch2(&mut self, code: String, target: MuName) {
qinsoon's avatar
qinsoon committed
482
        self.add_asm_inst_internal(code, hashmap!{}, hashmap!{}, false, ASMBranchTarget::Conditional(target));
483 484 485 486 487
    }
    
    fn add_asm_inst(
        &mut self, 
        code: String, 
qinsoon's avatar
qinsoon committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501
        defines: HashMap<MuID, Vec<ASMLocation>>,
        uses: HashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool)
    {
        self.add_asm_inst_internal(code, defines, uses, is_using_mem_op, ASMBranchTarget::None)
    }

    fn add_asm_inst_internal(
        &mut self,
        code: String,
        defines: HashMap<MuID, Vec<ASMLocation>>,
        uses: HashMap<MuID, Vec<ASMLocation>>,
        is_using_mem_op: bool,
        target: ASMBranchTarget)
502
    {
503 504
        let line = self.line();
        trace!("asm: {}", code);
qinsoon's avatar
qinsoon committed
505 506
        trace!("     defines: {:?}", defines);
        trace!("     uses: {:?}", uses);
507
        let mc = self.cur_mut();
qinsoon's avatar
qinsoon committed
508

509
        // put the instruction
qinsoon's avatar
qinsoon committed
510
        mc.code.push(ASMInst::inst(code, defines, uses, is_using_mem_op, target));
511 512
    }
    
513
    fn prepare_reg(&self, op: &P<Value>, loc: usize) -> (String, MuID, ASMLocation) {
514 515 516 517 518 519 520
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting register op")
            }
        }
        
521 522
        let str = self.asm_reg_op(op);
        let len = str.len();
qinsoon's avatar
qinsoon committed
523
        (str, op.extract_ssa_id().unwrap(), ASMLocation::new(self.line(), loc, len))
524 525 526
    }
    
    fn prepare_machine_reg(&self, op: &P<Value>) -> MuID {
527 528 529 530 531 532 533
        if cfg!(debug_assertions) {
            match op.v {
                Value_::SSAVar(_) => {},
                _ => panic!("expecting machine register op")
            }
        }        
        
534
        op.extract_ssa_id().unwrap()
535
    }
536
    
537
    #[allow(unused_assignments)]
qinsoon's avatar
qinsoon committed
538
    fn prepare_mem(&self, op: &P<Value>, loc: usize) -> (String, HashMap<MuID, Vec<ASMLocation>>) {
539 540 541 542 543 544
        if cfg!(debug_assertions) {
            match op.v {
                Value_::Memory(_) => {},
                _ => panic!("expecting register op")
            }
        }        
qinsoon's avatar
qinsoon committed
545

546 547 548 549
        let mut ids : Vec<MuID> = vec![];
        let mut locs : Vec<ASMLocation> = vec![];
        let mut result_str : String = "".to_string();
        
550
        let mut loc_cursor : usize = loc;
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
        
        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;
            },
633 634
            Value_::Memory(MemoryLocation::Symbolic{ref base, ref label}) => {
                result_str.push_str(&symbol(label.clone()));
635 636 637 638 639 640 641 642 643 644 645
                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();
qinsoon's avatar
qinsoon committed
646

647
                    result_str.push(')');
qinsoon's avatar
qinsoon committed
648
                    loc_cursor += 1;
649 650 651 652
                }
            },
            _ => panic!("expect mem location as value")
        }
qinsoon's avatar
qinsoon committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670

        let uses : HashMap<MuID, Vec<ASMLocation>> = {
            let mut map : HashMap<MuID, Vec<ASMLocation>> = hashmap!{};
            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)
671 672
    }
    
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
    
    fn control_flow_analysis(&mut self) {
        // control flow analysis
        let n_insts = self.line();
qinsoon's avatar
qinsoon committed
691

692
        let code = self.cur_mut();
qinsoon's avatar
qinsoon committed
693
        let ref mut asm = code.code;
694 695 696 697 698 699
        
        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 {
700 701
                    trace!("inst {}: not a block start", i);
                    trace!("inst {}: set PREDS as previous inst {}", i, i-1);
qinsoon's avatar
qinsoon committed
702
                    asm[i].preds.push(i - 1);
703 704 705 706 707 708 709
                }
            } 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
qinsoon's avatar
qinsoon committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
            let branch = asm[i].branch.clone();
            match branch {
                ASMBranchTarget::Unconditional(ref target) => {
                    // branch to target
                    trace!("inst {}: is a branch to {}", i, target);

                    let target_n = code.blk_to_idx.get(target).unwrap();
                    trace!("inst {}: branch target index is {}", i, target_n);

                    // cur inst's succ is target
                    trace!("inst {}: set SUCCS as branch target {}", i, target_n);
                    asm[i].succs.push(*target_n);

                    // target's pred is cur
                    trace!("inst {}: set PREDS as branch source {}", target_n, i);
                    asm[*target_n].preds.push(i);
                },
                ASMBranchTarget::Conditional(ref target) => {
728
                    // branch to target
729
                    trace!("inst {}: is a cond branch to {}", i, target);
qinsoon's avatar
qinsoon committed
730

731
                    let target_n = code.blk_to_idx.get(target).unwrap();
732
                    trace!("inst {}: branch target index is {}", i, target_n);
qinsoon's avatar
qinsoon committed
733

734
                    // cur insts' succ is target and next inst
qinsoon's avatar
qinsoon committed
735
                    asm[i].succs.push(*target_n);
736
                    trace!("inst {}: set SUCCS as branch target {}", i, target_n);
737
                    if i < n_insts - 1 {
qinsoon's avatar
qinsoon committed
738 739
                        trace!("inst {}: set SUCCS as next inst", i + 1);
                        asm[i].succs.push(i + 1);
740
                    }
qinsoon's avatar
qinsoon committed
741

742
                    // target's pred is cur
qinsoon's avatar
qinsoon committed
743
                    asm[*target_n].preds.push(i);
744
                    trace!("inst {}: set PREDS as {}", *target_n, i);
qinsoon's avatar
qinsoon committed
745 746
                },
                ASMBranchTarget::None => {
747
                    // not branch nor cond branch, succ is next inst
748
                    trace!("inst {}: not a branch inst", i);
749
                    if i < n_insts - 1 {
750
                        trace!("inst {}: set SUCCS as next inst {}", i, i + 1);
qinsoon's avatar
qinsoon committed
751
                        asm[i].succs.push(i + 1);
752 753
                    }
                }
qinsoon's avatar
qinsoon committed
754
            }
755 756 757 758
        }
        
        // a sanity check for fallthrough blocks
        for i in 0..n_insts {
qinsoon's avatar
qinsoon committed
759 760
            if i != 0 && asm[i].preds.len() == 0 {
                asm[i].preds.push(i - 1);
761 762 763
            }
        }        
    }
764 765 766 767

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

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

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

            idx_to_blk: HashMap::new(),
            blk_to_idx: 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> {
830
        self.finish_code_sequence_asm()
831 832
    }

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