2021-08-11 14:37:26 +08:00
|
|
|
use crate::{
|
2021-11-20 19:50:25 +08:00
|
|
|
symbol_resolver::{StaticValue, SymbolResolver},
|
2021-09-30 17:07:48 +08:00
|
|
|
toplevel::{TopLevelContext, TopLevelDef},
|
2021-08-11 14:37:26 +08:00
|
|
|
typecheck::{
|
2021-08-19 15:30:15 +08:00
|
|
|
type_inferencer::{CodeLocation, PrimitiveStore},
|
2021-10-17 13:02:18 +08:00
|
|
|
typedef::{CallId, FuncArg, Type, TypeEnum, Unifier},
|
2021-08-11 14:37:26 +08:00
|
|
|
},
|
|
|
|
};
|
2021-08-13 14:48:46 +08:00
|
|
|
use crossbeam::channel::{unbounded, Receiver, Sender};
|
2021-08-11 14:37:26 +08:00
|
|
|
use inkwell::{
|
2022-03-09 22:09:36 +08:00
|
|
|
AddressSpace,
|
2023-09-20 13:34:50 +08:00
|
|
|
IntPredicate,
|
2022-03-09 22:09:36 +08:00
|
|
|
OptimizationLevel,
|
|
|
|
attributes::{Attribute, AttributeLoc},
|
2021-08-11 14:37:26 +08:00
|
|
|
basic_block::BasicBlock,
|
|
|
|
builder::Builder,
|
|
|
|
context::Context,
|
|
|
|
module::Module,
|
2023-09-11 13:14:35 +08:00
|
|
|
passes::PassBuilderOptions,
|
2023-09-11 10:25:44 +08:00
|
|
|
targets::{CodeModel, RelocMode, Target, TargetMachine, TargetTriple},
|
2022-03-09 22:09:36 +08:00
|
|
|
types::{AnyType, BasicType, BasicTypeEnum},
|
2023-09-20 13:34:50 +08:00
|
|
|
values::{BasicValueEnum, FunctionValue, IntValue, PhiValue, PointerValue},
|
2022-04-14 15:40:12 +08:00
|
|
|
debug_info::{
|
|
|
|
DebugInfoBuilder, DICompileUnit, DISubprogram, AsDIScope, DIFlagsConstants, DIScope
|
|
|
|
},
|
2021-08-11 14:37:26 +08:00
|
|
|
};
|
|
|
|
use itertools::Itertools;
|
2022-04-04 23:21:00 +08:00
|
|
|
use nac3parser::ast::{Stmt, StrRef, Location};
|
2021-11-20 19:50:25 +08:00
|
|
|
use parking_lot::{Condvar, Mutex};
|
2022-02-22 14:33:43 +08:00
|
|
|
use std::collections::{HashMap, HashSet};
|
2021-08-13 16:20:14 +08:00
|
|
|
use std::sync::{
|
|
|
|
atomic::{AtomicBool, Ordering},
|
|
|
|
Arc,
|
|
|
|
};
|
2021-08-13 14:48:46 +08:00
|
|
|
use std::thread;
|
2021-08-11 14:37:26 +08:00
|
|
|
|
2024-01-23 17:21:24 +08:00
|
|
|
pub mod classes;
|
2021-10-17 13:02:18 +08:00
|
|
|
pub mod concrete_type;
|
2021-10-31 17:16:21 +08:00
|
|
|
pub mod expr;
|
2021-10-16 22:17:36 +08:00
|
|
|
mod generator;
|
2022-01-08 22:16:55 +08:00
|
|
|
pub mod irrt;
|
2024-02-22 01:47:26 +08:00
|
|
|
pub mod llvm_intrinsics;
|
2022-02-21 18:27:46 +08:00
|
|
|
pub mod stmt;
|
2021-08-11 14:37:26 +08:00
|
|
|
|
2021-08-12 13:55:15 +08:00
|
|
|
#[cfg(test)]
|
|
|
|
mod test;
|
|
|
|
|
2021-10-17 13:02:18 +08:00
|
|
|
use concrete_type::{ConcreteType, ConcreteTypeEnum, ConcreteTypeStore};
|
2021-10-16 22:17:36 +08:00
|
|
|
pub use generator::{CodeGenerator, DefaultCodeGenerator};
|
|
|
|
|
2021-11-20 19:50:25 +08:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct StaticValueStore {
|
|
|
|
pub lookup: HashMap<Vec<(usize, u64)>, usize>,
|
|
|
|
pub store: Vec<HashMap<usize, Arc<dyn StaticValue + Send + Sync>>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub type VarValue<'ctx> = (PointerValue<'ctx>, Option<Arc<dyn StaticValue + Send + Sync>>, i64);
|
|
|
|
|
2023-09-12 10:09:11 +08:00
|
|
|
/// Additional options for LLVM during codegen.
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
|
|
pub struct CodeGenLLVMOptions {
|
|
|
|
/// The optimization level to apply on the generated LLVM IR.
|
|
|
|
pub opt_level: OptimizationLevel,
|
2023-09-11 13:12:46 +08:00
|
|
|
|
|
|
|
/// Options related to the target machine.
|
|
|
|
pub target: CodeGenTargetMachineOptions,
|
2023-09-12 10:09:11 +08:00
|
|
|
}
|
|
|
|
|
2023-09-11 10:25:44 +08:00
|
|
|
/// Additional options for code generation for the target machine.
|
|
|
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
|
|
|
pub struct CodeGenTargetMachineOptions {
|
|
|
|
/// The target machine triple.
|
|
|
|
pub triple: String,
|
|
|
|
/// The target machine CPU.
|
|
|
|
pub cpu: String,
|
|
|
|
/// Additional target machine features.
|
|
|
|
pub features: String,
|
|
|
|
/// Relocation mode for code generation.
|
|
|
|
pub reloc_mode: RelocMode,
|
|
|
|
/// Code model for code generation.
|
|
|
|
pub code_model: CodeModel,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CodeGenTargetMachineOptions {
|
|
|
|
|
2023-12-08 17:43:32 +08:00
|
|
|
/// Creates an instance of [`CodeGenTargetMachineOptions`] using the triple of the host machine.
|
2023-09-11 10:25:44 +08:00
|
|
|
/// Other options are set to defaults.
|
2023-12-08 17:43:32 +08:00
|
|
|
#[must_use]
|
2023-09-11 10:25:44 +08:00
|
|
|
pub fn from_host_triple() -> CodeGenTargetMachineOptions {
|
|
|
|
CodeGenTargetMachineOptions {
|
|
|
|
triple: TargetMachine::get_default_triple().as_str().to_string_lossy().into_owned(),
|
|
|
|
cpu: String::default(),
|
|
|
|
features: String::default(),
|
|
|
|
reloc_mode: RelocMode::Default,
|
|
|
|
code_model: CodeModel::Default,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-08 17:43:32 +08:00
|
|
|
/// Creates an instance of [`CodeGenTargetMachineOptions`] using the properties of the host
|
2023-09-11 10:25:44 +08:00
|
|
|
/// machine. Other options are set to defaults.
|
2023-12-08 17:43:32 +08:00
|
|
|
#[must_use]
|
2023-09-11 10:25:44 +08:00
|
|
|
pub fn from_host() -> CodeGenTargetMachineOptions {
|
|
|
|
CodeGenTargetMachineOptions {
|
|
|
|
cpu: TargetMachine::get_host_cpu_name().to_string(),
|
|
|
|
features: TargetMachine::get_host_cpu_features().to_string(),
|
|
|
|
..CodeGenTargetMachineOptions::from_host_triple()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-08 17:43:32 +08:00
|
|
|
/// Creates a [`TargetMachine`] using the target options specified by this struct.
|
2023-09-11 10:25:44 +08:00
|
|
|
///
|
2023-12-08 17:43:32 +08:00
|
|
|
/// See [`Target::create_target_machine`].
|
|
|
|
#[must_use]
|
2023-09-11 10:25:44 +08:00
|
|
|
pub fn create_target_machine(
|
|
|
|
&self,
|
|
|
|
level: OptimizationLevel,
|
|
|
|
) -> Option<TargetMachine> {
|
|
|
|
let triple = TargetTriple::create(self.triple.as_str());
|
|
|
|
let target = Target::from_triple(&triple)
|
2023-12-06 11:49:02 +08:00
|
|
|
.unwrap_or_else(|_| panic!("could not create target from target triple {}", self.triple));
|
2023-09-11 10:25:44 +08:00
|
|
|
|
|
|
|
target.create_target_machine(
|
|
|
|
&triple,
|
|
|
|
self.cpu.as_str(),
|
|
|
|
self.features.as_str(),
|
|
|
|
level,
|
|
|
|
self.reloc_mode,
|
|
|
|
self.code_model
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-12 13:55:15 +08:00
|
|
|
pub struct CodeGenContext<'ctx, 'a> {
|
2023-10-18 13:40:37 +08:00
|
|
|
/// The LLVM context associated with [this context][CodeGenContext].
|
2021-08-11 14:37:26 +08:00
|
|
|
pub ctx: &'ctx Context,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The [Builder] instance for creating LLVM IR statements.
|
2021-08-11 14:37:26 +08:00
|
|
|
pub builder: Builder<'ctx>,
|
2023-10-06 11:11:38 +08:00
|
|
|
/// The [DebugInfoBuilder], [compilation unit information][DICompileUnit], and
|
|
|
|
/// [scope information][DIScope] of this context.
|
2022-04-14 15:40:12 +08:00
|
|
|
pub debug_info: (DebugInfoBuilder<'ctx>, DICompileUnit<'ctx>, DIScope<'ctx>),
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The module for which [this context][CodeGenContext] is generating into.
|
2021-08-11 14:37:26 +08:00
|
|
|
pub module: Module<'ctx>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The [TopLevelContext] associated with [this context][CodeGenContext].
|
2021-08-12 13:55:15 +08:00
|
|
|
pub top_level: &'a TopLevelContext,
|
2021-08-11 14:37:26 +08:00
|
|
|
pub unifier: Unifier,
|
2021-10-16 18:08:13 +08:00
|
|
|
pub resolver: Arc<dyn SymbolResolver + Send + Sync>,
|
2021-11-20 19:50:25 +08:00
|
|
|
pub static_value_store: Arc<Mutex<StaticValueStore>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// A [HashMap] containing the mapping between the names of variables currently in-scope and
|
|
|
|
/// its value information.
|
2021-11-20 19:50:25 +08:00
|
|
|
pub var_assignment: HashMap<StrRef, VarValue<'ctx>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
///
|
2021-08-11 14:37:26 +08:00
|
|
|
pub type_cache: HashMap<Type, BasicTypeEnum<'ctx>>,
|
|
|
|
pub primitives: PrimitiveStore,
|
2021-09-22 16:04:25 +08:00
|
|
|
pub calls: Arc<HashMap<CodeLocation, CallId>>,
|
2021-08-25 15:29:58 +08:00
|
|
|
pub registry: &'a WorkerRegistry,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// Cache for constant strings.
|
2022-02-12 21:13:16 +08:00
|
|
|
pub const_strings: HashMap<String, BasicValueEnum<'ctx>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// [BasicBlock] containing all `alloca` statements for the current function.
|
2021-08-11 14:37:26 +08:00
|
|
|
pub init_bb: BasicBlock<'ctx>,
|
2023-10-06 11:47:28 +08:00
|
|
|
pub exception_val: Option<PointerValue<'ctx>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
2023-09-05 12:10:52 +08:00
|
|
|
/// The header and exit basic blocks of a loop in this context. See
|
|
|
|
/// https://llvm.org/docs/LoopTerminology.html for explanation of these terminology.
|
2022-02-12 21:13:16 +08:00
|
|
|
pub loop_target: Option<(BasicBlock<'ctx>, BasicBlock<'ctx>)>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The target [BasicBlock] to jump to when performing stack unwind.
|
2022-02-12 21:13:16 +08:00
|
|
|
pub unwind_target: Option<BasicBlock<'ctx>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The target [BasicBlock] to jump to before returning from the function.
|
|
|
|
///
|
|
|
|
/// If this field is [None] when generating a return from a function, `ret` with no argument can
|
|
|
|
/// be emitted.
|
2022-02-12 21:13:16 +08:00
|
|
|
pub return_target: Option<BasicBlock<'ctx>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The [PointerValue] containing the return value of the function.
|
2022-02-12 21:13:16 +08:00
|
|
|
pub return_buffer: Option<PointerValue<'ctx>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
2022-02-12 21:13:16 +08:00
|
|
|
// outer catch clauses
|
|
|
|
pub outer_catch_clauses:
|
|
|
|
Option<(Vec<Option<BasicValueEnum<'ctx>>>, BasicBlock<'ctx>, PhiValue<'ctx>)>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// Whether `sret` is needed for the first parameter of the function.
|
|
|
|
///
|
|
|
|
/// See [need_sret].
|
2022-03-09 22:09:36 +08:00
|
|
|
pub need_sret: bool,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The current source location.
|
2022-04-04 23:21:00 +08:00
|
|
|
pub current_loc: Location,
|
2022-02-12 21:13:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// Whether the [current basic block][Builder::get_insert_block] referenced by `builder`
|
|
|
|
/// contains a [terminator statement][BasicBlock::get_terminator].
|
2022-02-12 21:13:16 +08:00
|
|
|
pub fn is_terminated(&self) -> bool {
|
2023-12-08 17:43:32 +08:00
|
|
|
self.builder.get_insert_block().and_then(BasicBlock::get_terminator).is_some()
|
2022-02-12 21:13:16 +08:00
|
|
|
}
|
2021-08-11 14:37:26 +08:00
|
|
|
}
|
|
|
|
|
2021-08-13 14:48:46 +08:00
|
|
|
type Fp = Box<dyn Fn(&Module) + Send + Sync>;
|
|
|
|
|
|
|
|
pub struct WithCall {
|
|
|
|
fp: Fp,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WithCall {
|
2023-12-08 17:43:32 +08:00
|
|
|
#[must_use]
|
2021-08-13 14:48:46 +08:00
|
|
|
pub fn new(fp: Fp) -> WithCall {
|
|
|
|
WithCall { fp }
|
|
|
|
}
|
|
|
|
|
2023-12-06 11:49:02 +08:00
|
|
|
pub fn run(&self, m: &Module) {
|
2023-12-08 17:43:32 +08:00
|
|
|
(self.fp)(m);
|
2021-08-13 14:48:46 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct WorkerRegistry {
|
|
|
|
sender: Arc<Sender<Option<CodeGenTask>>>,
|
|
|
|
receiver: Arc<Receiver<Option<CodeGenTask>>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// Whether any thread in this registry has panicked.
|
2021-08-13 16:20:14 +08:00
|
|
|
panicked: AtomicBool,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The total number of tasks queued or completed in the registry.
|
2021-08-13 14:48:46 +08:00
|
|
|
task_count: Mutex<usize>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// The number of threads available for this registry.
|
2021-08-13 14:48:46 +08:00
|
|
|
thread_count: usize,
|
|
|
|
wait_condvar: Condvar,
|
2021-11-20 19:50:25 +08:00
|
|
|
top_level_ctx: Arc<TopLevelContext>,
|
|
|
|
static_value_store: Arc<Mutex<StaticValueStore>>,
|
2023-10-18 13:40:37 +08:00
|
|
|
|
2023-09-06 17:50:17 +08:00
|
|
|
/// LLVM-related options for code generation.
|
2023-11-27 13:25:53 +08:00
|
|
|
pub llvm_options: CodeGenLLVMOptions,
|
2021-08-13 14:48:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl WorkerRegistry {
|
2023-10-18 13:40:37 +08:00
|
|
|
|
|
|
|
/// Creates workers for this registry.
|
2023-12-08 17:43:32 +08:00
|
|
|
#[must_use]
|
2021-10-16 22:17:36 +08:00
|
|
|
pub fn create_workers<G: CodeGenerator + Send + 'static>(
|
|
|
|
generators: Vec<Box<G>>,
|
2021-08-13 14:48:46 +08:00
|
|
|
top_level_ctx: Arc<TopLevelContext>,
|
2023-09-06 17:50:17 +08:00
|
|
|
llvm_options: &CodeGenLLVMOptions,
|
2023-12-08 17:43:32 +08:00
|
|
|
f: &Arc<WithCall>,
|
2021-08-13 16:20:14 +08:00
|
|
|
) -> (Arc<WorkerRegistry>, Vec<thread::JoinHandle<()>>) {
|
2021-08-13 14:48:46 +08:00
|
|
|
let (sender, receiver) = unbounded();
|
|
|
|
let task_count = Mutex::new(0);
|
|
|
|
let wait_condvar = Condvar::new();
|
|
|
|
|
2021-11-20 19:50:25 +08:00
|
|
|
// init: 0 to be empty
|
2023-12-08 17:43:32 +08:00
|
|
|
let mut static_value_store = StaticValueStore::default();
|
|
|
|
static_value_store.lookup.insert(Vec::default(), 0);
|
|
|
|
static_value_store.store.push(HashMap::default());
|
2021-11-20 19:50:25 +08:00
|
|
|
|
2021-08-13 14:48:46 +08:00
|
|
|
let registry = Arc::new(WorkerRegistry {
|
|
|
|
sender: Arc::new(sender),
|
|
|
|
receiver: Arc::new(receiver),
|
2021-10-16 22:17:36 +08:00
|
|
|
thread_count: generators.len(),
|
2021-08-13 16:20:14 +08:00
|
|
|
panicked: AtomicBool::new(false),
|
2021-11-20 19:50:25 +08:00
|
|
|
static_value_store: Arc::new(Mutex::new(static_value_store)),
|
2021-08-13 14:48:46 +08:00
|
|
|
task_count,
|
|
|
|
wait_condvar,
|
2021-11-20 19:50:25 +08:00
|
|
|
top_level_ctx,
|
2023-09-06 17:50:17 +08:00
|
|
|
llvm_options: llvm_options.clone(),
|
2021-08-13 14:48:46 +08:00
|
|
|
});
|
|
|
|
|
2021-08-13 16:20:14 +08:00
|
|
|
let mut handles = Vec::new();
|
2023-12-08 17:43:32 +08:00
|
|
|
for mut generator in generators {
|
2021-08-13 14:48:46 +08:00
|
|
|
let registry = registry.clone();
|
2021-08-13 16:20:14 +08:00
|
|
|
let registry2 = registry.clone();
|
2021-08-13 14:48:46 +08:00
|
|
|
let f = f.clone();
|
2021-08-13 16:20:14 +08:00
|
|
|
let handle = thread::spawn(move || {
|
2023-12-08 17:43:32 +08:00
|
|
|
registry.worker_thread(generator.as_mut(), &f);
|
2021-08-13 14:48:46 +08:00
|
|
|
});
|
2021-08-13 16:20:14 +08:00
|
|
|
let handle = thread::spawn(move || {
|
|
|
|
if let Err(e) = handle.join() {
|
|
|
|
if let Some(e) = e.downcast_ref::<&'static str>() {
|
2023-12-08 17:43:32 +08:00
|
|
|
eprintln!("Got an error: {e}");
|
2021-08-13 16:20:14 +08:00
|
|
|
} else {
|
2023-12-08 17:43:32 +08:00
|
|
|
eprintln!("Got an unknown error: {e:?}");
|
2021-08-13 16:20:14 +08:00
|
|
|
}
|
|
|
|
registry2.panicked.store(true, Ordering::SeqCst);
|
|
|
|
registry2.wait_condvar.notify_all();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
handles.push(handle);
|
2021-08-13 14:48:46 +08:00
|
|
|
}
|
2021-08-13 16:20:14 +08:00
|
|
|
(registry, handles)
|
2021-08-13 14:48:46 +08:00
|
|
|
}
|
|
|
|
|
2021-08-13 16:20:14 +08:00
|
|
|
pub fn wait_tasks_complete(&self, handles: Vec<thread::JoinHandle<()>>) {
|
2021-08-13 14:48:46 +08:00
|
|
|
{
|
|
|
|
let mut count = self.task_count.lock();
|
|
|
|
while *count != 0 {
|
2021-08-13 16:20:14 +08:00
|
|
|
if self.panicked.load(Ordering::SeqCst) {
|
|
|
|
break;
|
|
|
|
}
|
2021-08-13 14:48:46 +08:00
|
|
|
self.wait_condvar.wait(&mut count);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _ in 0..self.thread_count {
|
|
|
|
self.sender.send(None).unwrap();
|
|
|
|
}
|
|
|
|
{
|
|
|
|
let mut count = self.task_count.lock();
|
|
|
|
while *count != self.thread_count {
|
2021-08-13 16:20:14 +08:00
|
|
|
if self.panicked.load(Ordering::SeqCst) {
|
|
|
|
break;
|
|
|
|
}
|
2021-08-13 14:48:46 +08:00
|
|
|
self.wait_condvar.wait(&mut count);
|
|
|
|
}
|
|
|
|
}
|
2021-08-13 16:20:14 +08:00
|
|
|
for handle in handles {
|
|
|
|
handle.join().unwrap();
|
|
|
|
}
|
2023-12-08 17:43:32 +08:00
|
|
|
assert!(!self.panicked.load(Ordering::SeqCst), "tasks panicked");
|
2021-08-13 14:48:46 +08:00
|
|
|
}
|
|
|
|
|
2023-12-08 17:43:32 +08:00
|
|
|
/// Adds a task to this [`WorkerRegistry`].
|
2021-08-13 14:48:46 +08:00
|
|
|
pub fn add_task(&self, task: CodeGenTask) {
|
|
|
|
*self.task_count.lock() += 1;
|
|
|
|
self.sender.send(Some(task)).unwrap();
|
|
|
|
}
|
|
|
|
|
2023-10-18 13:40:37 +08:00
|
|
|
/// Function executed by worker thread for generating IR for each function.
|
2023-12-08 17:43:32 +08:00
|
|
|
fn worker_thread<G: CodeGenerator>(&self, generator: &mut G, f: &Arc<WithCall>) {
|
2021-08-13 14:48:46 +08:00
|
|
|
let context = Context::create();
|
|
|
|
let mut builder = context.create_builder();
|
2022-05-31 23:03:05 +08:00
|
|
|
let mut module = context.create_module(generator.get_name());
|
2021-08-13 14:48:46 +08:00
|
|
|
|
2022-04-14 15:40:12 +08:00
|
|
|
module.add_basic_value_flag(
|
|
|
|
"Debug Info Version",
|
|
|
|
inkwell::module::FlagBehavior::Warning,
|
|
|
|
context.i32_type().const_int(3, false),
|
|
|
|
);
|
|
|
|
module.add_basic_value_flag(
|
|
|
|
"Dwarf Version",
|
|
|
|
inkwell::module::FlagBehavior::Warning,
|
|
|
|
context.i32_type().const_int(4, false),
|
|
|
|
);
|
|
|
|
|
2022-02-22 14:33:43 +08:00
|
|
|
let mut errors = HashSet::new();
|
2021-08-13 14:48:46 +08:00
|
|
|
while let Some(task) = self.receiver.recv().unwrap() {
|
2022-05-31 23:03:05 +08:00
|
|
|
match gen_func(&context, generator, self, builder, module, task) {
|
2022-02-21 17:52:34 +08:00
|
|
|
Ok(result) => {
|
|
|
|
builder = result.0;
|
2022-05-31 23:03:05 +08:00
|
|
|
module = result.1;
|
2022-02-21 17:52:34 +08:00
|
|
|
}
|
|
|
|
Err((old_builder, e)) => {
|
|
|
|
builder = old_builder;
|
2022-02-22 14:33:43 +08:00
|
|
|
errors.insert(e);
|
2022-05-31 23:03:05 +08:00
|
|
|
// create a new empty module just to continue codegen and collect errors
|
|
|
|
module = context.create_module(&format!("{}_recover", generator.get_name()));
|
2022-02-21 17:52:34 +08:00
|
|
|
}
|
|
|
|
}
|
2021-08-13 14:48:46 +08:00
|
|
|
*self.task_count.lock() -= 1;
|
|
|
|
self.wait_condvar.notify_all();
|
|
|
|
}
|
2023-12-08 17:43:32 +08:00
|
|
|
assert!(errors.is_empty(), "Codegen error: {}", errors.into_iter().sorted().join("\n----------\n"));
|
2021-08-13 14:48:46 +08:00
|
|
|
|
2021-10-17 12:56:11 +08:00
|
|
|
let result = module.verify();
|
|
|
|
if let Err(err) = result {
|
|
|
|
println!("{}", module.print_to_string().to_str().unwrap());
|
2023-09-19 12:38:35 +08:00
|
|
|
panic!("{}", err.to_string())
|
2021-10-17 12:56:11 +08:00
|
|
|
}
|
2023-09-06 17:50:17 +08:00
|
|
|
|
2023-09-11 13:14:35 +08:00
|
|
|
let pass_options = PassBuilderOptions::create();
|
2023-12-06 11:49:02 +08:00
|
|
|
let target_machine = self
|
|
|
|
.llvm_options
|
|
|
|
.target
|
|
|
|
.create_target_machine(self.llvm_options.opt_level)
|
|
|
|
.unwrap_or_else(|| panic!("could not create target machine from properties {:?}", self.llvm_options.target));
|
2023-09-11 13:14:35 +08:00
|
|
|
let passes = format!("default<O{}>", self.llvm_options.opt_level as u32);
|
|
|
|
let result = module.run_passes(passes.as_str(), &target_machine, pass_options);
|
|
|
|
if let Err(err) = result {
|
|
|
|
panic!("Failed to run optimization for module `{}`: {}",
|
|
|
|
module.get_name().to_str().unwrap(),
|
|
|
|
err.to_string());
|
|
|
|
}
|
|
|
|
|
2021-08-13 14:48:46 +08:00
|
|
|
f.run(&module);
|
2021-09-16 21:36:42 +08:00
|
|
|
let mut lock = self.task_count.lock();
|
2021-08-13 14:48:46 +08:00
|
|
|
*lock += 1;
|
|
|
|
self.wait_condvar.notify_all();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-11 14:37:26 +08:00
|
|
|
pub struct CodeGenTask {
|
2021-10-17 13:02:18 +08:00
|
|
|
pub subst: Vec<(Type, ConcreteType)>,
|
|
|
|
pub store: ConcreteTypeStore,
|
2021-08-11 14:37:26 +08:00
|
|
|
pub symbol_name: String,
|
2021-10-17 13:02:18 +08:00
|
|
|
pub signature: ConcreteType,
|
2021-09-22 16:04:25 +08:00
|
|
|
pub body: Arc<Vec<Stmt<Option<Type>>>>,
|
|
|
|
pub calls: Arc<HashMap<CodeLocation, CallId>>,
|
2021-10-17 13:02:18 +08:00
|
|
|
pub unifier_index: usize,
|
2021-10-16 18:08:13 +08:00
|
|
|
pub resolver: Arc<dyn SymbolResolver + Send + Sync>,
|
2021-11-20 19:50:25 +08:00
|
|
|
pub id: usize,
|
2021-08-11 14:37:26 +08:00
|
|
|
}
|
|
|
|
|
2023-09-20 13:34:50 +08:00
|
|
|
/// Retrieves the [LLVM type][BasicTypeEnum] corresponding to the [Type].
|
|
|
|
///
|
2023-09-20 16:59:47 +08:00
|
|
|
/// This function is used to obtain the in-memory representation of `ty`, e.g. a `bool` variable
|
2023-09-20 13:34:50 +08:00
|
|
|
/// would be represented by an `i8`.
|
2024-02-20 18:07:55 +08:00
|
|
|
#[allow(clippy::too_many_arguments)]
|
2021-08-11 14:37:26 +08:00
|
|
|
fn get_llvm_type<'ctx>(
|
|
|
|
ctx: &'ctx Context,
|
2022-05-31 23:03:05 +08:00
|
|
|
module: &Module<'ctx>,
|
2021-12-27 22:55:51 +08:00
|
|
|
generator: &mut dyn CodeGenerator,
|
2021-08-11 14:37:26 +08:00
|
|
|
unifier: &mut Unifier,
|
|
|
|
top_level: &TopLevelContext,
|
|
|
|
type_cache: &mut HashMap<Type, BasicTypeEnum<'ctx>>,
|
2022-03-26 15:09:15 +08:00
|
|
|
primitives: &PrimitiveStore,
|
2021-08-11 14:37:26 +08:00
|
|
|
ty: Type,
|
|
|
|
) -> BasicTypeEnum<'ctx> {
|
|
|
|
use TypeEnum::*;
|
|
|
|
// we assume the type cache should already contain primitive types,
|
|
|
|
// and they should be passed by value instead of passing as pointer.
|
2023-12-08 17:43:32 +08:00
|
|
|
type_cache.get(&unifier.get_representative(ty)).copied().unwrap_or_else(|| {
|
2022-02-12 21:13:16 +08:00
|
|
|
let ty_enum = unifier.get_ty(ty);
|
|
|
|
let result = match &*ty_enum {
|
2021-08-12 16:36:23 +08:00
|
|
|
TObj { obj_id, fields, .. } => {
|
2022-03-26 15:09:15 +08:00
|
|
|
// check to avoid treating primitives other than Option as classes
|
|
|
|
if obj_id.0 <= 10 {
|
|
|
|
match (unifier.get_ty(ty).as_ref(), unifier.get_ty(primitives.option).as_ref())
|
|
|
|
{
|
|
|
|
(
|
2023-10-26 13:52:40 +08:00
|
|
|
TObj { obj_id, params, .. },
|
|
|
|
TObj { obj_id: opt_id, .. },
|
2022-03-26 15:09:15 +08:00
|
|
|
) if *obj_id == *opt_id => {
|
|
|
|
return get_llvm_type(
|
|
|
|
ctx,
|
2022-05-31 23:03:05 +08:00
|
|
|
module,
|
2022-03-26 15:09:15 +08:00
|
|
|
generator,
|
|
|
|
unifier,
|
|
|
|
top_level,
|
|
|
|
type_cache,
|
|
|
|
primitives,
|
|
|
|
*params.iter().next().unwrap().1,
|
|
|
|
)
|
2023-01-12 19:31:03 +08:00
|
|
|
.ptr_type(AddressSpace::default())
|
2022-03-26 15:09:15 +08:00
|
|
|
.into();
|
|
|
|
}
|
|
|
|
_ => unreachable!("must be option type"),
|
|
|
|
}
|
2022-02-12 21:13:16 +08:00
|
|
|
}
|
2021-08-12 16:36:23 +08:00
|
|
|
// a struct with fields in the order of declaration
|
2021-08-23 10:34:11 +08:00
|
|
|
let top_level_defs = top_level.definitions.read();
|
|
|
|
let definition = top_level_defs.get(obj_id.0).unwrap();
|
2023-12-12 13:38:27 +08:00
|
|
|
let TopLevelDef::Class { fields: fields_list, .. } = &*definition.read() else {
|
2021-08-12 16:36:23 +08:00
|
|
|
unreachable!()
|
|
|
|
};
|
2023-12-12 13:38:27 +08:00
|
|
|
|
|
|
|
let name = unifier.stringify(ty);
|
|
|
|
let ty = if let Some(t) = module.get_struct_type(&name) {
|
|
|
|
t.ptr_type(AddressSpace::default()).into()
|
|
|
|
} else {
|
|
|
|
let struct_type = ctx.opaque_struct_type(&name);
|
|
|
|
type_cache.insert(
|
|
|
|
unifier.get_representative(ty),
|
|
|
|
struct_type.ptr_type(AddressSpace::default()).into()
|
|
|
|
);
|
|
|
|
let fields = fields_list
|
|
|
|
.iter()
|
|
|
|
.map(|f| {
|
|
|
|
get_llvm_type(
|
|
|
|
ctx,
|
|
|
|
module,
|
|
|
|
generator,
|
|
|
|
unifier,
|
|
|
|
top_level,
|
|
|
|
type_cache,
|
|
|
|
primitives,
|
|
|
|
fields[&f.0].0,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.collect_vec();
|
|
|
|
struct_type.set_body(&fields, false);
|
|
|
|
struct_type.ptr_type(AddressSpace::default()).into()
|
|
|
|
};
|
|
|
|
return ty
|
2021-08-12 16:36:23 +08:00
|
|
|
}
|
|
|
|
TTuple { ty } => {
|
|
|
|
// a struct with fields in the order present in the tuple
|
|
|
|
let fields = ty
|
2021-08-11 14:37:26 +08:00
|
|
|
.iter()
|
2022-05-31 23:03:05 +08:00
|
|
|
.map(|ty| {
|
|
|
|
get_llvm_type(
|
|
|
|
ctx, module, generator, unifier, top_level, type_cache, primitives, *ty,
|
|
|
|
)
|
|
|
|
})
|
2021-08-11 14:37:26 +08:00
|
|
|
.collect_vec();
|
2022-01-20 04:14:22 +08:00
|
|
|
ctx.struct_type(&fields, false).into()
|
2021-08-12 16:36:23 +08:00
|
|
|
}
|
|
|
|
TList { ty } => {
|
|
|
|
// a struct with an integer and a pointer to an array
|
2022-05-31 23:03:05 +08:00
|
|
|
let element_type = get_llvm_type(
|
|
|
|
ctx, module, generator, unifier, top_level, type_cache, primitives, *ty,
|
|
|
|
);
|
2022-02-21 18:27:46 +08:00
|
|
|
let fields = [
|
2023-01-12 19:31:03 +08:00
|
|
|
element_type.ptr_type(AddressSpace::default()).into(),
|
2022-02-21 18:27:46 +08:00
|
|
|
generator.get_size_type(ctx).into(),
|
|
|
|
];
|
2023-01-12 19:31:03 +08:00
|
|
|
ctx.struct_type(&fields, false).ptr_type(AddressSpace::default()).into()
|
2021-08-12 16:36:23 +08:00
|
|
|
}
|
2023-11-06 18:03:52 +08:00
|
|
|
TNDArray { ty, .. } => {
|
|
|
|
let llvm_usize = generator.get_size_type(ctx);
|
|
|
|
let element_type = get_llvm_type(
|
|
|
|
ctx, module, generator, unifier, top_level, type_cache, primitives, *ty,
|
|
|
|
);
|
|
|
|
|
|
|
|
// struct NDArray { num_dims: size_t, dims: size_t*, data: T* }
|
|
|
|
//
|
|
|
|
// * num_dims: Number of dimensions in the array
|
|
|
|
// * dims: Pointer to an array containing the size of each dimension
|
|
|
|
// * data: Pointer to an array containing the array data
|
|
|
|
let fields = [
|
|
|
|
llvm_usize.into(),
|
|
|
|
llvm_usize.ptr_type(AddressSpace::default()).into(),
|
|
|
|
element_type.ptr_type(AddressSpace::default()).into(),
|
|
|
|
];
|
|
|
|
ctx.struct_type(&fields, false).ptr_type(AddressSpace::default()).into()
|
|
|
|
}
|
2021-08-12 16:36:23 +08:00
|
|
|
TVirtual { .. } => unimplemented!(),
|
2022-02-12 21:13:16 +08:00
|
|
|
_ => unreachable!("{}", ty_enum.get_type_name()),
|
|
|
|
};
|
|
|
|
type_cache.insert(unifier.get_representative(ty), result);
|
|
|
|
result
|
2021-08-11 14:37:26 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-12-08 17:43:32 +08:00
|
|
|
/// Retrieves the [LLVM type][`BasicTypeEnum`] corresponding to the [`Type`].
|
2023-09-20 13:34:50 +08:00
|
|
|
///
|
2023-09-20 16:59:47 +08:00
|
|
|
/// This function is used mainly to obtain the ABI representation of `ty`, e.g. a `bool` is
|
2023-09-20 13:34:50 +08:00
|
|
|
/// would be represented by an `i1`.
|
|
|
|
///
|
2023-12-08 17:43:32 +08:00
|
|
|
/// The difference between the in-memory representation (as returned by [`get_llvm_type`]) and the
|
2023-09-20 13:34:50 +08:00
|
|
|
/// ABI representation is that the in-memory representation must be at least byte-sized and must
|
|
|
|
/// be byte-aligned for the variable to be addressable in memory, whereas there is no such
|
|
|
|
/// restriction for ABI representations.
|
2024-02-20 18:07:55 +08:00
|
|
|
#[allow(clippy::too_many_arguments)]
|
2023-09-20 13:34:50 +08:00
|
|
|
fn get_llvm_abi_type<'ctx>(
|
|
|
|
ctx: &'ctx Context,
|
|
|
|
module: &Module<'ctx>,
|
|
|
|
generator: &mut dyn CodeGenerator,
|
|
|
|
unifier: &mut Unifier,
|
|
|
|
top_level: &TopLevelContext,
|
|
|
|
type_cache: &mut HashMap<Type, BasicTypeEnum<'ctx>>,
|
|
|
|
primitives: &PrimitiveStore,
|
|
|
|
ty: Type,
|
|
|
|
) -> BasicTypeEnum<'ctx> {
|
|
|
|
// If the type is used in the definition of a function, return `i1` instead of `i8` for ABI
|
|
|
|
// consistency.
|
|
|
|
return if unifier.unioned(ty, primitives.bool) {
|
|
|
|
ctx.bool_type().into()
|
|
|
|
} else {
|
|
|
|
get_llvm_type(ctx, module, generator, unifier, top_level, type_cache, primitives, ty)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-18 13:40:37 +08:00
|
|
|
/// Whether `sret` is needed for a return value with type `ty`.
|
|
|
|
///
|
|
|
|
/// When returning a large data structure (e.g. structures that do not fit in 1-2 native words of
|
|
|
|
/// the target processor) by value, a synthetic parameter with a pointer type will be passed in the
|
|
|
|
/// slot of the first parameter to act as the location of which the return value is passed into.
|
|
|
|
///
|
2023-12-08 17:43:32 +08:00
|
|
|
/// See <https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes> for more
|
2023-10-18 13:40:37 +08:00
|
|
|
/// information.
|
2023-12-06 11:49:02 +08:00
|
|
|
fn need_sret(ty: BasicTypeEnum) -> bool {
|
|
|
|
fn need_sret_impl(ty: BasicTypeEnum, maybe_large: bool) -> bool {
|
2022-03-09 22:09:36 +08:00
|
|
|
match ty {
|
|
|
|
BasicTypeEnum::IntType(_) | BasicTypeEnum::PointerType(_) => false,
|
|
|
|
BasicTypeEnum::FloatType(_) if maybe_large => false,
|
|
|
|
BasicTypeEnum::StructType(ty) if maybe_large && ty.count_fields() <= 2 =>
|
2023-12-06 11:49:02 +08:00
|
|
|
ty.get_field_types().iter().any(|ty| need_sret_impl(*ty, false)),
|
2022-03-09 22:09:36 +08:00
|
|
|
_ => true,
|
|
|
|
}
|
|
|
|
}
|
2023-12-06 11:49:02 +08:00
|
|
|
need_sret_impl(ty, true)
|
2022-03-09 22:09:36 +08:00
|
|
|
}
|
|
|
|
|
2023-09-20 16:59:47 +08:00
|
|
|
/// Implementation for generating LLVM IR for a function.
|
2022-03-25 22:42:01 +08:00
|
|
|
pub fn gen_func_impl<'ctx, G: CodeGenerator, F: FnOnce(&mut G, &mut CodeGenContext) -> Result<(), String>> (
|
2021-08-12 16:36:23 +08:00
|
|
|
context: &'ctx Context,
|
2021-10-16 22:17:36 +08:00
|
|
|
generator: &mut G,
|
2021-08-25 15:29:58 +08:00
|
|
|
registry: &WorkerRegistry,
|
2021-08-12 16:36:23 +08:00
|
|
|
builder: Builder<'ctx>,
|
|
|
|
module: Module<'ctx>,
|
|
|
|
task: CodeGenTask,
|
2022-03-25 22:42:01 +08:00
|
|
|
codegen_function: F
|
2022-02-21 17:52:34 +08:00
|
|
|
) -> Result<(Builder<'ctx>, Module<'ctx>, FunctionValue<'ctx>), (Builder<'ctx>, String)> {
|
2021-11-20 19:50:25 +08:00
|
|
|
let top_level_ctx = registry.top_level_ctx.clone();
|
|
|
|
let static_value_store = registry.static_value_store.clone();
|
2021-08-11 14:37:26 +08:00
|
|
|
let (mut unifier, primitives) = {
|
2021-10-17 13:02:18 +08:00
|
|
|
let (unifier, primitives) = &top_level_ctx.unifiers.read()[task.unifier_index];
|
|
|
|
(Unifier::from_shared_unifier(unifier), *primitives)
|
2021-08-11 14:37:26 +08:00
|
|
|
};
|
2023-12-13 18:23:32 +08:00
|
|
|
unifier.put_primitive_store(&primitives);
|
2022-03-23 00:22:28 +08:00
|
|
|
unifier.top_level = Some(top_level_ctx.clone());
|
2021-08-11 14:37:26 +08:00
|
|
|
|
2021-10-17 13:02:18 +08:00
|
|
|
let mut cache = HashMap::new();
|
2023-12-08 17:43:32 +08:00
|
|
|
for (a, b) in &task.subst {
|
2021-08-11 14:37:26 +08:00
|
|
|
// this should be unification between variables and concrete types
|
|
|
|
// and should not cause any problem...
|
2021-10-17 13:02:18 +08:00
|
|
|
let b = task.store.to_unifier_type(&mut unifier, &primitives, *b, &mut cache);
|
2022-02-21 18:27:46 +08:00
|
|
|
unifier
|
|
|
|
.unify(*a, b)
|
|
|
|
.or_else(|err| {
|
|
|
|
if matches!(&*unifier.get_ty(*a), TypeEnum::TRigidVar { .. }) {
|
|
|
|
unifier.replace_rigid_var(*a, b);
|
|
|
|
Ok(())
|
|
|
|
} else {
|
|
|
|
Err(err)
|
|
|
|
}
|
|
|
|
})
|
2023-12-08 17:43:32 +08:00
|
|
|
.unwrap();
|
2021-08-11 14:37:26 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// rebuild primitive store with unique representatives
|
|
|
|
let primitives = PrimitiveStore {
|
|
|
|
int32: unifier.get_representative(primitives.int32),
|
|
|
|
int64: unifier.get_representative(primitives.int64),
|
2022-03-05 03:45:09 +08:00
|
|
|
uint32: unifier.get_representative(primitives.uint32),
|
|
|
|
uint64: unifier.get_representative(primitives.uint64),
|
2021-08-11 14:37:26 +08:00
|
|
|
float: unifier.get_representative(primitives.float),
|
|
|
|
bool: unifier.get_representative(primitives.bool),
|
|
|
|
none: unifier.get_representative(primitives.none),
|
2021-10-23 23:53:36 +08:00
|
|
|
range: unifier.get_representative(primitives.range),
|
2021-11-02 23:22:37 +08:00
|
|
|
str: unifier.get_representative(primitives.str),
|
2022-02-12 21:09:23 +08:00
|
|
|
exception: unifier.get_representative(primitives.exception),
|
2022-03-26 15:09:15 +08:00
|
|
|
option: unifier.get_representative(primitives.option),
|
2023-12-15 14:02:30 +08:00
|
|
|
..primitives
|
2021-08-11 14:37:26 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
let mut type_cache: HashMap<_, _> = [
|
2022-02-12 21:09:23 +08:00
|
|
|
(primitives.int32, context.i32_type().into()),
|
|
|
|
(primitives.int64, context.i64_type().into()),
|
2022-03-05 03:45:09 +08:00
|
|
|
(primitives.uint32, context.i32_type().into()),
|
|
|
|
(primitives.uint64, context.i64_type().into()),
|
2022-02-12 21:09:23 +08:00
|
|
|
(primitives.float, context.f64_type().into()),
|
2023-09-20 13:34:50 +08:00
|
|
|
(primitives.bool, context.i8_type().into()),
|
2022-02-12 21:09:23 +08:00
|
|
|
(primitives.str, {
|
2022-05-31 23:03:05 +08:00
|
|
|
let name = "str";
|
|
|
|
match module.get_struct_type(name) {
|
|
|
|
None => {
|
|
|
|
let str_type = context.opaque_struct_type("str");
|
|
|
|
let fields = [
|
2023-01-12 19:31:03 +08:00
|
|
|
context.i8_type().ptr_type(AddressSpace::default()).into(),
|
2022-05-31 23:03:05 +08:00
|
|
|
generator.get_size_type(context).into(),
|
|
|
|
];
|
|
|
|
str_type.set_body(&fields, false);
|
|
|
|
str_type.into()
|
|
|
|
}
|
|
|
|
Some(t) => t.as_basic_type_enum()
|
|
|
|
}
|
2022-02-12 21:09:23 +08:00
|
|
|
}),
|
2023-01-12 19:31:03 +08:00
|
|
|
(primitives.range, context.i32_type().array_type(3).ptr_type(AddressSpace::default()).into()),
|
2022-05-31 23:03:05 +08:00
|
|
|
(primitives.exception, {
|
|
|
|
let name = "Exception";
|
2023-12-08 17:43:32 +08:00
|
|
|
if let Some(t) = module.get_struct_type(name) {
|
|
|
|
t.ptr_type(AddressSpace::default()).as_basic_type_enum()
|
|
|
|
} else {
|
|
|
|
let exception = context.opaque_struct_type("Exception");
|
|
|
|
let int32 = context.i32_type().into();
|
|
|
|
let int64 = context.i64_type().into();
|
|
|
|
let str_ty = module.get_struct_type("str").unwrap().as_basic_type_enum();
|
|
|
|
let fields = [int32, str_ty, int32, int32, str_ty, str_ty, int64, int64, int64];
|
|
|
|
exception.set_body(&fields, false);
|
|
|
|
exception.ptr_type(AddressSpace::default()).as_basic_type_enum()
|
2022-05-31 23:03:05 +08:00
|
|
|
}
|
|
|
|
})
|
2021-08-11 14:37:26 +08:00
|
|
|
]
|
|
|
|
.iter()
|
2023-12-08 17:43:32 +08:00
|
|
|
.copied()
|
2021-08-11 14:37:26 +08:00
|
|
|
.collect();
|
2022-03-26 15:09:15 +08:00
|
|
|
// NOTE: special handling of option cannot use this type cache since it contains type var,
|
|
|
|
// handled inside get_llvm_type instead
|
2021-08-11 14:37:26 +08:00
|
|
|
|
2023-12-12 13:38:27 +08:00
|
|
|
let ConcreteTypeEnum::TFunc { args, ret, .. } =
|
|
|
|
task.store.get(task.signature) else {
|
2021-10-17 13:02:18 +08:00
|
|
|
unreachable!()
|
|
|
|
};
|
2023-12-12 13:38:27 +08:00
|
|
|
|
|
|
|
let (args, ret) = (
|
|
|
|
args.iter()
|
|
|
|
.map(|arg| FuncArg {
|
|
|
|
name: arg.name,
|
|
|
|
ty: task.store.to_unifier_type(&mut unifier, &primitives, arg.ty, &mut cache),
|
|
|
|
default_value: arg.default_value.clone(),
|
|
|
|
})
|
|
|
|
.collect_vec(),
|
|
|
|
task.store.to_unifier_type(&mut unifier, &primitives, *ret, &mut cache),
|
|
|
|
);
|
2022-03-09 22:09:36 +08:00
|
|
|
let ret_type = if unifier.unioned(ret, primitives.none) {
|
|
|
|
None
|
|
|
|
} else {
|
2023-09-20 13:34:50 +08:00
|
|
|
Some(get_llvm_abi_type(context, &module, generator, &mut unifier, top_level_ctx.as_ref(), &mut type_cache, &primitives, ret))
|
2022-03-09 22:09:36 +08:00
|
|
|
};
|
|
|
|
|
2023-12-06 11:49:02 +08:00
|
|
|
let has_sret = ret_type.map_or(false, |ty| need_sret(ty));
|
2022-03-09 22:09:36 +08:00
|
|
|
let mut params = args
|
2021-08-11 14:37:26 +08:00
|
|
|
.iter()
|
|
|
|
.map(|arg| {
|
2023-09-20 13:34:50 +08:00
|
|
|
get_llvm_abi_type(
|
2022-02-21 18:27:46 +08:00
|
|
|
context,
|
2022-05-31 23:03:05 +08:00
|
|
|
&module,
|
2022-02-21 18:27:46 +08:00
|
|
|
generator,
|
|
|
|
&mut unifier,
|
|
|
|
top_level_ctx.as_ref(),
|
|
|
|
&mut type_cache,
|
2022-03-26 15:09:15 +08:00
|
|
|
&primitives,
|
2022-02-21 18:27:46 +08:00
|
|
|
arg.ty,
|
|
|
|
)
|
|
|
|
.into()
|
2021-08-11 14:37:26 +08:00
|
|
|
})
|
|
|
|
.collect_vec();
|
|
|
|
|
2022-03-09 22:09:36 +08:00
|
|
|
if has_sret {
|
2023-01-12 19:31:03 +08:00
|
|
|
params.insert(0, ret_type.unwrap().ptr_type(AddressSpace::default()).into());
|
2022-03-09 22:09:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
let fn_type = match ret_type {
|
|
|
|
Some(ret_type) if !has_sret => ret_type.fn_type(¶ms, false),
|
|
|
|
_ => context.void_type().fn_type(¶ms, false)
|
2021-08-11 14:37:26 +08:00
|
|
|
};
|
|
|
|
|
2021-08-27 16:25:59 +08:00
|
|
|
let symbol = &task.symbol_name;
|
2021-09-08 19:45:36 +08:00
|
|
|
let fn_val =
|
|
|
|
module.get_function(symbol).unwrap_or_else(|| module.add_function(symbol, fn_type, None));
|
2021-08-27 16:25:59 +08:00
|
|
|
|
2021-09-25 21:44:00 +08:00
|
|
|
if let Some(personality) = &top_level_ctx.personality_symbol {
|
2021-10-16 18:08:13 +08:00
|
|
|
let personality = module.get_function(personality).unwrap_or_else(|| {
|
2021-09-25 21:44:00 +08:00
|
|
|
let ty = context.i32_type().fn_type(&[], true);
|
2021-10-16 18:08:13 +08:00
|
|
|
module.add_function(personality, ty, None)
|
2021-09-25 21:44:00 +08:00
|
|
|
});
|
|
|
|
fn_val.set_personality_function(personality);
|
|
|
|
}
|
2022-03-09 22:09:36 +08:00
|
|
|
if has_sret {
|
|
|
|
fn_val.add_attribute(AttributeLoc::Param(0),
|
|
|
|
context.create_type_attribute(Attribute::get_named_enum_kind_id("sret"),
|
|
|
|
ret_type.unwrap().as_any_type_enum()));
|
|
|
|
}
|
2021-09-25 21:44:00 +08:00
|
|
|
|
2021-08-11 14:37:26 +08:00
|
|
|
let init_bb = context.append_basic_block(fn_val, "init");
|
|
|
|
builder.position_at_end(init_bb);
|
|
|
|
let body_bb = context.append_basic_block(fn_val, "body");
|
|
|
|
|
|
|
|
let mut var_assignment = HashMap::new();
|
2023-12-08 17:43:32 +08:00
|
|
|
let offset = u32::from(has_sret);
|
2021-10-17 13:02:18 +08:00
|
|
|
for (n, arg) in args.iter().enumerate() {
|
2022-03-09 22:09:36 +08:00
|
|
|
let param = fn_val.get_nth_param((n as u32) + offset).unwrap();
|
2023-09-20 13:34:50 +08:00
|
|
|
let local_type = get_llvm_type(
|
|
|
|
context,
|
|
|
|
&module,
|
|
|
|
generator,
|
|
|
|
&mut unifier,
|
|
|
|
top_level_ctx.as_ref(),
|
|
|
|
&mut type_cache,
|
|
|
|
&primitives,
|
|
|
|
arg.ty,
|
|
|
|
);
|
2024-02-19 19:30:25 +08:00
|
|
|
let alloca = builder
|
|
|
|
.build_alloca(local_type, &format!("{}.addr", &arg.name.to_string()))
|
|
|
|
.unwrap();
|
2023-09-20 13:34:50 +08:00
|
|
|
|
|
|
|
// Remap boolean parameters into i8
|
|
|
|
let param = if local_type.is_int_type() && param.is_int_value() {
|
|
|
|
let expected_ty = local_type.into_int_type();
|
|
|
|
let param_val = param.into_int_value();
|
|
|
|
|
|
|
|
if expected_ty.get_bit_width() == 8 && param_val.get_type().get_bit_width() == 1 {
|
2023-12-06 11:49:02 +08:00
|
|
|
bool_to_i8(&builder, context, param_val)
|
2023-09-20 13:34:50 +08:00
|
|
|
} else {
|
|
|
|
param_val
|
|
|
|
}.into()
|
|
|
|
} else {
|
|
|
|
param
|
|
|
|
};
|
|
|
|
|
2024-02-19 19:30:25 +08:00
|
|
|
builder.build_store(alloca, param).unwrap();
|
2021-11-20 19:50:25 +08:00
|
|
|
var_assignment.insert(arg.name, (alloca, None, 0));
|
|
|
|
}
|
2022-03-09 22:09:36 +08:00
|
|
|
|
|
|
|
let return_buffer = if has_sret {
|
|
|
|
Some(fn_val.get_nth_param(0).unwrap().into_pointer_value())
|
|
|
|
} else {
|
2024-02-19 19:30:25 +08:00
|
|
|
fn_type.get_return_type().map(|v| builder.build_alloca(v, "$ret").unwrap())
|
2022-03-09 22:09:36 +08:00
|
|
|
};
|
|
|
|
|
2021-11-20 19:50:25 +08:00
|
|
|
let static_values = {
|
|
|
|
let store = registry.static_value_store.lock();
|
|
|
|
store.store[task.id].clone()
|
|
|
|
};
|
2023-12-08 17:43:32 +08:00
|
|
|
for (k, v) in static_values {
|
2021-11-20 19:50:25 +08:00
|
|
|
let (_, static_val, _) = var_assignment.get_mut(&args[k].name).unwrap();
|
|
|
|
*static_val = Some(v);
|
2021-08-11 14:37:26 +08:00
|
|
|
}
|
2021-11-20 19:50:25 +08:00
|
|
|
|
2024-02-19 19:30:25 +08:00
|
|
|
builder.build_unconditional_branch(body_bb).unwrap();
|
2021-08-11 14:37:26 +08:00
|
|
|
builder.position_at_end(body_bb);
|
|
|
|
|
2022-04-14 15:40:12 +08:00
|
|
|
let (dibuilder, compile_unit) = module.create_debug_info_builder(
|
|
|
|
/* allow_unresolved */ true,
|
|
|
|
/* language */ inkwell::debug_info::DWARFSourceLanguage::Python,
|
|
|
|
/* filename */
|
|
|
|
&task
|
|
|
|
.body
|
2024-02-20 18:07:55 +08:00
|
|
|
.first()
|
2022-04-14 15:40:12 +08:00
|
|
|
.map_or_else(
|
|
|
|
|| "<nac3_internal>".to_string(),
|
|
|
|
|f| f.location.file.0.to_string(),
|
|
|
|
),
|
|
|
|
/* directory */ "",
|
|
|
|
/* producer */ "NAC3",
|
2023-09-06 17:50:17 +08:00
|
|
|
/* is_optimized */ registry.llvm_options.opt_level != OptimizationLevel::None,
|
2022-04-14 15:40:12 +08:00
|
|
|
/* compiler command line flags */ "",
|
|
|
|
/* runtime_ver */ 0,
|
|
|
|
/* split_name */ "",
|
|
|
|
/* kind */ inkwell::debug_info::DWARFEmissionKind::Full,
|
|
|
|
/* dwo_id */ 0,
|
|
|
|
/* split_debug_inling */ true,
|
|
|
|
/* debug_info_for_profiling */ false,
|
|
|
|
/* sysroot */ "",
|
|
|
|
/* sdk */ "",
|
|
|
|
);
|
|
|
|
let subroutine_type = dibuilder.create_subroutine_type(
|
|
|
|
compile_unit.get_file(),
|
|
|
|
Some(
|
|
|
|
dibuilder
|
|
|
|
.create_basic_type("_", 0_u64, 0x00, inkwell::debug_info::DIFlags::PUBLIC)
|
|
|
|
.unwrap()
|
|
|
|
.as_type(),
|
|
|
|
),
|
|
|
|
&[],
|
|
|
|
inkwell::debug_info::DIFlags::PUBLIC,
|
|
|
|
);
|
|
|
|
let (row, col) =
|
2024-02-20 18:07:55 +08:00
|
|
|
task.body.first().map_or_else(|| (0, 0), |b| (b.location.row, b.location.column));
|
2022-04-14 15:40:12 +08:00
|
|
|
let func_scope: DISubprogram<'_> = dibuilder.create_function(
|
|
|
|
/* scope */ compile_unit.as_debug_info_scope(),
|
|
|
|
/* func name */ symbol,
|
|
|
|
/* linkage_name */ None,
|
|
|
|
/* file */ compile_unit.get_file(),
|
|
|
|
/* line_no */ row as u32,
|
|
|
|
/* DIType */ subroutine_type,
|
|
|
|
/* is_local_to_unit */ false,
|
|
|
|
/* is_definition */ true,
|
|
|
|
/* scope_line */ row as u32,
|
|
|
|
/* flags */ inkwell::debug_info::DIFlags::PUBLIC,
|
2023-09-06 17:50:17 +08:00
|
|
|
/* is_optimized */ registry.llvm_options.opt_level != OptimizationLevel::None,
|
2022-04-14 15:40:12 +08:00
|
|
|
);
|
|
|
|
fn_val.set_subprogram(func_scope);
|
|
|
|
|
2021-08-11 14:37:26 +08:00
|
|
|
let mut code_gen_context = CodeGenContext {
|
2021-10-16 18:08:13 +08:00
|
|
|
ctx: context,
|
2021-08-11 14:37:26 +08:00
|
|
|
resolver: task.resolver,
|
|
|
|
top_level: top_level_ctx.as_ref(),
|
2021-08-19 15:30:15 +08:00
|
|
|
calls: task.calls,
|
2022-02-12 21:13:16 +08:00
|
|
|
loop_target: None,
|
|
|
|
return_target: None,
|
|
|
|
return_buffer,
|
|
|
|
unwind_target: None,
|
|
|
|
outer_catch_clauses: None,
|
2023-12-08 17:43:32 +08:00
|
|
|
const_strings: HashMap::default(),
|
2021-08-25 15:29:58 +08:00
|
|
|
registry,
|
2021-08-11 14:37:26 +08:00
|
|
|
var_assignment,
|
|
|
|
type_cache,
|
|
|
|
primitives,
|
|
|
|
init_bb,
|
2023-12-08 17:43:32 +08:00
|
|
|
exception_val: Option::default(),
|
2021-08-11 14:37:26 +08:00
|
|
|
builder,
|
|
|
|
module,
|
|
|
|
unifier,
|
2021-11-20 19:50:25 +08:00
|
|
|
static_value_store,
|
2022-04-04 23:21:00 +08:00
|
|
|
need_sret: has_sret,
|
2023-12-08 17:43:32 +08:00
|
|
|
current_loc: Location::default(),
|
2022-04-14 15:40:12 +08:00
|
|
|
debug_info: (dibuilder, compile_unit, func_scope.as_debug_info_scope()),
|
2021-08-11 14:37:26 +08:00
|
|
|
};
|
|
|
|
|
2022-04-14 15:40:12 +08:00
|
|
|
let loc = code_gen_context.debug_info.0.create_debug_location(
|
|
|
|
context,
|
|
|
|
row as u32,
|
|
|
|
col as u32,
|
|
|
|
func_scope.as_debug_info_scope(),
|
|
|
|
None
|
|
|
|
);
|
2023-03-08 15:19:09 +08:00
|
|
|
code_gen_context.builder.set_current_debug_location(loc);
|
2022-04-14 15:40:12 +08:00
|
|
|
|
2022-03-25 22:42:01 +08:00
|
|
|
let result = codegen_function(generator, &mut code_gen_context);
|
|
|
|
|
2021-09-19 22:54:06 +08:00
|
|
|
// after static analysis, only void functions can have no return at the end.
|
2022-02-12 21:13:16 +08:00
|
|
|
if !code_gen_context.is_terminated() {
|
2024-02-19 19:30:25 +08:00
|
|
|
code_gen_context.builder.build_return(None).unwrap();
|
2021-08-11 14:37:26 +08:00
|
|
|
}
|
2021-08-12 13:55:15 +08:00
|
|
|
|
2022-04-14 15:40:12 +08:00
|
|
|
code_gen_context.builder.unset_current_debug_location();
|
|
|
|
code_gen_context.debug_info.0.finalize();
|
|
|
|
|
2021-08-13 13:33:59 +08:00
|
|
|
let CodeGenContext { builder, module, .. } = code_gen_context;
|
2022-03-25 22:42:01 +08:00
|
|
|
if let Err(e) = result {
|
2022-02-21 17:52:34 +08:00
|
|
|
return Err((builder, e));
|
|
|
|
}
|
2021-08-13 13:33:59 +08:00
|
|
|
|
2022-02-21 17:52:34 +08:00
|
|
|
Ok((builder, module, fn_val))
|
2021-08-11 14:37:26 +08:00
|
|
|
}
|
2022-03-25 22:42:01 +08:00
|
|
|
|
2023-09-20 16:59:47 +08:00
|
|
|
/// Generates LLVM IR for a function.
|
|
|
|
///
|
2023-12-08 17:43:32 +08:00
|
|
|
/// * `context` - The [LLVM Context][`Context`] used in generating the function body.
|
|
|
|
/// * `generator` - The [`CodeGenerator`] for generating various program constructs.
|
|
|
|
/// * `registry` - The [`WorkerRegistry`] responsible for monitoring this function generation task.
|
|
|
|
/// * `builder` - The [`Builder`] used for generating LLVM IR.
|
|
|
|
/// * `module` - The [`Module`] of which the generated LLVM function will be inserted into.
|
|
|
|
/// * `task` - The [`CodeGenTask`] associated with this function generation task.
|
2023-09-20 16:59:47 +08:00
|
|
|
///
|
2022-03-25 22:42:01 +08:00
|
|
|
pub fn gen_func<'ctx, G: CodeGenerator>(
|
|
|
|
context: &'ctx Context,
|
|
|
|
generator: &mut G,
|
|
|
|
registry: &WorkerRegistry,
|
|
|
|
builder: Builder<'ctx>,
|
|
|
|
module: Module<'ctx>,
|
|
|
|
task: CodeGenTask,
|
|
|
|
) -> Result<(Builder<'ctx>, Module<'ctx>, FunctionValue<'ctx>), (Builder<'ctx>, String)> {
|
|
|
|
let body = task.body.clone();
|
|
|
|
gen_func_impl(context, generator, registry, builder, module, task, |generator, ctx| {
|
2023-10-23 15:42:39 +08:00
|
|
|
generator.gen_block(ctx, body.iter())
|
2022-03-25 22:42:01 +08:00
|
|
|
})
|
|
|
|
}
|
2023-09-20 13:34:50 +08:00
|
|
|
|
2023-09-20 16:59:47 +08:00
|
|
|
/// Converts the value of a boolean-like value `bool_value` into an `i1`.
|
2023-09-20 13:34:50 +08:00
|
|
|
fn bool_to_i1<'ctx>(builder: &Builder<'ctx>, bool_value: IntValue<'ctx>) -> IntValue<'ctx> {
|
2023-12-08 17:43:32 +08:00
|
|
|
if bool_value.get_type().get_bit_width() == 1 {
|
|
|
|
bool_value
|
|
|
|
} else {
|
2024-02-19 19:30:25 +08:00
|
|
|
builder
|
|
|
|
.build_int_compare(
|
|
|
|
IntPredicate::NE,
|
|
|
|
bool_value,
|
|
|
|
bool_value.get_type().const_zero(),
|
|
|
|
"tobool",
|
|
|
|
)
|
|
|
|
.unwrap()
|
2023-09-20 13:34:50 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-20 16:59:47 +08:00
|
|
|
/// Converts the value of a boolean-like value `bool_value` into an `i8`.
|
2023-09-20 13:34:50 +08:00
|
|
|
fn bool_to_i8<'ctx>(
|
|
|
|
builder: &Builder<'ctx>,
|
|
|
|
ctx: &'ctx Context,
|
|
|
|
bool_value: IntValue<'ctx>
|
|
|
|
) -> IntValue<'ctx> {
|
|
|
|
let value_bits = bool_value.get_type().get_bit_width();
|
|
|
|
match value_bits {
|
|
|
|
8 => bool_value,
|
2024-02-19 19:30:25 +08:00
|
|
|
1 => builder.build_int_z_extend(bool_value, ctx.i8_type(), "frombool").unwrap(),
|
2023-09-20 13:34:50 +08:00
|
|
|
_ => bool_to_i8(
|
|
|
|
builder,
|
|
|
|
ctx,
|
2024-02-19 19:30:25 +08:00
|
|
|
builder
|
|
|
|
.build_int_compare(
|
|
|
|
IntPredicate::NE,
|
|
|
|
bool_value,
|
|
|
|
bool_value.get_type().const_zero(),
|
|
|
|
"",
|
|
|
|
)
|
|
|
|
.unwrap()
|
2023-09-20 13:34:50 +08:00
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
2023-10-06 12:11:57 +08:00
|
|
|
|
|
|
|
/// Generates a sequence of IR which checks whether `value` does not exceed the upper bound of the
|
|
|
|
/// range as defined by `stop` and `step`.
|
|
|
|
///
|
|
|
|
/// Note that the generated IR will **not** check whether value is part of the range or whether
|
|
|
|
/// value exceeds the lower bound of the range (as evident by the missing `start` argument).
|
|
|
|
///
|
|
|
|
/// The generated IR is equivalent to the following Rust code:
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// let sign = step > 0;
|
|
|
|
/// let (lo, hi) = if sign { (value, stop) } else { (stop, value) };
|
|
|
|
/// let cmp = lo < hi;
|
|
|
|
/// ```
|
|
|
|
///
|
2023-12-08 17:43:32 +08:00
|
|
|
/// Returns an `i1` [`IntValue`] representing the result of whether the `value` is in the range.
|
2023-12-06 11:49:02 +08:00
|
|
|
fn gen_in_range_check<'ctx>(
|
|
|
|
ctx: &CodeGenContext<'ctx, '_>,
|
2023-10-06 12:11:57 +08:00
|
|
|
value: IntValue<'ctx>,
|
|
|
|
stop: IntValue<'ctx>,
|
|
|
|
step: IntValue<'ctx>,
|
|
|
|
) -> IntValue<'ctx> {
|
2024-02-19 19:30:25 +08:00
|
|
|
let sign = ctx.builder.build_int_compare(IntPredicate::SGT, step, ctx.ctx.i32_type().const_zero(), "").unwrap();
|
|
|
|
let lo = ctx.builder.build_select(sign, value, stop, "")
|
|
|
|
.map(BasicValueEnum::into_int_value)
|
|
|
|
.unwrap();
|
|
|
|
let hi = ctx.builder.build_select(sign, stop, value, "")
|
|
|
|
.map(BasicValueEnum::into_int_value)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
ctx.builder.build_int_compare(IntPredicate::SLT, lo, hi, "cmp").unwrap()
|
2023-10-06 12:11:57 +08:00
|
|
|
}
|