liveness.rs 22.8 KB
Newer Older
1 2
extern crate hprof;

qinsoon's avatar
qinsoon committed
3
use compiler::machine_code::CompiledFunction;
4
use ast::ir::*;
qinsoon's avatar
qinsoon committed
5
use compiler::backend;
6
use utils::LinkedHashSet;
7
use utils::LinkedHashMap;
qinsoon's avatar
qinsoon committed
8

9 10 11
use compiler::backend::reg_alloc::graph_coloring::petgraph;
use compiler::backend::reg_alloc::graph_coloring::petgraph::Graph;
use compiler::backend::reg_alloc::graph_coloring::petgraph::graph::NodeIndex;
qinsoon's avatar
qinsoon committed
12

13 14 15
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphNode {
    temp: MuID,
qinsoon's avatar
qinsoon committed
16
    color: Option<MuID>,
17 18
    group: backend::RegGroup,
    spill_cost: f32
qinsoon's avatar
qinsoon committed
19
}
20

qinsoon's avatar
qinsoon committed
21
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22
pub struct Move{pub from: NodeIndex, pub to: NodeIndex}
23 24

pub struct InterferenceGraph {
25
    graph: Graph<GraphNode, (), petgraph::Undirected>,
26 27
    nodes: LinkedHashMap<MuID, NodeIndex>,
    moves: LinkedHashSet<Move>,
28 29 30 31
}

impl InterferenceGraph {
    fn new() -> InterferenceGraph {
qinsoon's avatar
qinsoon committed
32
        InterferenceGraph {
33
            graph: Graph::new_undirected(),
34 35
            nodes: LinkedHashMap::new(),
            moves: LinkedHashSet::new()
qinsoon's avatar
qinsoon committed
36 37 38
        }
    }
    
39
    fn new_node(&mut self, reg_id: MuID, context: &FunctionContext) -> NodeIndex {
qinsoon's avatar
qinsoon committed
40 41 42
        let entry = context.get_value(reg_id).unwrap();
        
        if !self.nodes.contains_key(&reg_id) {
43
            let node = GraphNode {
44
                temp: reg_id,
45
                color: None,
46
                group: backend::RegGroup::get_from_ty(entry.ty()),
47
                spill_cost: 0.0f32
qinsoon's avatar
qinsoon committed
48
            };
49 50 51 52 53

            let index = self.graph.add_node(node);

            self.nodes.insert(reg_id, index);
        }
54
        
55 56
        let node_index = *self.nodes.get(&reg_id).unwrap();
        let node_mut = self.graph.node_weight_mut(node_index).unwrap();
57 58
        
        // increase node spill cost
59
        node_mut.spill_cost += 1.0f32;
60
        
61
        node_index
qinsoon's avatar
qinsoon committed
62 63
    }
    
64
    pub fn get_node(&self, reg: MuID) -> NodeIndex {
qinsoon's avatar
qinsoon committed
65
        match self.nodes.get(&reg) {
qinsoon's avatar
qinsoon committed
66
            Some(index) => *index,
qinsoon's avatar
qinsoon committed
67
            None => panic!("do not have a node for {}", reg)
qinsoon's avatar
qinsoon committed
68 69 70
        }
    }
    
71 72 73 74 75 76 77 78
    pub fn temps(&self) -> Vec<MuID>{
        let mut ret = vec![];
        for reg in self.nodes.keys() {
            ret.push(*reg);
        }
        ret
    }
    
79
    pub fn nodes(&self) -> Vec<NodeIndex> {
qinsoon's avatar
qinsoon committed
80
        let mut ret = vec![];
81 82
        for index in self.nodes.values() {
            ret.push(*index);
qinsoon's avatar
qinsoon committed
83 84 85 86
        }
        ret
    }
    
87
    pub fn moves(&self) -> &LinkedHashSet<Move> {
qinsoon's avatar
qinsoon committed
88 89 90 91 92 93 94
        &self.moves
    }
    
    pub fn n_nodes(&self) -> usize {
        self.nodes.len()
    }
    
95
    fn add_move(&mut self, src: NodeIndex, dst: NodeIndex) {
qinsoon's avatar
qinsoon committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        let src = {
            let temp_src = self.get_temp_of(src);
            if temp_src < MACHINE_ID_END {
                let alias = backend::get_color_for_precolored(self.get_temp_of(src));
                self.get_node(alias)
            } else {
                src
            }
        };


        let dst = {
            let temp_dst = self.get_temp_of(dst);
            if temp_dst < MACHINE_ID_END {
                let alias = backend::get_color_for_precolored(self.get_temp_of(dst));
                self.get_node(alias)
            } else {
                dst
            }
        };

qinsoon's avatar
qinsoon committed
117
        self.moves.insert(Move{from: src, to: dst});
118 119
    }
    
120 121
    pub fn add_interference_edge(&mut self, from: NodeIndex, to: NodeIndex) {
        self.graph.update_edge(from, to, ());
qinsoon's avatar
qinsoon committed
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

        // if one of the node is machine register, we also add
        // interference edge to its alias
        // e.g. if we have %a, %edi interferenced,
        // we also add %a, %rdi interference

        let from_tmp = self.graph.node_weight(from).unwrap().temp;
        let to_tmp   = self.graph.node_weight(to).unwrap().temp;

        if from_tmp < MACHINE_ID_END || to_tmp < MACHINE_ID_END {
            let from_tmp = if from_tmp < MACHINE_ID_END {
                backend::get_color_for_precolored(from_tmp)
            } else {
                from_tmp
            };

            let to_tmp = if to_tmp < MACHINE_ID_END {
                backend::get_color_for_precolored(to_tmp)
            } else {
                to_tmp
            };

            let from_tmp_node = self.get_node(from_tmp);
            let to_tmp_node   = self.get_node(to_tmp);
            self.graph.update_edge(from_tmp_node, to_tmp_node, ());
        }
qinsoon's avatar
qinsoon committed
148 149
    }

150
    pub fn is_interferenced_with(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
151 152 153
        let edge = self.graph.find_edge(node1, node2);

        edge.is_some()
qinsoon's avatar
qinsoon committed
154 155
    }
    
156 157
    pub fn color_node(&mut self, node: NodeIndex, color: MuID) {
        self.graph.node_weight_mut(node).unwrap().color = Some(color);
qinsoon's avatar
qinsoon committed
158 159
    }
    
160 161
    pub fn is_colored(&self, node: NodeIndex) -> bool {
        self.graph.node_weight(node).unwrap().color.is_some()
qinsoon's avatar
qinsoon committed
162 163
    }
    
164 165
    pub fn get_color_of(&self, node: NodeIndex) -> Option<MuID> {
        self.graph.node_weight(node).unwrap().color
166 167
    }
    
168 169
    pub fn get_group_of(&self, node: NodeIndex) -> backend::RegGroup {
        self.graph.node_weight(node).unwrap().group
qinsoon's avatar
qinsoon committed
170 171
    }
    
172 173
    pub fn get_temp_of(&self, node: NodeIndex) -> MuID {
        self.graph.node_weight(node).unwrap().temp
174 175
    }
    
176 177
    pub fn get_spill_cost(&self, node: NodeIndex) -> f32 {
        self.graph.node_weight(node).unwrap().spill_cost
178 179
    }
    
180
    fn is_same_node(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
qinsoon's avatar
qinsoon committed
181
        node1 == node2
qinsoon's avatar
qinsoon committed
182
    }
183 184 185 186 187 188 189

    fn is_same_group(&self, node1: NodeIndex, node2: NodeIndex) -> bool {
        let node1 = self.graph.node_weight(node1).unwrap();
        let node2 = self.graph.node_weight(node2).unwrap();

        node1.group == node2.group
    }
qinsoon's avatar
qinsoon committed
190
    
191 192
    pub fn is_adj(&self, from: NodeIndex, to: NodeIndex) -> bool {
        self.is_interferenced_with(from, to)
qinsoon's avatar
qinsoon committed
193 194
    }
    
195 196
    pub fn outedges_of(&self, node: NodeIndex) -> Vec<NodeIndex> {
        self.graph.neighbors(node).collect()
197 198
    }
    
199 200
    pub fn outdegree_of(&self, node: NodeIndex) -> usize {
        self.outedges_of(node).len()
qinsoon's avatar
qinsoon committed
201 202
    }
    
203 204
    pub fn indegree_of(&self, node: NodeIndex) -> usize {
        self.outdegree_of(node)
qinsoon's avatar
qinsoon committed
205 206
    }
    
207
    pub fn degree_of(&self, node: NodeIndex) -> usize {
qinsoon's avatar
fix  
qinsoon committed
208
        self.outdegree_of(node)
qinsoon's avatar
qinsoon committed
209 210
    }
    
qinsoon's avatar
qinsoon committed
211
    pub fn print(&self, context: &FunctionContext) {
212 213 214
        use compiler::backend::reg_alloc::graph_coloring::petgraph::dot::Dot;
        use compiler::backend::reg_alloc::graph_coloring::petgraph::dot::Config;

215 216
        trace!("");
        trace!("Interference Graph");
217

218
        trace!("nodes:");
qinsoon's avatar
qinsoon committed
219
        for id in self.nodes.keys() {
qinsoon's avatar
qinsoon committed
220
            let val = context.get_value(*id).unwrap().value();
221
            trace!("Reg {} -> {:?}", val, self.nodes.get(&id).unwrap());
qinsoon's avatar
qinsoon committed
222 223
        }

224
        trace!("moves:");
225
        for mov in self.moves.iter() {
226
            trace!("Move {:?} -> {:?}", mov.from, mov.to);
227
        }
qinsoon's avatar
qinsoon committed
228

229 230 231
        trace!("graph:");
        trace!("\n\n{:?}\n", Dot::with_config(&self.graph, &[Config::EdgeNoLabel]));
        trace!("");
232
    }
qinsoon's avatar
qinsoon committed
233 234
}

235 236
const TRACE_BUILD_LIVE_SET : bool = false;

qinsoon's avatar
[wip]  
qinsoon committed
237 238
fn build_live_set (cf: &mut CompiledFunction, func: &MuFunctionVersion) {
    info!("---start building live set---");
239

240
    let cfg = local_liveness_analysis(cf);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    global_liveness_analysis(cfg, cf, func);

    info!("---finish building live set---");
}

#[derive(Clone, Debug)]
struct CFGBlockNode {
    block: String,

    pred: Vec<String>,
    succ: Vec<String>,

    uses:  Vec<MuID>,
    defs: Vec<MuID>
}

257
fn local_liveness_analysis (cf: &mut CompiledFunction) -> LinkedHashMap<String, CFGBlockNode> {
258 259 260
    info!("---local liveness analysis---");
    let mc = cf.mc();

261
    let mut ret = LinkedHashMap::new();
262 263 264 265

    let all_blocks = mc.get_all_blocks();

    // create maps (start_inst -> name) and (end_inst -> name)
266 267
    let mut start_inst_map : LinkedHashMap<usize, &str> = LinkedHashMap::new();
    let mut end_inst_map   : LinkedHashMap<usize, &str> = LinkedHashMap::new();
268 269 270 271 272 273
    for block in all_blocks.iter() {
        let range = match mc.get_block_range(block) {
            Some(range) => range,
            None => panic!("cannot find range for block {}", block)
        };

274 275 276 277 278 279 280 281 282
        let first_inst = range.start;
        let last_inst = match mc.get_last_inst(range.end) {
            Some(last) => last,
            None => panic!("cannot find last instruction in block {}, this block contains no instruction?", block)
        };
        trace!("Block {}: start_inst={}, end_inst(inclusive)={}", block, first_inst, last_inst);

        start_inst_map.insert(first_inst, block);
        end_inst_map.insert(last_inst, block);
283 284 285 286 287 288 289 290 291 292 293
    }

    // local liveness analysis
    for block in mc.get_all_blocks().iter() {
        trace!("---block {}---", block);
        let range = mc.get_block_range(block).unwrap();

        let start_inst = range.start;
        let end        = range.end;

        let mut livein = vec![];
294
        let mut all_defined : LinkedHashSet<MuID> = LinkedHashSet::new();
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311

        for i in start_inst..end {
            let reg_uses = mc.get_inst_reg_uses(i);

            // if a reg is used but not defined before, it is a live-in
            for reg in reg_uses {
                if !all_defined.contains(&reg) {
                    livein.push(reg);
                }
            }

            let reg_defs = mc.get_inst_reg_defines(i);
            for reg in reg_defs {
                all_defined.insert(reg);
            }
        }

312
        let defs : Vec<MuID> = all_defined.iter().map(|x| *x).collect();
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

        let preds : Vec<String> = {
            let mut ret = vec![];

            // start_inst is the first instruction
            // start_inst-1 is the label for the block
            // FIXME: this is confusing! label should be an attribute to an instruction
            for pred in mc.get_preds(start_inst).into_iter() {
                match end_inst_map.get(pred) {
                    Some(str) => ret.push(String::from(*str)),
                    None => {}
                }
            }

            ret
        };

        let succs : Vec<String> = {
            let mut ret = vec![];

333
            for succ in mc.get_succs(mc.get_last_inst(end).unwrap()).into_iter() {
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                match start_inst_map.get(succ) {
                    Some(str) => ret.push(String::from(*str)),
                    None => {}
                }
            }

            ret
        };

        let node = CFGBlockNode {
            block: block.clone(),

            pred: preds,
            succ: succs,

            uses: livein,
            defs: defs
        };

        trace!("as CFGNode {:?}", node);

        ret.insert(block.clone(), node);
    }

    ret
}

361
//fn topological_sort_cfg(entry: String, cfg: LinkedHashMap<String, CFGBlockNode>) -> Vec<CFGBlockNode> {
362 363 364 365
//    let mut ret = vec![];
//    // for all nodes i
//    //   mark[i] <- false
//    let mut mark = {
366
//        let mut ret = LinkedHashMap::new();
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
//        for str in cfg.keys() {
//            ret.insert(str.clone(), false);
//        }
//
//        ret
//    };
//
//    // dfs(start-node)
//    dfs(entry, &cfg, &mut mark, &mut ret);
//
//    ret.reverse();
//
//    ret
//}
//
382
//fn dfs(node: String, cfg: &LinkedHashMap<String, CFGBlockNode>, mark: &mut LinkedHashMap<String, bool>, sorted: &mut Vec<CFGBlockNode>) {
383 384 385 386 387 388 389 390 391 392 393 394 395
//    // if mark[i] = false
//    if !mark.get(&node).unwrap() {
//        mark.insert(node.clone(), true);
//
//        let cfg_node = cfg.get(&node).unwrap().clone();
//        for succ in cfg_node.succ.iter() {
//            dfs(succ.clone(), cfg, mark, sorted);
//        }
//
//        sorted.push(cfg_node);
//    }
//}

396
fn global_liveness_analysis(blocks: LinkedHashMap<String, CFGBlockNode>, cf: &mut CompiledFunction, func: &MuFunctionVersion) {
397 398
    info!("---global liveness analysis---");
    info!("{} blocks", blocks.len());
399 400

    // init live in and live out
401 402
    let mut livein  : LinkedHashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = LinkedHashMap::new();
403 404 405 406 407
        for name in blocks.keys() {
            ret.insert(name.clone(), LinkedHashSet::new());
        }
        ret
    };
408 409
    let mut liveout  : LinkedHashMap<String, LinkedHashSet<MuID>> = {
        let mut ret = LinkedHashMap::new();
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        for name in blocks.keys() {
            ret.insert(name.clone(), LinkedHashSet::new());
        }
        ret
    };

    let mut is_changed = true;
    let mut i = 0;

    while is_changed {
        trace!("---iteration {}---", i);
        i += 1;

        // reset
        is_changed = false;

        for node in blocks.keys() {
            let cfg_node = blocks.get(node).unwrap();

            let in_set_old  = livein.get(node).unwrap().clone();
            let out_set_old = liveout.get(node).unwrap().clone();

            // in <- use + (out - def)
            {
                let mut inset = livein.get_mut(node).unwrap();

                inset.clear();

                // (1) out - def
                inset.add_all(liveout.get(node).unwrap().clone());
                for def in cfg_node.defs.iter() {
                    inset.remove(def);
                }

                // (2) in + (out - def)
                for in_reg in cfg_node.uses.iter() {
                    inset.insert(*in_reg);
                }
            }

            // out[n] <- union(in[s] for every successor s of n)
            {
                let mut outset = liveout.get_mut(node).unwrap();
                outset.clear();

                for s in cfg_node.succ.iter() {
                    outset.add_all(livein.get(s).unwrap().clone());
                }
            }

            // is in/out changed in this iteration?
            let n_changed = !in_set_old.equals(livein.get(node).unwrap()) || !out_set_old.equals(liveout.get(node).unwrap());

            if TRACE_BUILD_LIVE_SET {
                trace!("block {}", node);
                trace!("in(old)  = {:?}", in_set_old);
                trace!("in(new)  = {:?}", livein.get(node).unwrap());
                trace!("out(old) = {:?}", out_set_old);
                trace!("out(new) = {:?}", liveout.get(node).unwrap());
            }

            is_changed = is_changed || n_changed;
        }
    }

475 476
    info!("finished in {} iterations", i);

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    for block in blocks.keys() {
        let livein : Vec<MuID> = livein.get(block).unwrap().clone().iter().map(|x| *x).collect();
        {
            let display_array : Vec<String> =  livein.iter().map(|x| func.context.get_temp_display(*x)).collect();
            trace!("livein  for block {}: {:?}", block, display_array);
        }
        cf.mc_mut().set_ir_block_livein(block, livein);

        let liveout : Vec<MuID> = liveout.get(block).unwrap().clone().iter().map(|x| *x).collect();
        {
            let display_array : Vec<String> = liveout.iter().map(|x| func.context.get_temp_display(*x)).collect();
            trace!("liveout for block {}: {:?}", block, display_array);
        }
        cf.mc_mut().set_ir_block_liveout(block, liveout);
    }
}

#[allow(dead_code)]
495
fn naive_global_liveness_analysis(cf: &mut CompiledFunction) {
qinsoon's avatar
qinsoon committed
496
    let n_insts = cf.mc().number_of_insts();
497 498 499 500

    let mut livein  : Vec<LinkedHashSet<MuID>> = vec![LinkedHashSet::new(); n_insts];
    let mut liveout : Vec<LinkedHashSet<MuID>> = vec![LinkedHashSet::new(); n_insts];

501
    let mut is_changed = true;
502

qinsoon's avatar
[wip]  
qinsoon committed
503
    let mut i = 0;
504
    while is_changed {
qinsoon's avatar
qinsoon committed
505
        trace!("---iteration {}---", i);
qinsoon's avatar
[wip]  
qinsoon committed
506 507
        i += 1;

508 509
        // reset
        is_changed = false;
510

511
        for n in 0..n_insts {
512 513 514 515 516 517 518 519 520
            let in_set_old = livein[n].clone();
            let out_set_old = liveout[n].clone();

            // in[n] <- use[n] + (out[n] - def[n]);
            {
                let ref mut inset = livein[n];

                inset.clear();

qinsoon's avatar
[wip]  
qinsoon committed
521
                // (1) out[n] - def[n]
522 523 524 525
                inset.add_all(liveout[n].clone());
                for def in cf.mc().get_inst_reg_defines(n) {
                    inset.remove(&def);
                }
qinsoon's avatar
[wip]  
qinsoon committed
526 527
                // (2) in[n] + (out[n] - def[n])
                inset.add_from_vec(cf.mc().get_inst_reg_uses(n));
528
            }
529

530
            // out[n] <- union(in[s] for every successor s of n)
531 532 533 534 535 536 537
            {
                let ref mut outset = liveout[n];
                outset.clear();

                for s in cf.mc().get_succs(n) {
                    outset.add_all(livein[*s].clone());
                }
538
            }
539 540 541 542

            // is in/out changed in this iteration?
            let n_changed = !in_set_old.equals(&livein[n]) || !out_set_old.equals(&liveout[n]);

543 544 545 546 547 548 549
            if TRACE_BUILD_LIVE_SET {
                trace!("inst {}", n);
                trace!("in(old)  = {:?}", in_set_old);
                trace!("in(new)  = {:?}", livein[n]);
                trace!("out(old) = {:?}", out_set_old);
                trace!("out(new) = {:?}", liveout[n]);
            }
qinsoon's avatar
[wip]  
qinsoon committed
550

551 552 553
            is_changed = is_changed || n_changed;
        }
    }
554 555
}

556
// from Tailoring Graph-coloring Register Allocation For Runtime Compilation, Figure 4
557
pub fn build_chaitin_briggs (cf: &mut CompiledFunction, func: &MuFunctionVersion) -> InterferenceGraph {
558
    let _p = hprof::enter("regalloc: build live set");
qinsoon's avatar
[wip]  
qinsoon committed
559
    build_live_set(cf, func);
560 561 562
    drop(_p);

    let _p = hprof::enter("regalloc: build interference graph");
qinsoon's avatar
[wip]  
qinsoon committed
563 564

    info!("---start building interference graph---");
565
    
566 567 568
    let mut ig = InterferenceGraph::new();
    
    // precolor machine register nodes
569
    for reg in backend::all_regs().values() {
570 571
        let reg_id = reg.extract_ssa_id().unwrap();
        let node = ig.new_node(reg_id, &func.context);
qinsoon's avatar
qinsoon committed
572

qinsoon's avatar
qinsoon committed
573
        let precolor = backend::get_color_for_precolored(reg_id);
qinsoon's avatar
qinsoon committed
574 575

        ig.color_node(node, precolor);
576 577 578
    }
    
    // Initialize and creates nodes for all the involved temps/regs
qinsoon's avatar
qinsoon committed
579 580
    for i in 0..cf.mc().number_of_insts() {
        for reg_id in cf.mc().get_inst_reg_defines(i) {
581 582 583
            ig.new_node(reg_id, &func.context);
        }
        
qinsoon's avatar
qinsoon committed
584
        for reg_id in cf.mc().get_inst_reg_uses(i) {
585 586 587 588
            ig.new_node(reg_id, &func.context);
        }
    }
    
qinsoon's avatar
qinsoon committed
589
    for block in cf.mc().get_all_blocks() {
590
        // Current_Live(B) = LiveOut(B)
qinsoon's avatar
qinsoon committed
591
        let mut current_live = LinkedHashSet::from_vec(match cf.mc().get_ir_block_liveout(&block) {
592 593 594
            Some(liveout) => liveout.to_vec(),
            None => panic!("cannot find liveout for block {}", block)
        });
qinsoon's avatar
qinsoon committed
595 596 597 598 599 600
        if cfg!(debug_assertions) {
            trace!("Block{}: live out", block);
            for ele in current_live.iter() {
                trace!("{}", func.context.get_temp_display(*ele));
            }
        }
601
        
qinsoon's avatar
qinsoon committed
602
        let range = cf.mc().get_block_range(&block);
603
        if range.is_none() {
qinsoon's avatar
qinsoon committed
604
            warn!("Block{}: has no range (no instructions?)", block);
605 606
            continue;
        }
qinsoon's avatar
qinsoon committed
607
        trace!("Block{}: range = {:?}", block, range.as_ref().unwrap());
608 609 610
        
        // for every inst I in reverse order
        for i in range.unwrap().rev() {
qinsoon's avatar
qinsoon committed
611
            if cfg!(debug_assertions) {
qinsoon's avatar
[wip]  
qinsoon committed
612 613 614
                trace!("Block{}: Inst{}", block, i);
                cf.mc().trace_inst(i);
                trace!("current live: ");
qinsoon's avatar
qinsoon committed
615 616 617 618 619
                for ele in current_live.iter() {
                    trace!("{}", func.context.get_temp_display(*ele));
                }
            }

620
            let src : Option<MuID> = {
qinsoon's avatar
qinsoon committed
621 622 623
                if cf.mc().is_move(i) {
                    let src = cf.mc().get_inst_reg_uses(i);
                    let dst = cf.mc().get_inst_reg_defines(i);
624
                    
qinsoon's avatar
qinsoon committed
625 626 627
                    // src:  reg/imm/mem
                    // dest: reg/mem
                    // we dont care if src/dest is mem
qinsoon's avatar
qinsoon committed
628
                    if cf.mc().is_using_mem_op(i) {
629
                        None
qinsoon's avatar
qinsoon committed
630 631 632 633
                    } else {
                        if src.len() == 1 {
                            let node1 = ig.get_node(src[0]);
                            let node2 = ig.get_node(dst[0]);
qinsoon's avatar
qinsoon committed
634 635 636
                            trace!("add move between {} and {}",
                                   func.context.get_temp_display(src[0]),
                                   func.context.get_temp_display(dst[0]));
qinsoon's avatar
qinsoon committed
637 638 639 640 641 642
                            ig.add_move(node1, node2);
                            
                            Some(src[0])
                        } else {
                            None
                        }
643 644 645 646 647
                    }
                } else {
                    None
                }
            };
qinsoon's avatar
qinsoon committed
648
            trace!("Block{}: Inst{}: src={:?}", block, i, src);
649 650
            
            // for every definition D in I
qinsoon's avatar
qinsoon committed
651
            for d in cf.mc().get_inst_reg_defines(i) {
qinsoon's avatar
qinsoon committed
652
                trace!("Block{}: Inst{}: for definition {}", block, i, func.context.get_temp_display(d));
653 654 655
                // add an interference from D to every element E in Current_Live - {D}
                // creating nodes if necessary
                for e in current_live.iter() {
qinsoon's avatar
qinsoon committed
656 657 658
                    trace!("Block{}: Inst{}: for each live {}",
                           block, i,
                           func.context.get_temp_display(*e));
659
                    if src.is_none() || (src.is_some() && *e != src.unwrap()) {
qinsoon's avatar
qinsoon committed
660
                        let from = ig.get_node(d);
661 662
                        let to = ig.get_node(*e);
                        
qinsoon's avatar
qinsoon committed
663
                        if !ig.is_same_node(from, to) &&ig.is_same_group(from, to) && !ig.is_adj(from, to) {
664
                            if !ig.is_colored(from) {
qinsoon's avatar
qinsoon committed
665 666 667 668
                                trace!("Block{}: Inst{}: add interference between {} and {}",
                                       block, i,
                                       func.context.get_temp_display(d),
                                       func.context.get_temp_display(*e));
669 670 671
                                ig.add_interference_edge(from, to);
                            }
                            if !ig.is_colored(to) {
qinsoon's avatar
qinsoon committed
672 673 674 675
                                trace!("Block{}: Inst{}: add interference between {} and {}",
                                       block, i,
                                       func.context.get_temp_display(*e),
                                       func.context.get_temp_display(d));
676 677 678 679 680 681 682 683
                                ig.add_interference_edge(to, from);
                            }
                        }
                    }
                }
            }
            
            // for every definition D in I
qinsoon's avatar
qinsoon committed
684
            for d in cf.mc().get_inst_reg_defines(i) {
qinsoon's avatar
qinsoon committed
685 686 687
                trace!("Block{}: Inst{}: remove define {} from current_live",
                       block, i,
                       func.context.get_temp_display(d));
688
                // remove D from Current_Live
qinsoon's avatar
qinsoon committed
689
                current_live.remove(&d);
690 691 692
            }
            
            // for every use U in I
qinsoon's avatar
qinsoon committed
693
            for u in cf.mc().get_inst_reg_uses(i) {
qinsoon's avatar
qinsoon committed
694 695 696
                trace!("Block{}: Inst{}: add use {} to current_live",
                       block, i,
                       func.context.get_temp_display(u));
697
                // add U to Current_live
qinsoon's avatar
qinsoon committed
698
                current_live.insert(u);
699
            }
qinsoon's avatar
qinsoon committed
700 701 702 703 704 705 706

            if cfg!(debug_assertions) {
                trace!("Block{}: Inst{}: done. current_live:", block, i);
                for ele in current_live.iter() {
                    trace!("{}", func.context.get_temp_display(*ele));
                }
            }
707 708
        }
    }
qinsoon's avatar
[wip]  
qinsoon committed
709

710
    drop(_p);
qinsoon's avatar
[wip]  
qinsoon committed
711
    info!("---finish building interference graph---");
712
    ig
713
}