gen_mov_phi.rs 17.5 KB
Newer Older
1
// Copyright 2017 The Australian National University
2
//
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9 10 11 12 13 14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17 18 19 20 21 22 23
use ast::ir::*;
use ast::ptr::*;
use ast::inst::*;
use vm::VM;

use compiler::CompilerPass;
use std::any::Any;

pub struct GenMovPhi {
24
    name: &'static str
25 26 27 28
}

impl GenMovPhi {
    pub fn new() -> GenMovPhi {
29
        GenMovPhi {
30
            name: "Generate Phi Moves"
31
        }
32 33 34 35 36
    }
}

struct IntermediateBlockInfo {
    blk_id: MuID,
37
    blk_name: MuName,
38
    target: MuID,
39
    from_args: Vec<P<TreeNode>>
40 41 42 43 44 45 46 47 48 49 50 51 52 53
}

impl CompilerPass for GenMovPhi {
    fn name(&self) -> &'static str {
        self.name
    }

    fn as_any(&self) -> &Any {
        self
    }

    fn visit_function(&mut self, vm: &VM, func: &mut MuFunctionVersion) {
        let mut f_content = func.content.take().unwrap();

54 55 56
        // we do this with two steps.
        // first step collects information about intermediate blocks
        // and second step inserts intermediate blocks
57
        let mut new_blocks_to_insert: Vec<IntermediateBlockInfo> = vec![];
58

59
        // first step - collects info on intermediate blocks
60 61 62 63
        for (blk_id, mut block) in f_content.blocks.iter_mut() {
            trace!("block: {}", blk_id);

            // old block content
qinsoon's avatar
qinsoon committed
64
            let block_content = block.content.as_ref().unwrap().clone();
65 66 67 68 69 70 71

            let mut new_body = vec![];

            let mut i = 0;
            let i_last = block_content.body.len() - 1;
            for node in block_content.body.iter() {
                if i != i_last {
72
                    // if this is last instruction, we simply copy it
73 74
                    new_body.push(node.clone());
                } else {
75 76
                    // otherwise, we need to check if we need to insert intermediate block
                    // and rewrite the inst
77 78 79 80
                    trace!("last instruction is {}", node);
                    let last_inst = node.clone();
                    match last_inst.v {
                        TreeNode_::Instruction(inst) => {
81
                            let ref ops = inst.ops;
82
                            let inst_name = inst.name().clone();
83
                            match inst.v {
84 85 86 87
                                Instruction_::Branch2 {
                                    cond,
                                    true_dest,
                                    false_dest,
88
                                    true_prob
89
                                } => {
90
                                    // check and insert intermediate blocks for true/false dest
91 92 93 94 95 96
                                    let true_dest = process_dest(
                                        true_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
97
                                        "true"
98 99 100 101 102 103 104
                                    );
                                    let false_dest = process_dest(
                                        false_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
105
                                        "false"
106
                                    );
107

108
                                    // rewrite the instruction
109
                                    let new_inst = func.new_inst(Instruction {
110 111
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
112
                                        ops: ops.to_vec(),
113 114 115 116
                                        v: Instruction_::Branch2 {
                                            cond: cond,
                                            true_dest: true_dest,
                                            false_dest: false_dest,
117 118
                                            true_prob: true_prob
                                        }
119 120 121 122 123
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                }
124 125 126 127 128 129 130
                                Instruction_::Call { data, resume } => {
                                    let norm_dest = process_dest(
                                        resume.normal_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
131
                                        "norm"
132 133 134 135 136 137 138
                                    );
                                    let exn_dest = process_dest(
                                        resume.exn_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
139
                                        "exc"
140 141 142
                                    );

                                    let new_inst = func.new_inst(Instruction {
143 144
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
145
                                        ops: ops.to_vec(),
146 147
                                        v: Instruction_::Call {
                                            data: data.clone(),
148
                                            resume: ResumptionData {
149
                                                normal_dest: norm_dest,
150 151 152
                                                exn_dest: exn_dest
                                            }
                                        }
153 154 155 156 157
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                }
158 159 160 161 162 163 164
                                Instruction_::CCall { data, resume } => {
                                    let norm_dest = process_dest(
                                        resume.normal_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
165
                                        "norm"
166 167 168 169 170 171 172
                                    );
                                    let exn_dest = process_dest(
                                        resume.exn_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
173
                                        "exc"
174 175 176
                                    );

                                    let new_inst = func.new_inst(Instruction {
177 178
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
179
                                        ops: ops.to_vec(),
180 181
                                        v: Instruction_::Call {
                                            data: data.clone(),
182
                                            resume: ResumptionData {
183
                                                normal_dest: norm_dest,
184 185 186
                                                exn_dest: exn_dest
                                            }
                                        }
187 188 189 190
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
191 192 193 194
                                }
                                Instruction_::Switch {
                                    cond,
                                    default,
195
                                    mut branches
196 197 198 199 200 201 202
                                } => {
                                    let default_dest = process_dest(
                                        default,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
203
                                        "default"
204 205 206 207 208 209 210 211 212 213 214
                                    );

                                    let new_branches = branches
                                        .drain(..)
                                        .map(|pair| {
                                            let dest = process_dest(
                                                pair.1,
                                                &mut new_blocks_to_insert,
                                                &ops,
                                                vm,
                                                &inst_name,
215
                                                format!("case_{}", pair.0).as_str()
216 217 218 219 220 221
                                            );
                                            (pair.0, dest)
                                        })
                                        .collect();

                                    let new_inst = func.new_inst(Instruction {
222 223
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
224
                                        ops: ops.to_vec(),
225 226 227
                                        v: Instruction_::Switch {
                                            cond: cond,
                                            default: default_dest,
228 229
                                            branches: new_branches
                                        }
230 231 232 233 234
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
                                }
235 236
                                Instruction_::Watchpoint { .. } => unimplemented!(),
                                Instruction_::WPBranch { .. } => unimplemented!(),
237 238 239 240 241 242
                                Instruction_::SwapStackExc {
                                    stack,
                                    is_exception,
                                    args,
                                    resume
                                } => {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
                                    let norm_dest = process_dest(
                                        resume.normal_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
                                        "norm"
                                    );
                                    let exn_dest = process_dest(
                                        resume.exn_dest,
                                        &mut new_blocks_to_insert,
                                        &ops,
                                        vm,
                                        &inst_name,
                                        "exc"
                                    );

                                    let new_inst = func.new_inst(Instruction {
                                        hdr: inst.hdr.clone(),
                                        value: inst.value.clone(),
                                        ops: ops.to_vec(),
                                        v: Instruction_::SwapStackExc {
                                            stack: stack,
                                            is_exception: is_exception,
                                            args: args,
                                            resume: ResumptionData {
                                                normal_dest: norm_dest,
                                                exn_dest: exn_dest
                                            }
                                        }
                                    });

                                    trace!("rewrite to {}", new_inst);
                                    new_body.push(new_inst);
277
                                }
278
                                Instruction_::ExnInstruction { .. } => unimplemented!(),
279 280 281 282 283 284
                                _ => {
                                    trace!("no rewrite");
                                    new_body.push(node.clone())
                                }
                            }
                        }
285
                        _ => panic!("expect a terminal instruction")
286 287 288 289 290 291
                    }
                }

                i += 1;
            }

292 293 294 295
            block.content = Some(BlockContent {
                args: block_content.args.to_vec(),
                exn_arg: block_content.exn_arg.clone(),
                body: new_body,
296
                keepalives: block_content.keepalives.clone()
297 298 299
            });
        }

300
        // second step - insert new blocks
301
        for block_info in new_blocks_to_insert {
302
            // create intermediate block
303
            let block = {
304
                let target_id = block_info.target; //
305 306
                let mut ret = Block::new(MuEntityHeader::named(
                    block_info.blk_id,
307
                    block_info.blk_name.clone()
308
                ));
309

310
                let mut target_block = f_content.get_block_mut(target_id);
311 312
                assert!(target_block.content.is_some());

313 314 315
                // if target_block is an exception block,
                // set its exn argument to None, and set this new block as an exception block
                let exn_arg = target_block.content.as_mut().unwrap().exn_arg.take();
316 317
                let ref target_args = target_block.content.as_ref().unwrap().args;

318
                ret.content = Some(BlockContent {
319
                    args: vec![],
320
                    exn_arg: exn_arg,
321 322 323 324 325 326
                    body: {
                        let mut vec = vec![];

                        // move every from_arg to target_arg
                        let mut i = 0;
                        for arg in block_info.from_args.iter() {
327 328 329 330 331 332 333 334 335 336 337 338 339
                            let ref target_arg = target_args[i];
                            // when a block branches to itself, it is possible that
                            // arg is the same as target_arg
                            if arg.as_value() != target_arg {
                                let m = func.new_inst(Instruction {
                                    hdr: MuEntityHeader::unnamed(vm.next_id()),
                                    value: Some(vec![target_args[i].clone()]),
                                    ops: vec![arg.clone()],
                                    v: Instruction_::Move(0)
                                });

                                vec.push(m);
                            }
340 341 342 343 344

                            i += 1;
                        }

                        // branch to target
345
                        let b = func.new_inst(Instruction {
346 347
                            hdr: MuEntityHeader::unnamed(vm.next_id()),
                            value: None,
348
                            ops: vec![],
349
                            v: Instruction_::Branch1(Destination {
350
                                target: target_block.hdr.clone(),
351 352
                                args: vec![]
                            })
353 354 355 356 357
                        });
                        vec.push(b);

                        vec
                    },
358
                    keepalives: None
359 360 361 362 363 364 365 366 367 368
                });

                trace!("inserting new intermediate block: {:?}", ret);

                ret
            };

            f_content.blocks.insert(block.id(), block);
        }

369
        func.content = Some(f_content);
370 371 372
    }
}

373 374 375 376 377
/// returns the destination.
/// if the instruction passes any argument to its destination,
/// we need an intermediate block to move the arguments, return
/// the intermediate block as destination. Otherwise, return
/// the original destination
378 379 380 381 382 383
fn process_dest(
    dest: Destination,
    blocks_to_insert: &mut Vec<IntermediateBlockInfo>,
    ops: &Vec<P<TreeNode>>,
    vm: &VM,
    inst: &MuName,
384
    label: &str
385
) -> Destination {
386 387 388 389 390 391 392 393 394
    if dest.args.is_empty() {
        dest
    } else {
        let target = dest.target;

        let mut from_args = vec![];
        for arg in dest.args.iter() {
            let from_arg = match arg {
                &DestArg::Normal(i) => ops[i].clone(),
395
                &DestArg::Freshbound(_) => unimplemented!()
396 397 398
            };

            from_args.push(from_arg);
399
        }
400 401

        let new_blk_id = vm.next_id();
402
        let new_blck_name = Arc::new(format!("{}:{}:#{}-#{}", inst, label, new_blk_id, target));
403 404

        let dest = Destination {
405
            target: MuEntityHeader::named(new_blk_id, new_blck_name.clone()),
406
            args: vec![]
407 408 409 410
        };

        blocks_to_insert.push(IntermediateBlockInfo {
            blk_id: new_blk_id,
411 412
            blk_name: new_blck_name,
            target: target.id(),
413
            from_args: from_args
414 415 416 417
        });

        dest
    }
418
}