Skip to content

Commit

Permalink
[llvm-context,solidity] Generate debug-info location information.
Browse files Browse the repository at this point in the history
When debug-info generation is enabled, construct a DebugInfo instance.

Add a namespace stack to the DebugInfo structure to keep track of the
names of named scopes, such as namespaces, objects and functions,
enclosing a construct.

Generate source level debug information for the functions defined when
YUL is lowered to LLVM-IR. This includes the deploy_code and runtime
functions generated by the compiler.

Generate debug-location information for other constructs that may appear
in a contract.
  • Loading branch information
wpt967 committed Oct 4, 2024
1 parent c54a5b9 commit a16de55
Show file tree
Hide file tree
Showing 14 changed files with 550 additions and 47 deletions.
1 change: 1 addition & 0 deletions crates/llvm-context/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub use self::polkavm::context::argument::Argument as PolkaVMArgument;
pub use self::polkavm::context::attribute::Attribute as PolkaVMAttribute;
pub use self::polkavm::context::build::Build as PolkaVMBuild;
pub use self::polkavm::context::code_type::CodeType as PolkaVMCodeType;
pub use self::polkavm::context::debug_info::DebugInfo;
pub use self::polkavm::context::evmla_data::EVMLAData as PolkaVMContextEVMLAData;
pub use self::polkavm::context::function::block::evmla_data::key::Key as PolkaVMFunctionBlockKey;
pub use self::polkavm::context::function::block::evmla_data::EVMLAData as PolkaVMFunctionBlockEVMLAData;
Expand Down
175 changes: 139 additions & 36 deletions crates/llvm-context/src/polkavm/context/debug_info.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,53 @@
//! The LLVM debug information.

use std::cell::RefCell;

use inkwell::debug_info::AsDIScope;
use num::Zero;
use inkwell::debug_info::DIScope;

/// Debug info scope stack
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScopeStack<'ctx> {
stack: Vec<DIScope<'ctx>>,
}

// Abstract the type of the DIScope stack.
impl<'ctx> ScopeStack<'ctx> {
pub fn from(item: DIScope<'ctx>) -> Self {
Self { stack: vec![item] }
}

/// Return the top of the scope stack, or None if the stack is empty.
pub fn top(&self) -> Option<DIScope<'ctx>> {
self.stack.last().map(|rc| rc.clone())
}

/// Push a scope onto the stack.
pub fn push(&mut self, scope: DIScope<'ctx>) -> () {
self.stack.push(scope)
}

/// Pop the scope at the top of the stack and return it.
/// Return None if the stack is empty.
pub fn pop(&mut self) -> Option<DIScope<'ctx>> {
self.stack.pop()
}

pub fn len(&self) -> usize {
self.stack.len()
}
}

/// The LLVM debug information.
pub struct DebugInfo<'ctx> {
/// The compile unit.
compile_unit: inkwell::debug_info::DICompileUnit<'ctx>,
/// The debug info builder.
builder: inkwell::debug_info::DebugInfoBuilder<'ctx>,
/// The debug info scope stack. Used when lowering to llvm-ir.
scope_stack: RefCell<ScopeStack<'ctx>>,
// Stack of names of enclosing objects, functions and other namespaces.
namespace_stack: RefCell<Vec<String>>,
}

impl<'ctx> DebugInfo<'ctx> {
Expand All @@ -35,63 +74,127 @@ impl<'ctx> DebugInfo<'ctx> {
Self {
compile_unit,
builder,
scope_stack: RefCell::new(ScopeStack::from(compile_unit.as_debug_info_scope())),
namespace_stack: RefCell::new(vec![]),
}
}

/// Creates a function info.
/// Create debug-info for a function.
pub fn create_function(
&self,
scope: inkwell::debug_info::DIScope<'ctx>,
name: &str,
linkage_name: Option<&str>,
return_type: Option<inkwell::debug_info::DIType<'ctx>>,
parameter_types: &[inkwell::debug_info::DIType<'ctx>],
file: inkwell::debug_info::DIFile<'ctx>,
line_num: u32,
is_definition: bool,
is_local: bool,
is_optimized: bool,
flags: Option<inkwell::debug_info::DIFlags>,
) -> anyhow::Result<inkwell::debug_info::DISubprogram<'ctx>> {
let subroutine_type = self.builder.create_subroutine_type(
self.compile_unit.get_file(),
Some(self.create_type(revive_common::BIT_LENGTH_FIELD)?),
&[],
inkwell::debug_info::DIFlags::zero(),
);
let di_flags = flags.unwrap_or(inkwell::debug_info::DIFlagsConstants::ZERO);
let ret_type = return_type.unwrap_or(self.create_word_type(flags)?.as_type());
let subroutine_type =
self.builder
.create_subroutine_type(file, Some(ret_type), parameter_types, di_flags);

let function = self.builder.create_function(
self.compile_unit.get_file().as_debug_info_scope(),
scope,
name,
None,
self.compile_unit.get_file(),
42,
linkage_name,
file,
line_num,
subroutine_type,
true,
false,
1,
inkwell::debug_info::DIFlags::zero(),
false,
);

self.builder.create_lexical_block(
function.as_debug_info_scope(),
self.compile_unit.get_file(),
1,
is_local,
is_definition,
1,
di_flags,
is_optimized,
);

Ok(function)
}

/// Creates a primitive type info.
pub fn create_type(
/// Creates primitive integer type debug-info.
pub fn create_primitive_type(
&self,
bit_length: usize,
) -> anyhow::Result<inkwell::debug_info::DIType<'ctx>> {
flags: Option<inkwell::debug_info::DIFlags>,
) -> anyhow::Result<inkwell::debug_info::DIBasicType<'ctx>> {
let di_flags = flags.unwrap_or(inkwell::debug_info::DIFlagsConstants::ZERO);
let di_encoding: u32 = 0;
let type_name = String::from("U") + bit_length.to_string().as_str();
self.builder
.create_basic_type(
"U256",
bit_length as u64,
0,
inkwell::debug_info::DIFlags::zero(),
)
.map(|basic_type| basic_type.as_type())
.create_basic_type(type_name.as_str(), bit_length as u64, di_encoding, di_flags)
.map_err(|error| anyhow::anyhow!("Debug info error: {}", error))
}

/// Finalizes the builder.
pub fn finalize(&self) {
self.builder.finalize();
/// Returns the debug-info model of word-sized integer types.
pub fn create_word_type(
&self,
flags: Option<inkwell::debug_info::DIFlags>,
) -> anyhow::Result<inkwell::debug_info::DIBasicType<'ctx>> {
self.create_primitive_type(revive_common::BIT_LENGTH_WORD, flags)
}

/// Return the DIBuilder.
pub fn builder(&self) -> &inkwell::debug_info::DebugInfoBuilder<'ctx> {
&self.builder
}

/// Return the compilation unit. {
pub fn compilation_unit(&self) -> &inkwell::debug_info::DICompileUnit<'ctx> {
&self.compile_unit
}

pub fn push_scope(&self, scope: DIScope<'ctx>) -> () {
self.scope_stack.borrow_mut().push(scope)
}

pub fn pop_scope(&self) -> Option<DIScope<'ctx>> {
self.scope_stack.borrow_mut().pop()
}

pub fn num_scopes(&self) -> usize {
self.scope_stack.borrow().len()
}

pub fn top_scope(&self) -> Option<DIScope<'ctx>> {
self.scope_stack.borrow().top()
}

pub fn push_namespace(&self, name: String) -> () {
self.namespace_stack.borrow_mut().push(name);
}

pub fn pop_namespace(&self) -> Option<String> {
self.namespace_stack.borrow_mut().pop()
}

pub fn top_namespace(&self) -> Option<String> {
self.namespace_stack.borrow().last().map(|rc| rc.clone())
}

// Get a string representation of the namespace stack. Optionally append the given name.
pub fn namespace_as_identifier(&self, name: Option<&str>) -> String {
let separator = '.';
let mut ret = String::new();
let mut sep = false;
for s in self.namespace_stack.borrow().iter() {
if sep {
ret.push(separator);
};
sep = true;
ret.push_str(s.as_str())
}
if let Some(n) = name {
if sep {
ret.push(separator);
};
ret.push_str(n);
}
ret
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,8 @@ impl<'ctx> Declaration<'ctx> {
) -> Self {
Self { r#type, value }
}

pub fn function_value(&self) -> inkwell::values::FunctionValue<'ctx> {
self.value
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm::WriteLLVM;

use inkwell::debug_info::AsDIScope;

/// The deploy code function.
/// Is a special function that is only used by the front-end generated code.
#[derive(Debug)]
Expand Down Expand Up @@ -60,6 +62,47 @@ where
context.set_basic_block(context.current_function().borrow().entry_block());
context.set_code_type(CodeType::Deploy);

if let Some(dinfo) = context.debug_info() {
context.builder().unset_current_debug_location();
let di_builder = dinfo.builder();
let line_num: u32 = 0;
let column: u32 = 0;
let func_name: &str = runtime::FUNCTION_DEPLOY_CODE;
let linkage_name = dinfo.namespace_as_identifier(Some(func_name).clone());
let di_file = dinfo.compilation_unit().get_file();
let di_scope = di_file.as_debug_info_scope();
let di_func_scope = dinfo.create_function(
di_scope,
func_name,
Some(linkage_name.as_str()),
None,
&[],
di_file,
line_num,
true,
false,
false,
Some(inkwell::debug_info::DIFlagsConstants::PUBLIC),
)?;
let _ = dinfo.push_scope(di_func_scope.as_debug_info_scope());
let func_value = context
.current_function()
.borrow()
.declaration()
.function_value();
let _ = func_value.set_subprogram(di_func_scope);

let lexical_scope = di_builder
.create_lexical_block(
di_func_scope.as_debug_info_scope(),
dinfo.compilation_unit().get_file(),
line_num,
column,
)
.as_debug_info_scope();
let _ = dinfo.push_scope(lexical_scope);
}

self.inner.into_llvm(context)?;
match context
.basic_block()
Expand All @@ -73,8 +116,30 @@ where
}

context.set_basic_block(context.current_function().borrow().return_block());
if let Some(dinfo) = context.debug_info() {
context.builder().unset_current_debug_location();
let di_builder = dinfo.builder();
let line_num: u32 = 0x0beef;
let di_parent_scope = dinfo
.top_scope()
.expect("expected an existing debug-info scope")
.clone();
let di_loc = di_builder.create_debug_location(
context.llvm(),
line_num,
0,
di_parent_scope,
None,
);
context.builder().set_current_debug_location(di_loc)
}
context.build_return(None);

if let Some(dinfo) = context.debug_info() {
let _ = dinfo.pop_scope();
let _ = dinfo.pop_scope();
}

Ok(())
}
}
Loading

0 comments on commit a16de55

Please sign in to comment.