Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement control flow graph construction #3037

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 42 additions & 2 deletions cli/src/debug/optimizer.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use boa_engine::{
builtins::function::OrdinaryFunction,
js_string,
object::{FunctionObjectBuilder, ObjectInitializer},
optimizer::OptimizerOptions,
optimizer::{control_flow_graph::ControlFlowGraph, OptimizerOptions},
property::Attribute,
Context, JsArgs, JsObject, JsResult, JsValue, NativeFunction,
Context, JsArgs, JsNativeError, JsObject, JsResult, JsValue, NativeFunction,
};

fn get_constant_folding(_: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
Expand Down Expand Up @@ -36,6 +37,44 @@ fn set_statistics(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsRes
Ok(JsValue::undefined())
}

fn graph(_: &JsValue, args: &[JsValue], _context: &mut Context) -> JsResult<JsValue> {
let Some(value) = args.get(0) else {
return Err(JsNativeError::typ()
.with_message("expected function argument")
.into());
};

let Some(object) = value.as_object() else {
return Err(JsNativeError::typ()
.with_message(format!("expected object, got {}", value.type_of()))
.into());
};
let object = object.borrow();
let Some(function) = object.downcast_ref::<OrdinaryFunction>() else {
return Err(JsNativeError::typ()
.with_message("expected function object")
.into());
};
let code = function.codeblock();

let cfg = ControlFlowGraph::generate_from_codeblock(code);
println!("{cfg:#?}");

let bytecode = cfg.finalize();
assert_eq!(code.bytecode(), &bytecode);

// let mut cfg = ControlFlowGraph::generate(&bytecode, &[]);
// println!("Original\n{cfg:#?}\n");

// let changed = GraphSimplification::perform(&mut cfg);
// println!("Simplified({changed}) \n{cfg:#?}");

// let changed = GraphEliminateUnreachableBasicBlocks::perform(&mut cfg);
// println!("Eliminate Unreachble({changed}) \n{cfg:#?}");

Ok(JsValue::undefined())
}

pub(super) fn create_object(context: &mut Context) -> JsObject {
let get_constant_folding = FunctionObjectBuilder::new(
context.realm(),
Expand Down Expand Up @@ -75,5 +114,6 @@ pub(super) fn create_object(context: &mut Context) -> JsObject {
Some(set_statistics),
Attribute::WRITABLE | Attribute::CONFIGURABLE | Attribute::NON_ENUMERABLE,
)
.function(NativeFunction::from_fn_ptr(graph), js_string!("graph"), 1)
.build()
}
1 change: 1 addition & 0 deletions core/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ bytemuck = { version = "1.14.0", features = ["derive"] }
arrayvec = "0.7.4"
intrusive-collections = "0.9.6"
cfg-if = "1.0.0"
slotmap = { version = "1.0", default-features = false }

# intl deps
boa_icu_provider = {workspace = true, features = ["std"], optional = true }
Expand Down
8 changes: 7 additions & 1 deletion core/engine/src/bytecompiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::{
builtins::function::ThisMode,
environments::{BindingLocator, BindingLocatorError, CompileTimeEnvironment},
js_string,
optimizer::control_flow_graph::ControlFlowGraph,
vm::{
BindingOpcode, CodeBlock, CodeBlockFlags, Constant, GeneratorResumeKind, Handler,
InlineCache, Opcode, VaryingOperandKind,
Expand Down Expand Up @@ -1521,12 +1522,17 @@ impl<'ctx> ByteCompiler<'ctx> {
}
self.r#return(false);

// FIXME: remove this, this is used to ensure that `finalize` works correctly.
let graph = ControlFlowGraph::generate(&self.bytecode, &self.handlers);
let bytecode = graph.finalize().into_boxed_slice();
assert_eq!(self.bytecode.as_slice(), bytecode.as_ref());

CodeBlock {
name: self.function_name,
length: self.length,
this_mode: self.this_mode,
params: self.params,
bytecode: self.bytecode.into_boxed_slice(),
bytecode,
constants: self.constants,
bindings: self.bindings.into_boxed_slice(),
handlers: self.handlers,
Expand Down
86 changes: 86 additions & 0 deletions core/engine/src/optimizer/control_flow_graph/basic_block.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use std::hash::Hash;

use bitflags::bitflags;

use crate::vm::{Handler, Instruction};

use super::{BasicBlockKey, Terminator};

bitflags! {
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct BasicBlockFlags: u8 {
const REACHABLE = 0b0000_0001;
}
}

pub(crate) struct BasicBlockHandler {
basic_block: BasicBlockKey,
handler: Handler,
}

/// TODO: doc
#[derive(Default, Clone)]
pub struct BasicBlock {
pub(crate) previous: Vec<BasicBlockKey>,
pub(crate) instructions: Vec<Instruction>,
pub(crate) terminator: Terminator,
pub(crate) handler: Option<(BasicBlockKey, Handler)>,

pub(crate) flags: BasicBlockFlags,
}

impl BasicBlock {
/// Get nth instruction in the [`BasicBlock`].
pub(crate) fn get(&mut self, nth: usize) -> Option<&Instruction> {
self.instructions.get(nth)
}

/// Insert nth instruction in the [`BasicBlock`].
pub(crate) fn insert(&mut self, nth: usize, instruction: Instruction) {
self.instructions.insert(nth, instruction);
}

/// Insert instruction in the last position in the [`BasicBlock`].
pub(crate) fn insert_last(&mut self, instruction: Instruction) {
self.instructions.push(instruction);
}

/// Remove nth instruction in the [`BasicBlock`].
pub(crate) fn remove(&mut self, nth: usize) -> Instruction {
self.instructions.remove(nth)
}

/// Remove last instruction in the [`BasicBlock`].
pub(crate) fn remove_last(&mut self) -> bool {
self.instructions.pop().is_some()
}

pub(crate) fn reachable(&self) -> bool {
self.flags.contains(BasicBlockFlags::REACHABLE)
}

pub(crate) fn next(&self) -> Vec<BasicBlockKey> {
let mut result = Vec::new();
self.next_into(&mut result);
result
}

pub(crate) fn next_into(&self, nexts: &mut Vec<BasicBlockKey>) {
match &self.terminator {
Terminator::None => {}
Terminator::JumpUnconditional { target, .. } => {
nexts.push(*target);
}
Terminator::JumpConditional { no, yes, .. }
| Terminator::TemplateLookup { no, yes, .. } => {
nexts.push(*no);
nexts.push(*yes);
}
Terminator::JumpTable { default, addresses } => {
nexts.push(*default);
nexts.extend_from_slice(addresses);
}
Terminator::Return { end } => nexts.push(*end),
}
}
}
Loading
Loading