WARNING! Access to this system is limited to authorised users only.
Unauthorised users may be subject to prosecution.
Unauthorised access to this system is a criminal offence under Australian law (Federal Crimes Act 1914 Part VIA)
It is a criminal offence to:
(1) Obtain access to data without authority. -Penalty 2 years imprisonment.
(2) Damage, delete, alter or insert data without authority. -Penalty 10 years imprisonment.
User activity is monitored and recorded. Anyone using this system expressly consents to such monitoring and recording.

To protect your data, the CISO officer has suggested users to enable 2FA as soon as possible.
Currently 2.7% of users enabled 2FA.

coloring.rs 22 KB
Newer Older
qinsoon's avatar
qinsoon committed
1
2
3
use ast::ir::*;
use compiler::backend;
use compiler::backend::reg_alloc::graph_coloring;
4
5
use compiler::backend::reg_alloc::graph_coloring::liveness::InterferenceGraph;
use compiler::backend::reg_alloc::graph_coloring::liveness::{Node, Move};
6
use compiler::backend::reg_alloc::RegAllocFailure;
qinsoon's avatar
qinsoon committed
7
8
use compiler::machine_code::CompiledFunction;
use vm::VM;
9

10
use utils::vec_utils;
11
use utils::LinkedHashSet;
qinsoon's avatar
qinsoon committed
12

qinsoon's avatar
qinsoon committed
13
use std::cell::RefCell;
qinsoon's avatar
qinsoon committed
14
15
use std::collections::HashMap;

qinsoon's avatar
qinsoon committed
16
const COALESCING : bool = true;
17

18
19
pub struct GraphColoring {
    pub ig: InterferenceGraph,
qinsoon's avatar
qinsoon committed
20

21
22
    precolored: LinkedHashSet<Node>,
    colors: HashMap<backend::RegGroup, LinkedHashSet<MuID>>,
23
    pub colored_nodes: Vec<Node>,
qinsoon's avatar
qinsoon committed
24
    
25
    initial: Vec<Node>,
26
    degree: HashMap<Node, usize>,
qinsoon's avatar
qinsoon committed
27
    
28
    worklist_moves: Vec<Move>,
qinsoon's avatar
qinsoon committed
29
    movelist: HashMap<Node, RefCell<Vec<Move>>>,
30
31
32
33
    active_moves: LinkedHashSet<Move>,
    coalesced_nodes: LinkedHashSet<Node>,
    coalesced_moves: LinkedHashSet<Move>,
    constrained_moves: LinkedHashSet<Move>,
qinsoon's avatar
qinsoon committed
34
    alias: HashMap<Node, Node>,
qinsoon's avatar
qinsoon committed
35
    
36
    worklist_spill: Vec<Node>,
37
38
39
    spillable: HashMap<MuID, bool>,
    spilled_nodes: Vec<Node>,
    
40
41
    worklist_freeze: LinkedHashSet<Node>,
    frozen_moves: LinkedHashSet<Move>,
42
    
43
    worklist_simplify: LinkedHashSet<Node>,
44
    select_stack: Vec<Node>
qinsoon's avatar
qinsoon committed
45
46
}

47
impl GraphColoring {
qinsoon's avatar
qinsoon committed
48
    pub fn start (func: &mut MuFunctionVersion, cf: &mut CompiledFunction, vm: &VM) -> Result<GraphColoring, RegAllocFailure> {
qinsoon's avatar
qinsoon committed
49
        let mut coloring = GraphColoring {
qinsoon's avatar
qinsoon committed
50
51
            ig: graph_coloring::build_inteference_graph(cf, func),

52
            precolored: LinkedHashSet::new(),
53
54
            colors: {
                let mut map = HashMap::new();
55
56
                map.insert(backend::RegGroup::GPR, LinkedHashSet::new());
                map.insert(backend::RegGroup::FPR, LinkedHashSet::new());
57
58
59
                map
            },
            colored_nodes: Vec::new(),
qinsoon's avatar
qinsoon committed
60
            
61
            initial: Vec::new(),
qinsoon's avatar
qinsoon committed
62
63
            degree: HashMap::new(),
            
64
            worklist_moves: Vec::new(),
qinsoon's avatar
qinsoon committed
65
            movelist: HashMap::new(),
66
67
68
69
            active_moves: LinkedHashSet::new(),
            coalesced_nodes: LinkedHashSet::new(),
            coalesced_moves: LinkedHashSet::new(),
            constrained_moves: LinkedHashSet::new(),
qinsoon's avatar
qinsoon committed
70
            alias: HashMap::new(),
qinsoon's avatar
qinsoon committed
71
            
72
            worklist_spill: Vec::new(),
73
74
75
            spillable: HashMap::new(),
            spilled_nodes: Vec::new(),
            
76
77
            worklist_freeze: LinkedHashSet::new(),
            frozen_moves: LinkedHashSet::new(),
78
            
79
            worklist_simplify: LinkedHashSet::new(),
80
            select_stack: Vec::new()
qinsoon's avatar
qinsoon committed
81
82
        };
        
qinsoon's avatar
qinsoon committed
83
        match coloring.regalloc(func, cf, vm) {
84
85
86
            Ok(_) => Ok(coloring),
            Err(fail) => Err(fail)
        }
qinsoon's avatar
qinsoon committed
87
88
    }
    
qinsoon's avatar
qinsoon committed
89
    fn regalloc(&mut self, func: &mut MuFunctionVersion, cf: &mut CompiledFunction, vm: &VM) -> Result<(), RegAllocFailure> {
90
        trace!("Initializing coloring allocator...");
qinsoon's avatar
qinsoon committed
91
        
qinsoon's avatar
qinsoon committed
92
        // precolor for all machine registers
93
        for reg in backend::all_regs().values() {
94
95
96
97
98
            let reg_id = reg.extract_ssa_id().unwrap();
            let node = self.ig.get_node(reg_id);
            self.precolored.insert(node);
        }
        
qinsoon's avatar
qinsoon committed
99
        // put usable registers as available colors
100
        for reg in backend::all_usable_regs().iter() {
qinsoon's avatar
qinsoon committed
101
            let reg_id = reg.extract_ssa_id().unwrap();
qinsoon's avatar
qinsoon committed
102
103
            let group = backend::pick_group_for_reg(reg_id);
            self.colors.get_mut(&group).unwrap().insert(reg_id);
qinsoon's avatar
qinsoon committed
104
105
106
107
        }
        
        for node in self.ig.nodes() {
            if !self.ig.is_colored(node) {
108
                self.initial.push(node);
109
                let outdegree = self.ig.outdegree_of(node);
110
111
                self.degree.insert(node, outdegree);
                trace!("{} has a degree of {}", self.node_info(node), outdegree);
qinsoon's avatar
qinsoon committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
            }
        }
        
        self.build();
        self.make_work_list();
        
        while {
            if !self.worklist_simplify.is_empty() {
                self.simplify();
            } else if !self.worklist_moves.is_empty() {
                self.coalesce();
            } else if !self.worklist_freeze.is_empty() {
                self.freeze();
            } else if !self.worklist_spill.is_empty() {
                self.select_spill();
            }
            
            ! (self.worklist_simplify.is_empty()
            && self.worklist_moves.is_empty()
            && self.worklist_freeze.is_empty()
            && self.worklist_spill.is_empty())
        } {}
        
qinsoon's avatar
qinsoon committed
135
136
137
138
139
140
141
142
143
144
        self.assign_colors();

        if !self.spilled_nodes.is_empty() {
            trace!("spill required");
            self.rewrite_program(func, cf, vm);

            GraphColoring::start(func, cf, vm);
        }

        Ok(())
qinsoon's avatar
qinsoon committed
145
146
147
    }
    
    fn build(&mut self) {
qinsoon's avatar
qinsoon committed
148
149
        if COALESCING {
            trace!("coalescing enabled, build move list");
qinsoon's avatar
qinsoon committed
150
151
152
            let ref ig = self.ig;
            let ref mut movelist = self.movelist;
            for m in ig.moves() {
qinsoon's avatar
qinsoon committed
153
                trace!("add {:?} to movelist", m);
154
                self.worklist_moves.push(m.clone());
qinsoon's avatar
qinsoon committed
155
156
                GraphColoring::movelist_mut(movelist, m.from).borrow_mut().push(m.clone());
                GraphColoring::movelist_mut(movelist, m.to).borrow_mut().push(m.clone());
qinsoon's avatar
qinsoon committed
157
            }
qinsoon's avatar
qinsoon committed
158
159
        } else {
            trace!("coalescing disabled");
qinsoon's avatar
qinsoon committed
160
161
162
163
        }
    }
    
    fn make_work_list(&mut self) {
164
        trace!("Making work list from initials...");
qinsoon's avatar
qinsoon committed
165
        while !self.initial.is_empty() {
166
            let node = self.initial.pop().unwrap();
qinsoon's avatar
qinsoon committed
167
168
169
170
            
            if {
                // condition: degree >= K
                let degree = self.ig.degree_of(node); 
171
                let n_regs = self.n_regs_for_node(node);
qinsoon's avatar
qinsoon committed
172
173
174
                
                degree >= n_regs
            } {
175
                trace!("{} 's degree >= reg number limit (K), push to spill list", self.node_info(node));
176
                self.worklist_spill.push(node);
qinsoon's avatar
qinsoon committed
177
            } else if self.is_move_related(node) {
178
                trace!("{} is move related, push to freeze list", self.node_info(node));
qinsoon's avatar
qinsoon committed
179
180
                self.worklist_freeze.insert(node);
            } else {
181
                trace!("{} has small degree and not move related, push to simplify list", self.node_info(node));
qinsoon's avatar
qinsoon committed
182
183
184
185
186
                self.worklist_simplify.insert(node);
            }
        }
    }
    
187
188
189
190
    fn n_regs_for_node(&self, node: Node) -> usize {
        backend::number_of_regs_in_group(self.ig.get_group_of(node))
    }
    
qinsoon's avatar
qinsoon committed
191
192
193
194
    fn is_move_related(&mut self, node: Node) -> bool {
        !self.node_moves(node).is_empty()
    }
    
195
196
    fn node_moves(&mut self, node: Node) -> LinkedHashSet<Move> {
        let mut moves = LinkedHashSet::new();
qinsoon's avatar
qinsoon committed
197
198
199
200
201
202
203
204
205
206
207
        
        // addAll(active_moves)
        for m in self.active_moves.iter() {
            moves.insert(m.clone());
        }
        
        // addAll(worklist_moves)
        for m in self.worklist_moves.iter() {
            moves.insert(m.clone());
        }
        
208
        let mut retained = LinkedHashSet::new();
qinsoon's avatar
qinsoon committed
209
        let movelist = &GraphColoring::movelist_mut(&mut self.movelist, node).borrow();
qinsoon's avatar
qinsoon committed
210
        for m in moves.iter() {
211
            if vec_utils::find_value(movelist, *m).is_some() {
qinsoon's avatar
qinsoon committed
212
213
214
215
216
217
218
                retained.insert(*m);
            }
        }
        
        retained
    }
    
qinsoon's avatar
qinsoon committed
219
220
221
222
223
224
225
226
227
    // avoid using &mut self as argument
    // in build(), we will need to mutate on self.movelist while
    // holding an immmutable reference of self(self.ig)
    fn movelist_mut(list: &mut HashMap<Node, RefCell<Vec<Move>>>, node: Node) -> &RefCell<Vec<Move>> {
        GraphColoring::movelist_check(list, node);
        unsafe {GraphColoring::movelist_nocheck(list, node)}
    }
    
    fn movelist_check(list: &mut HashMap<Node, RefCell<Vec<Move>>>, node: Node) {
qinsoon's avatar
qinsoon committed
228
        if !list.contains_key(&node) {
qinsoon's avatar
qinsoon committed
229
            list.insert(node, RefCell::new(Vec::new()));
qinsoon's avatar
qinsoon committed
230
        }
qinsoon's avatar
qinsoon committed
231
232
233
234
235
    }
    
    // allows getting the Vec<Move> without a mutable reference of the hashmap
    unsafe fn movelist_nocheck(list: &HashMap<Node, RefCell<Vec<Move>>>, node: Node) -> &RefCell<Vec<Move>> {
        list.get(&node).unwrap()
qinsoon's avatar
qinsoon committed
236
    }
237
238
    
    fn simplify(&mut self) {
239
        // remove next element from worklist_simplify, we know its not empty
240
        let node = self.worklist_simplify.pop_front().unwrap();
241
242
        
        trace!("Simplifying {}", self.node_info(node));
243
244
245
        
        self.select_stack.push(node);
        
246
        for m in self.adjacent(node).iter() {
247
            self.decrement_degree(*m);
248
249
250
        }
    }
    
251
252
    fn adjacent(&self, n: Node) -> LinkedHashSet<Node> {
        let mut adj = LinkedHashSet::new();
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        
        // add n's successors
        for s in self.ig.outedges_of(n) {
            adj.insert(s);
        }
        
        // removeAll(select_stack)
        for s in self.select_stack.iter() {
            adj.remove(s);
        }
        
        // removeAll(coalesced_nodes)
        for s in self.coalesced_nodes.iter() {
            adj.remove(s);
        }
        
        adj
    }
    
272
    fn degree(&self, n: Node) -> usize {
273
274
275
276
277
278
279
        match self.degree.get(&n) {
            Some(d) => *d,
            None => 0
        }
    }
    
    fn decrement_degree(&mut self, n: Node) {
280
281
282
283
284
285
        if self.precolored.contains(&n) {
            return;
        }
        
        trace!("decrement degree of {}", self.node_info(n));        
        
286
        let d = self.degree(n);
287
        debug_assert!(d != 0);
288
289
        self.degree.insert(n, d - 1);
        
290
        if d == self.n_regs_for_node(n) {
qinsoon's avatar
qinsoon committed
291
            trace!("{}'s degree is K, no longer need to spill it", self.node_info(n));
292
293
            let mut nodes = self.adjacent(n);
            nodes.insert(n);
qinsoon's avatar
qinsoon committed
294
            trace!("enable moves of {:?}", nodes);
295
296
297
298
299
            self.enable_moves(nodes);
            
            vec_utils::remove_value(&mut self.worklist_spill, n);
            
            if self.is_move_related(n) {
qinsoon's avatar
qinsoon committed
300
                trace!("{} is move related, push to freeze list", self.node_info(n));
301
302
                self.worklist_freeze.insert(n);
            } else {
qinsoon's avatar
qinsoon committed
303
                trace!("{} is not move related, push to simplify list", self.node_info(n));
304
305
306
307
308
                self.worklist_simplify.insert(n);
            }
        }
    }
    
309
310
311
312
313
    fn enable_moves(&mut self, nodes: LinkedHashSet<Node>) {
        for n in nodes.iter() {
            let n = *n;
            for mov in self.node_moves(n).iter() {
                let mov = *mov;
314
315
316
317
318
319
320
321
322
                if self.active_moves.contains(&mov) {
                    self.active_moves.insert(mov);
                    self.worklist_moves.push(mov);
                }
            }
        }
    }
    
    fn coalesce(&mut self) {
qinsoon's avatar
qinsoon committed
323
324
        let m = self.worklist_moves.pop().unwrap();
        
qinsoon's avatar
qinsoon committed
325
326
        trace!("Coalescing on {}", self.move_info(m));
        
qinsoon's avatar
qinsoon committed
327
328
        let x = self.get_alias(m.from);
        let y = self.get_alias(m.to);
qinsoon's avatar
qinsoon committed
329
        trace!("resolve alias: from {} to {}", self.node_info(x), self.node_info(y));
qinsoon's avatar
qinsoon committed
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        
        let (u, v, precolored_u, precolored_v) = {
            if self.precolored.contains(&y) {
                let u = y;
                let v = x;
                let precolored_u = true;
                let precolored_v = self.precolored.contains(&v);
                
                (u, v, precolored_u, precolored_v)
            } else {
                let u = x;
                let v = y;
                let precolored_u = self.precolored.contains(&u);
                let precolored_v = self.precolored.contains(&v);
                
                (u, v, precolored_u, precolored_v)
            }
        };
qinsoon's avatar
qinsoon committed
348
349
350
351
        trace!("u={}, v={}, precolored_u={}, precolroed_v={}", 
            self.node_info(u),
            self.node_info(v),
            precolored_u, precolored_v);
qinsoon's avatar
qinsoon committed
352
353
        
        if u == v {
qinsoon's avatar
qinsoon committed
354
            trace!("u == v, coalesce the move");
qinsoon's avatar
qinsoon committed
355
356
357
358
359
            self.coalesced_moves.insert(m);
            if !precolored_u {
                self.add_worklist(u);
            }
        } else if precolored_v || self.ig.is_adj(u, v) {
qinsoon's avatar
qinsoon committed
360
361
            trace!("v is precolored or u,v is adjacent, the move is constrained");
            self.constrained_moves.insert(m);
qinsoon's avatar
qinsoon committed
362
363
364
365
366
367
368
369
            if !precolored_u {
                self.add_worklist(u);
            }
            if !precolored_v {
                self.add_worklist(v);
            }
        } else if (precolored_u && self.ok(u, v)) 
          || (!precolored_u && self.conservative(u, v)) {
qinsoon's avatar
qinsoon committed
370
            trace!("precolored_u&&ok(u,v) || !precolored_u&&conserv(u,v), coalesce and combine the move");  
qinsoon's avatar
qinsoon committed
371
372
373
374
375
376
            self.coalesced_moves.insert(m);
            self.combine(u, v);
            if !precolored_u {
                self.add_worklist(u);
            }
        } else {
qinsoon's avatar
qinsoon committed
377
            trace!("cannot coalesce the move");
qinsoon's avatar
qinsoon committed
378
379
380
381
            self.active_moves.insert(m);
        }
    }
    
382
    pub fn get_alias(&self, node: Node) -> Node {
qinsoon's avatar
qinsoon committed
383
384
385
386
387
388
389
390
        if self.coalesced_nodes.contains(&node) {
            self.get_alias(*self.alias.get(&node).unwrap())
        } else {
            node
        }
    }
    
    fn add_worklist(&mut self, node: Node) {
391
        if !self.is_move_related(node) && self.degree(node) < self.n_regs_for_node(node) {
qinsoon's avatar
qinsoon committed
392
393
394
395
396
397
            self.worklist_freeze.remove(&node);
            self.worklist_simplify.insert(node);
        }
    }
    
    fn ok(&self, u: Node, v: Node) -> bool {
398
399
        for t in self.adjacent(v).iter() {
            let t = *t;
qinsoon's avatar
qinsoon committed
400
            if !self.precolored.contains(&t) 
401
              || self.degree(t) < self.n_regs_for_node(t)
qinsoon's avatar
qinsoon committed
402
403
404
405
406
407
408
409
410
411
412
413
414
              || self.ig.is_adj(t, u) {
                return false;
            } 
        }
        
        true
    }
    
    fn conservative(&self, u: Node, v: Node) -> bool {
        debug_assert!(self.ig.get_group_of(u) == self.ig.get_group_of(v));
        
        let adj_u = self.adjacent(u);
        let adj_v = self.adjacent(v);
415
416
417
418
419
        let nodes = {
            let mut ret = adj_u;
            ret.add_all(adj_v);
            ret
        };
qinsoon's avatar
qinsoon committed
420
421
        
        let mut k = 0;
422
        for n in nodes.iter() {
423
            if self.precolored.contains(n) || self.degree(*n) >= self.n_regs_for_node(*n) {
qinsoon's avatar
qinsoon committed
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
                k += 1;
            }
        }
        
        k < self.n_regs_for_node(u)
    }
    
    fn combine(&mut self, u: Node, v: Node) {
        if self.worklist_freeze.contains(&v) {
            self.worklist_freeze.remove(&v);
            self.coalesced_nodes.insert(v);
        } else {
            vec_utils::remove_value(&mut self.worklist_spill, v);
            self.coalesced_nodes.insert(v);
        }
        
        self.alias.insert(v, u); 
        
        {
            let ref mut movelist = self.movelist;
            GraphColoring::movelist_check(movelist, u);
            GraphColoring::movelist_check(movelist, v);
            // we checked before getting the movelist, its safe
            // use nocheck version which requires only immutable references of movelist
            // avoid maintaining a mutable reference of movelist alive
            let movelist_u = &mut unsafe {GraphColoring::movelist_nocheck(movelist, u)}.borrow_mut();
            let movelist_v = &mut unsafe {GraphColoring::movelist_nocheck(movelist, v)}.borrow_mut();
            
            // addAll()
            movelist_u.extend_from_slice(movelist_v.as_slice());
        }
        
456
        let mut nodes = LinkedHashSet::new();
qinsoon's avatar
qinsoon committed
457
458
459
        nodes.insert(v);
        self.enable_moves(nodes);
        
460
461
        for t in self.adjacent(v).iter() {
            let t = *t;
qinsoon's avatar
qinsoon committed
462
463
464
465
466
            self.add_edge(t, u);
            self.decrement_degree(t);
        }
        
        if self.worklist_freeze.contains(&u)
467
          && self.degree(u) >= self.n_regs_for_node(u) {
qinsoon's avatar
qinsoon committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
            self.worklist_freeze.remove(&u);
            self.worklist_spill.push(u);
        }
    }
    
    fn add_edge(&mut self, u: Node, v: Node) {
        if u != v && !self.ig.is_adj(u, v) {
            if !self.precolored.contains(&u) {
                self.ig.add_interference_edge(u, v);
                let degree_u = self.degree(u);
                self.degree.insert(u, degree_u + 1);
            }
            if !self.precolored.contains(&v) {
                self.ig.add_interference_edge(v, u);
                let degree_v = self.degree(v);
                self.degree.insert(v, degree_v + 1);
            }
        }
486
487
488
    }
    
    fn freeze(&mut self) {
qinsoon's avatar
qinsoon committed
489
        // it is not empty (checked before)
490
        let node = self.worklist_freeze.pop_front().unwrap();
qinsoon's avatar
qinsoon committed
491
        trace!("Freezing {}...", self.node_info(node));
qinsoon's avatar
qinsoon committed
492
493
494
495
496
497
        
        self.worklist_simplify.insert(node);
        self.freeze_moves(node);
    }
    
    fn freeze_moves(&mut self, u: Node) {
498
499
        for m in self.node_moves(u).iter() {
            let m = *m;
qinsoon's avatar
qinsoon committed
500
501
502
503
504
505
506
507
508
509
            let mut v = self.get_alias(m.from);
            if v == self.get_alias(u) {
                v = self.get_alias(m.to);
            }
            
            self.active_moves.remove(&m);
            self.frozen_moves.insert(m);
            
            if !self.precolored.contains(&v) 
               && self.node_moves(v).is_empty()
510
               && self.degree(v) < self.n_regs_for_node(v) {
qinsoon's avatar
qinsoon committed
511
512
513
514
                self.worklist_freeze.remove(&v);
                self.worklist_simplify.insert(v);
            }
        }
515
516
517
    }
    
    fn select_spill(&mut self) {
qinsoon's avatar
qinsoon committed
518
        trace!("Selecting a node to spill...");
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
        let mut m : Option<Node> = None;
        
        for n in self.worklist_spill.iter() {
            let n = *n;
            if m.is_none() {
                m = Some(n);
            } else if {
                // m is not none
                let temp = self.ig.get_temp_of(m.unwrap());
                let spillable = {match self.spillable.get(&temp) {
                    None => {
                        //by default, its spillable
                        true
                    },
                    Some(b) => *b
                }};
                
                !spillable
            } {
                m = Some(n);
            } else if (self.ig.get_spill_cost(n) / (self.degree(n) as f32)) 
              < (self.ig.get_spill_cost(m.unwrap()) / (self.degree(m.unwrap()) as f32)) {
                m = Some(n);
            }
        }
        
        // m is not none
        let m = m.unwrap();
qinsoon's avatar
qinsoon committed
547
548
        trace!("Spilling {}...", self.node_info(m));
        
549
550
551
        vec_utils::remove_value(&mut self.worklist_spill, m);
        self.worklist_simplify.insert(m);
        self.freeze_moves(m);
552
553
    }
    
qinsoon's avatar
qinsoon committed
554
    fn assign_colors(&mut self) -> Result<(), ()> {
qinsoon's avatar
qinsoon committed
555
        trace!("---coloring done---");
556
557
        while !self.select_stack.is_empty() {
            let n = self.select_stack.pop().unwrap();
qinsoon's avatar
qinsoon committed
558
            trace!("Assigning color to {}", self.node_info(n));
559
            
560
            let mut ok_colors : LinkedHashSet<MuID> = self.colors.get(&self.ig.get_group_of(n)).unwrap().clone();
561
562
563
564
565
566
567
            for w in self.ig.outedges_of(n) {
                let w = self.get_alias(w);
                match self.ig.get_color_of(w) {
                    None => {}, // do nothing
                    Some(color) => {ok_colors.remove(&color);}
                }
            }
qinsoon's avatar
qinsoon committed
568
            trace!("available colors: {:?}", ok_colors);
569
570
            
            if ok_colors.is_empty() {
qinsoon's avatar
qinsoon committed
571
                trace!("{} is a spilled node", self.node_info(n));
572
573
                self.spilled_nodes.push(n);
            } else {
574
                let first_available_color = ok_colors.pop_front().unwrap();
qinsoon's avatar
qinsoon committed
575
                trace!("Color {} as {}", self.node_info(n), first_available_color);
576
577
                
                if !backend::is_callee_saved(first_available_color) {
578
                    warn!("Use caller saved register {}", first_available_color);
579
580
                }
                
581
                self.colored_nodes.push(n);
qinsoon's avatar
qinsoon committed
582
                self.ig.color_node(n, first_available_color);
583
584
585
586
587
588
589
            }
        }
        
        for n in self.coalesced_nodes.iter() {
            let n = *n;
            let alias = self.get_alias(n);
            let alias_color = self.ig.get_color_of(alias).unwrap();
qinsoon's avatar
qinsoon committed
590
591
592
            
            trace!("Assign color to {} based on aliased {}", self.node_info(n), self.node_info(alias));
            trace!("Color {} as {}", self.node_info(n), alias_color);
593
594
            self.ig.color_node(n, alias_color);
        }
595
596

        Ok(())
597
    }
qinsoon's avatar
qinsoon committed
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

    fn rewrite_program(&mut self, func: &mut MuFunctionVersion, cf: &mut CompiledFunction, vm: &VM) {
        let spills = self.spills();

        let mut spilled_mem = HashMap::new();

        // allocating frame slots for every spilled temp
        for reg_id in spills.iter() {
            let ssa_entry = match func.context.get_value(*reg_id) {
                Some(entry) => entry,
                None => panic!("The spilled register {} is not in func context", reg_id)
            };
            let mem = cf.frame.alloc_slot_for_spilling(ssa_entry.value().clone(), vm);

            spilled_mem.insert(*reg_id, mem);
        }

        let new_temps = backend::spill_rewrite(&spilled_mem, func, cf, vm);
//
//        self.spilled_nodes.clear();
//
//        self.initial = {
//            let mut ret = vec![];
//
//            for node in self.colored_nodes.iter() {
//                vec_utils::add_unique(&mut ret, node.clone());
//            }
//            for node in self.coalesced_nodes.iter() {
//                vec_utils::add_unique(&mut ret, node.clone());
//            }
//
//            // create nodes for every new temp
//            for tmp in new_temps {
//                let node = self.ig.new_node(tmp.id(), &func.context);
//                vec_utils::add_unique(&mut ret, node.clone());
//            }
//
//            ret
//        };
//
//        self.colored_nodes.clear();
//        self.coalesced_nodes.clear();
    }
641
642
643
644
645
646
647
648
649
650
651
652
    
    pub fn spills(&self) -> Vec<MuID> {
        let mut spills = vec![];
        
        let spill_count = self.spilled_nodes.len();
        if spill_count > 0 {
            for n in self.spilled_nodes.iter() {
                spills.push(self.ig.get_temp_of(*n));
            }
        }
        
        spills
653
    }
qinsoon's avatar
qinsoon committed
654
655
656
657
658
659
660
661
662
    
    fn node_info(&self, node: Node) -> String {
        let reg = self.ig.get_temp_of(node);
        format!("{:?}/Reg {}", node, reg)
    }
    
    fn move_info(&self, m: Move) -> String {
        format!("Move: {} -> {}", self.node_info(m.from), self.node_info(m.to))
    }
663
}