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.

Commit 5298774a authored by Eduardo Souza's avatar Eduardo Souza
Browse files

Follow formatting instructions.

parent 1c5e3357
max_width = 80
wrap_comments = true
trailing_comma = "Never"
This diff is collapsed.
......@@ -8,31 +8,35 @@ use std::{iter, ptr};
extern crate llvm_sys as llvm;
use self::llvm::analysis::LLVMVerifierFailureAction::{
LLVMAbortProcessAction, LLVMPrintMessageAction,
LLVMAbortProcessAction, LLVMPrintMessageAction
};
use self::llvm::analysis::{LLVMVerifyFunction, LLVMVerifyModule};
use self::llvm::execution_engine::{
LLVMCreateExecutionEngineForModule, LLVMCreateJITCompilerForModule,
LLVMCreateSimpleMCJITMemoryManager, LLVMDisposeExecutionEngine, LLVMExecutionEngineRef,
LLVMFreeMachineCodeForFunction, LLVMGenericValueToFloat, LLVMGenericValueToInt,
LLVMGenericValueToPointer, LLVMInitializeMCJITCompilerOptions, LLVMLinkInMCJIT,
LLVMMCJITCompilerOptions, LLVMOpaqueExecutionEngine, LLVMRunFunction,
LLVMCreateSimpleMCJITMemoryManager, LLVMDisposeExecutionEngine,
LLVMExecutionEngineRef, LLVMFreeMachineCodeForFunction,
LLVMGenericValueToFloat, LLVMGenericValueToInt, LLVMGenericValueToPointer,
LLVMInitializeMCJITCompilerOptions, LLVMLinkInMCJIT,
LLVMMCJITCompilerOptions, LLVMOpaqueExecutionEngine, LLVMRunFunction
};
use self::llvm::prelude::{
LLVMBasicBlockRef, LLVMBool, LLVMBuilderRef, LLVMContextRef, LLVMPassManagerRef, LLVMTypeRef,
LLVMBasicBlockRef, LLVMBool, LLVMBuilderRef, LLVMContextRef,
LLVMPassManagerRef, LLVMTypeRef
};
use self::llvm::support::LLVMAddSymbol;
use self::llvm::target::{
LLVMIntPtrType, LLVMTargetDataRef, LLVM_InitializeNativeAsmPrinter, LLVM_InitializeNativeTarget,
LLVMIntPtrType, LLVMTargetDataRef, LLVM_InitializeNativeAsmPrinter,
LLVM_InitializeNativeTarget
};
use self::llvm::target_machine::{
LLVMCodeGenFileType, LLVMCodeGenOptLevel, LLVMCodeModel, LLVMCreateTargetDataLayout,
LLVMCreateTargetMachine, LLVMGetDefaultTargetTriple, LLVMGetFirstTarget, LLVMRelocMode,
LLVMTargetMachineEmitToFile, LLVMTargetMachineRef,
LLVMCodeGenFileType, LLVMCodeGenOptLevel, LLVMCodeModel,
LLVMCreateTargetDataLayout, LLVMCreateTargetMachine,
LLVMGetDefaultTargetTriple, LLVMGetFirstTarget, LLVMRelocMode,
LLVMTargetMachineEmitToFile, LLVMTargetMachineRef
};
use self::llvm::transforms::scalar::{
LLVMAddBasicAliasAnalysisPass, LLVMAddCFGSimplificationPass, LLVMAddGVNPass,
LLVMAddInstructionCombiningPass, LLVMAddReassociatePass,
LLVMAddBasicAliasAnalysisPass, LLVMAddCFGSimplificationPass,
LLVMAddGVNPass, LLVMAddInstructionCombiningPass, LLVMAddReassociatePass
};
use self::llvm::transforms::util::LLVMAddPromoteMemoryToRegisterPass;
use self::llvm::LLVMRealPredicate::LLVMRealOLT;
......@@ -48,21 +52,21 @@ pub enum RunResult {
Double(f64),
Int(i64),
Bool(bool),
IntArray(Vec<i64>),
IntArray(Vec<i64>)
}
pub struct Context {
pub context: LLVMContextRef,
pub builder: LLVMBuilderRef,
pub named_values: HashMap<String, LLVMValueRef>,
pub global_vars: HashMap<String, (Type, LLVMValueRef)>,
pub global_vars: HashMap<String, (Type, LLVMValueRef)>,
pub var_type_map: HashMap<String, Type>,
pub fn_type_map: HashMap<String, Type>,
pub curr_function: i32,
pub pass_manager: LLVMPassManagerRef,
pub target_machine: LLVMTargetMachineRef,
pub target_data: LLVMTargetDataRef,
pub options: LLVMMCJITCompilerOptions,
pub options: LLVMMCJITCompilerOptions
}
impl Context {
......@@ -74,7 +78,7 @@ impl Context {
LLVMInitializeMCJITCompilerOptions(
&mut options,
std::mem::size_of::<LLVMMCJITCompilerOptions>(),
std::mem::size_of::<LLVMMCJITCompilerOptions>()
);
LLVMLinkInMCJIT();
......@@ -96,7 +100,7 @@ impl Context {
feature.as_ptr(),
opt_level,
reloc_mode,
code_model,
code_model
);
let target_data = LLVMCreateTargetDataLayout(target_machine);
......@@ -104,14 +108,14 @@ impl Context {
context,
builder,
named_values,
global_vars : HashMap::new(),
global_vars: HashMap::new(),
var_type_map: HashMap::new(),
fn_type_map: HashMap::new(),
curr_function: 0,
pass_manager,
target_machine,
target_data,
options,
options
}
}
......@@ -128,7 +132,7 @@ impl Context {
Type::IntArray(n) => LLVMArrayType(LLVMInt64Type(), *n as u32),
Type::DoubleArray(n) => LLVMArrayType(LLVMDoubleType(), *n as u32),
Type::BoolArray(n) => LLVMArrayType(LLVMInt1Type(), *n as u32),
_ => panic!("Unsupported type."),
_ => panic!("Unsupported type.")
}
}
}
......@@ -137,7 +141,7 @@ unsafe fn run_function(
function: Result<*mut LLVMValue, String>,
function_type: &Type,
module: *mut LLVMModule,
context: &mut Context,
context: &mut Context
) -> Result<RunResult, String> {
let mut ee = 0 as LLVMExecutionEngineRef;
let mut error = 0 as *mut c_char;
......@@ -151,7 +155,13 @@ unsafe fn run_function(
return Err(message);
}
if LLVMCreateJITCompilerForModule(&mut ee, module, context.options.OptLevel, &mut error) > 0 {
if LLVMCreateJITCompilerForModule(
&mut ee,
module,
context.options.OptLevel,
&mut error
) > 0
{
let cstr_buf = std::ffi::CStr::from_ptr(error);
let result = String::from_utf8_lossy(cstr_buf.to_bytes()).into_owned();
let message = LLVMCreateMessage(error);
......@@ -165,9 +175,9 @@ unsafe fn run_function(
let (f, result) = match function {
Ok(f) => (
f,
LLVMRunFunction(ee, f, args.len() as c_uint, args.as_mut_ptr()),
LLVMRunFunction(ee, f, args.len() as c_uint, args.as_mut_ptr())
),
Err(e) => return Err(e),
Err(e) => return Err(e)
};
let file_type = LLVMCodeGenFileType::LLVMAssemblyFile;
......@@ -179,7 +189,7 @@ unsafe fn run_function(
module,
output_file.as_ptr() as *mut i8,
file_type,
&mut error_str,
&mut error_str
);
if res == 1 {
let x = CStr::from_ptr(error_str);
......@@ -204,10 +214,10 @@ unsafe fn run_function(
Ok(RunResult::Bool(result))
}
// Type::IntArray => {
// let result = LLVMGenericValueToPointer(result) as Vec<i64>;
// Ok(RunResult::IntArray(result))
// let result = LLVMGenericValueToPointer(result) as
// Vec<i64>; Ok(RunResult::IntArray(result))
// }
_ => Err("invalid function type".parse().unwrap()),
_ => Err("invalid function type".parse().unwrap())
}
}
......@@ -219,13 +229,18 @@ pub extern "C" fn putchard(x: f64) -> f64 {
pub unsafe fn init() {
LLVMAddSymbol(
"putchard\0".as_ptr() as *const c_char,
putchard as *mut c_void,
putchard as *mut c_void
);
}
pub unsafe fn code_gen(filename: String, mut nodes: ASTNodes) -> Vec<Result<RunResult, String>> {
pub unsafe fn code_gen(
filename: String,
mut nodes: ASTNodes
) -> Vec<Result<RunResult, String>> {
init();
let module = llvm::core::LLVMModuleCreateWithName(filename.as_str().as_ptr() as *const _);
let module = llvm::core::LLVMModuleCreateWithName(
filename.as_str().as_ptr() as *const _
);
let function_pass_manager = LLVMCreateFunctionPassManagerForModule(module);
LLVMAddBasicAliasAnalysisPass(function_pass_manager);
LLVMAddInstructionCombiningPass(function_pass_manager);
......@@ -241,25 +256,40 @@ pub unsafe fn code_gen(filename: String, mut nodes: ASTNodes) -> Vec<Result<RunR
let mut returning_values = vec![];
for global_var in nodes.global_vars.iter_mut() {
let out_file = CString::new(format!("out_{}.ll", module_number)).unwrap();
let out_file =
CString::new(format!("out_{}.ll", module_number)).unwrap();
global_var.code_gen(&module, &mut context);
llvm::core::LLVMPrintModuleToFile(module, out_file.as_ptr(), ptr::null_mut());
llvm::core::LLVMPrintModuleToFile(
module,
out_file.as_ptr(),
ptr::null_mut()
);
}
for prototype in nodes.prototypes.iter_mut() {
let out_file = CString::new(format!("out_{}.ll", module_number)).unwrap();
let out_file =
CString::new(format!("out_{}.ll", module_number)).unwrap();
prototype.code_gen(&module, &mut context);
llvm::core::LLVMPrintModuleToFile(module, out_file.as_ptr(), ptr::null_mut());
llvm::core::LLVMPrintModuleToFile(
module,
out_file.as_ptr(),
ptr::null_mut()
);
}
for function in nodes.functions.iter_mut() {
let out_file = CString::new(format!("out_{}.ll", module_number)).unwrap();
let out_file =
CString::new(format!("out_{}.ll", module_number)).unwrap();
let result = function.code_gen(&module, &mut context);
llvm::core::LLVMPrintModuleToFile(module, out_file.as_ptr(), ptr::null_mut());
llvm::core::LLVMPrintModuleToFile(
module,
out_file.as_ptr(),
ptr::null_mut()
);
// execute module
if function.proto().name() == "" {
......@@ -267,11 +297,14 @@ pub unsafe fn code_gen(filename: String, mut nodes: ASTNodes) -> Vec<Result<RunR
result,
function.proto().return_type(),
module,
&mut context,
&mut context
));
}
let module = llvm::core::LLVMModuleCreateWithName(filename.as_str().as_ptr() as *const _);
let function_pass_manager = LLVMCreateFunctionPassManagerForModule(module);
let module = llvm::core::LLVMModuleCreateWithName(
filename.as_str().as_ptr() as *const _
);
let function_pass_manager =
LLVMCreateFunctionPassManagerForModule(module);
let context = Context::new(function_pass_manager);
}
......@@ -282,23 +315,33 @@ trait Code_gen {
unsafe fn code_gen(
&mut self,
module: &*mut LLVMModule,
context: &mut Context,
context: &mut Context
) -> Result<LLVMValueRef, String>;
}
impl Code_gen for Global {
unsafe fn code_gen(&mut self, module: &*mut LLVMModule, context: &mut Context) -> Result<*mut LLVMValue, String> {
unsafe fn code_gen(
&mut self,
module: &*mut LLVMModule,
context: &mut Context
) -> Result<*mut LLVMValue, String> {
let llvm_var_type = context.get_llvm_type(self.var_type());
let var_name = self.var().name().clone();
let global = LLVMAddGlobal(*module, llvm_var_type, var_name.as_str().as_ptr() as *const c_char);
let global = LLVMAddGlobal(
*module,
llvm_var_type,
var_name.as_str().as_ptr() as *const c_char
);
let init_value = match self.value().code_gen(module, context) {
Ok(init_value) => init_value,
e @ Err(_) => return e,
e @ Err(_) => return e
};
context.global_vars.insert(var_name.clone(), (self.var_type().clone(), init_value));
context
.global_vars
.insert(var_name.clone(), (self.var_type().clone(), init_value));
Ok(global)
}
......@@ -308,9 +351,10 @@ impl Code_gen for Prototype {
unsafe fn code_gen(
&mut self,
module: &*mut LLVMModule,
context: &mut Context,
context: &mut Context
) -> Result<LLVMValueRef, String> {
let function = match get_function_by_name(*module, self.name().as_str()) {
let function = match get_function_by_name(*module, self.name().as_str())
{
Some(function) => {
if LLVMCountParams(function) as usize != self.args().len() {
return Err(String::from(
......@@ -338,7 +382,7 @@ impl Code_gen for Prototype {
context.get_llvm_type(self.return_type()),
param_types.as_mut_ptr(),
param_types.len() as c_uint,
false as LLVMBool,
false as LLVMBool
);
let name;
let fname;
......@@ -355,7 +399,11 @@ impl Code_gen for Prototype {
let ftype = self.return_type();
context.fn_type_map.insert(fname.clone(), ftype.clone());
let function = LLVMAddFunction(*module, name.as_ptr() as *const c_char, fty);
let function = LLVMAddFunction(
*module,
name.as_ptr() as *const c_char,
fty
);
for i in 0..self.args().len() {
let param = LLVMGetParam(function, i as u32);
......@@ -364,7 +412,7 @@ impl Code_gen for Prototype {
LLVMSetValueName2(
param,
param_name.as_str().as_ptr() as *const c_char,
param_name.len(),
param_name.len()
)
}
function
......@@ -377,9 +425,14 @@ impl Code_gen for Prototype {
}
}
pub fn get_function_by_name(function: *mut LLVMModule, name: &str) -> Option<*mut LLVMValue> {
pub fn get_function_by_name(
function: *mut LLVMModule,
name: &str
) -> Option<*mut LLVMValue> {
let name = CString::new(name).unwrap();
let function = unsafe { LLVMGetNamedFunction(function, name.as_ptr() as *const c_char) };
let function = unsafe {
LLVMGetNamedFunction(function, name.as_ptr() as *const c_char)
};
if !function.is_null() {
unsafe { Some(function) }
} else {
......@@ -390,7 +443,7 @@ pub fn get_function_by_name(function: *mut LLVMModule, name: &str) -> Option<*mu
pub unsafe fn create_block_alloca(
context: &mut Context,
block: LLVMBasicBlockRef,
var_name: &str,
var_name: &str
) -> LLVMValueRef {
let builder = LLVMCreateBuilder();
let fi = LLVMGetFirstInstruction(block);
......@@ -399,7 +452,7 @@ pub unsafe fn create_block_alloca(
LLVMBuildAlloca(
builder,
context.get_llvm_type(context.var_type_map.get(var_name).unwrap()),
var.as_str().as_ptr() as *const c_char,
var.as_str().as_ptr() as *const c_char
)
}
......@@ -407,7 +460,7 @@ impl Code_gen for Function {
unsafe fn code_gen(
&mut self,
module: &*mut LLVMModule,
context: &mut Context,
context: &mut Context
) -> Result<LLVMValueRef, String> {
context.named_values.clear();
context.var_type_map.clear();
......@@ -421,20 +474,26 @@ impl Code_gen for Function {
let function = match self.proto().code_gen(module, context) {
Ok(function) => function,
e @ Err(_) => return e,
e @ Err(_) => return e
};
let mut basic_block = LLVMAppendBasicBlockInContext(
context.context,
function,
CString::new("entry").unwrap().as_ptr(),
CString::new("entry").unwrap().as_ptr()
);
LLVMPositionBuilderAtEnd(context.builder, basic_block);
// set function parameters
for (param, (arg_type, arg_name)) in get_params(function).iter().zip(self.proto().args()) {
let arg_alloca = create_block_alloca(context, basic_block, arg_name.clone().as_str());
for (param, (arg_type, arg_name)) in
get_params(function).iter().zip(self.proto().args())
{
let arg_alloca = create_block_alloca(
context,
basic_block,
arg_name.clone().as_str()
);
LLVMBuildStore(context.builder, *param, arg_alloca);
context.named_values.insert(arg_name.clone(), arg_alloca);
}
......
......@@ -157,7 +157,7 @@ macro_rules! constdef {
let $name = $vm.declare_const(
MuEntityHeader::named($vm.next_id(), Mu(stringify!($name))),
$ty.clone(),
$val,
$val
);
$vm.set_name($name.as_entity());
};
......@@ -167,7 +167,7 @@ macro_rules! globaldef {
(($vm: expr) <$ty: ident> $name: ident) => {
let $name = $vm.declare_global(
MuEntityHeader::named($vm.next_id(), Mu(stringify!($name))),
$ty.clone(),
$ty.clone()
);
$vm.set_name($name.as_entity());
};
......@@ -186,7 +186,7 @@ macro_rules! funcdecl {
(($vm: expr) <$sig: ident> $name: ident) => {
let func = MuFunction::new(
MuEntityHeader::named($vm.next_id(), Mu(stringify!($name))),
$sig.clone(),
$sig.clone()
);
$vm.set_name(func.as_entity());
let $name = func.hdr.clone();
......@@ -199,7 +199,7 @@ macro_rules! funcdef {
let mut $version = MuFunctionVersion::new(
MuEntityHeader::named($vm.next_id(), Mu(stringify!($version))),
$func.id(),
$sig.clone(),
$sig.clone()
);
$vm.set_name($version.as_entity());
};
......@@ -219,7 +219,10 @@ macro_rules! define_func_ver {
macro_rules! block {
(($vm: expr, $fv: ident) $name: ident) => {
let mut $name = Block::new(MuEntityHeader::named($vm.next_id(), Mu(stringify!($name))));
let mut $name = Block::new(MuEntityHeader::named(
$vm.next_id(),
Mu(stringify!($name))
));
$vm.set_name($name.as_entity());
};
}
......@@ -249,7 +252,7 @@ macro_rules! ssa {
(($vm: expr, $fv: ident) <$ty: ident> $name: ident) => {
let $name = $fv.new_ssa(
MuEntityHeader::named($vm.next_id(), Mu(stringify!($name))),
$ty.clone(),
$ty.clone()
);
$vm.set_name($name.as_entity());
};
......@@ -923,8 +926,8 @@ macro_rules! inst_rt {
stack: 1,
thread_local: None,
is_exception: false,
args: vec![],
},
args: vec![]
}
});
};
......@@ -935,7 +938,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: None,
ops: vec![$thread.clone()],
v: Instruction_::NotifyThread(0),
v: Instruction_::NotifyThread(0)
});
};
......@@ -946,7 +949,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![$thread.clone()],
v: Instruction_::ThreadGetPriority(0),
v: Instruction_::ThreadGetPriority(0)
});
};
......@@ -957,7 +960,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: None,
ops: vec![$thread.clone(), $priority.clone()],
v: Instruction_::ThreadSetPriority(0, 1),
v: Instruction_::ThreadSetPriority(0, 1)
});
};
......@@ -968,7 +971,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![$thread.clone(), $cpu.clone()],
v: Instruction_::ThreadIssetCPU(0, 1),
v: Instruction_::ThreadIssetCPU(0, 1)
});
};
......@@ -979,7 +982,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![]),
ops: vec![$thread.clone(), $cpu.clone()],
v: Instruction_::ThreadSetCPU(0, 1),
v: Instruction_::ThreadSetCPU(0, 1)
});
};
......@@ -990,7 +993,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![]),
ops: vec![$thread.clone(), $cpu.clone()],
v: Instruction_::ThreadClearCPU(0, 1),
v: Instruction_::ThreadClearCPU(0, 1)
});
};
......@@ -1001,7 +1004,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![$size.clone()],
v: Instruction_::NewReg(0),
v: Instruction_::NewReg(0)
});
};
......@@ -1011,7 +1014,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![]),
ops: vec![$regionref.clone()],
v: Instruction_::DeleteReg(0),
v: Instruction_::DeleteReg(0)
});
};
......@@ -1022,7 +1025,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![$regionref.clone()],
v: Instruction_::rAlloc(0, $ty.clone()),
v: Instruction_::rAlloc(0, $ty.clone())
});
};
......@@ -1033,7 +1036,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![$regionref.clone(), $var_len.clone()],
v: Instruction_::rAllocHybrid(0, $ty.clone(), 1),
v: Instruction_::rAllocHybrid(0, $ty.clone(), 1)
});
};
......@@ -1044,7 +1047,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![],
v: Instruction_::eAlloc($ty.clone()),
v: Instruction_::eAlloc($ty.clone())
});
};
......@@ -1055,7 +1058,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![$var_len.clone()],
v: Instruction_::eAllocHybrid($ty.clone(), 0),
v: Instruction_::eAllocHybrid($ty.clone(), 0)
});
};
......@@ -1066,7 +1069,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![]),
ops: vec![$blk_ref.clone()],
v: Instruction_::eDelete(0),
v: Instruction_::eDelete(0)
});
};
......@@ -1077,7 +1080,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![],
v: Instruction_::GetTime,
v: Instruction_::GetTime
});
};
......@@ -1088,7 +1091,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![]),
ops: vec![$time.clone()],
v: Instruction_::SetTime(0),
v: Instruction_::SetTime(0)
});
};
......@@ -1098,7 +1101,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: None,
ops: vec![$val.clone()],
v: Instruction_::PrintTime(0),
v: Instruction_::PrintTime(0)
});
};
......@@ -1109,7 +1112,7 @@ macro_rules! inst_rt {
hdr: MuEntityHeader::unnamed($vm.next_id()),
value: Some(vec![$res.clone_value()]),
ops: vec![],
v: Instruction_::NewTimer,
v: Instruction_::NewTimer
});
};
......@@ -1126,7 +1129,7 @@ macro_rules! inst_rt {
$func.clone(),