-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathllvm_typesystem.rs
366 lines (331 loc) · 15.6 KB
/
llvm_typesystem.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright (c) 2020 Ghaith Hachem and Mathias Rieder
use inkwell::{
context::Context,
types::{FloatType, IntType},
values::{ArrayValue, BasicValueEnum, FloatValue, IntValue, PointerValue},
};
use crate::{
index::Index,
resolver::StatementAnnotation,
typesystem::{DataType, DataTypeInformation, InternalType, StructSource},
};
use super::{generators::llvm::Llvm, llvm_index::LlvmTypedIndex};
/// A convenience macro to call the `cast` function with fewer parameters.
///
/// Generates a cast from the given `value` to the given `target_type` if necessary and returns the casted value. It returns
/// the original `value` if no cast is necessary or if the provided value is not eligible to be cast (to the target type or at all).
///
/// This function provides no additional validation or safeguards for invalid casts, as such validation is expected to be
/// performed at the validation stage prior to code-gen.
/// Cast instructions for values other than IntValue, FloatValue and PointerValue will simply be ignored (and the value
/// returned unchanged). Invalid casting instructions for the above-mentioned values will fail spectacularly instead.
///
/// - `generator` the generator to use. must contain the following fields:
/// - `llvm` the llvm utilities to use for code-generation
/// - `index` the current Index used for type-lookups
/// - `llvm_type_index` the type index to lookup llvm generated types
/// - `target_type` the expected target type of the value
/// - `value_type` the current type of the given value
/// - `value` the value to (maybe) cast
macro_rules! cast_if_needed {
($generator:expr, $target_type:expr, $value_type:expr, $value:expr, $annotation:expr) => {
crate::codegen::llvm_typesystem::cast(
$generator.llvm,
$generator.index,
$generator.llvm_index,
$target_type,
$value_type,
$value,
$annotation,
)
};
}
pub(crate) use cast_if_needed;
pub fn get_llvm_int_type<'a>(context: &'a Context, size: u32, name: &str) -> IntType<'a> {
match size {
1 => context.bool_type(),
8 => context.i8_type(),
16 => context.i16_type(),
32 => context.i32_type(),
64 => context.i64_type(),
128 => context.i128_type(),
_ => unreachable!("Invalid size for type : '{name}' at {size}"),
}
}
pub fn get_llvm_float_type<'a>(context: &'a Context, size: u32, name: &str) -> FloatType<'a> {
match size {
32 => context.f32_type(),
64 => context.f64_type(),
_ => unreachable!("Invalid size for type : '{name}' at {size}"),
}
}
/// Generates a cast from the given `value` to the given `target_type` if necessary and returns the casted value. It returns
/// the original `value` if no cast is necessary or if the provided value is not eligible to be cast (to the target type or at all).
///
/// This function provides no additional validation or safeguards for invalid casts, as such validation is expected to be
/// performed at the validation stage prior to code-gen.
/// Cast instructions for values other than IntValue, FloatValue and PointerValue will simply be ignored (and the value
/// returned unchanged). Invalid casting instructions for the above-mentioned values will fail spectacularly instead.
///
/// - `llvm` the llvm utilities to use for code-generation
/// - `index` the current Index used for type-lookups
/// - `llvm_type_index` the type index to lookup llvm generated types
/// - `target_type` the expected target type of the value
/// - `value_type` the current type of the given value
/// - `value` the value to (maybe) cast
pub fn cast<'ctx>(
llvm: &Llvm<'ctx>,
index: &Index,
llvm_type_index: &LlvmTypedIndex<'ctx>,
target_type: &DataType,
value_type: &DataType,
value: BasicValueEnum<'ctx>,
annotation: Option<&StatementAnnotation>,
) -> BasicValueEnum<'ctx> {
value.cast(&CastInstructionData::new(llvm, index, llvm_type_index, value_type, target_type, annotation))
}
struct CastInstructionData<'ctx, 'cast> {
llvm: &'cast Llvm<'ctx>,
index: &'cast Index,
llvm_type_index: &'cast LlvmTypedIndex<'ctx>,
value_type: &'cast DataTypeInformation,
target_type: &'cast DataTypeInformation,
annotation: Option<&'cast StatementAnnotation>,
}
impl<'ctx, 'cast> CastInstructionData<'ctx, 'cast> {
fn new(
llvm: &'cast Llvm<'ctx>,
index: &'cast Index,
llvm_type_index: &'cast LlvmTypedIndex<'ctx>,
value_type: &DataType,
target_type: &DataType,
annotation: Option<&'cast StatementAnnotation>,
) -> Self {
let target_type = index.get_intrinsic_type_by_name(target_type.get_name()).get_type_information();
let value_type = index.get_intrinsic_type_by_name(value_type.get_name()).get_type_information();
let target_type =
if let DataTypeInformation::Pointer { auto_deref: Some(_), inner_type_name, .. } = target_type {
// Deref auto-deref pointers before casting
index.get_intrinsic_type_by_name(inner_type_name.as_str()).get_type_information()
} else {
target_type
};
CastInstructionData { llvm, index, llvm_type_index, value_type, target_type, annotation }
}
}
trait Castable<'ctx, 'cast> {
fn cast(self, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx>;
}
trait Promotable<'ctx, 'cast> {
fn promote(self, lsize: u32, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx>;
}
trait Truncatable<'ctx, 'cast> {
fn truncate(self, lsize: u32, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx>;
}
impl<'ctx, 'cast> Castable<'ctx, 'cast> for BasicValueEnum<'ctx> {
fn cast(self, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
match self {
BasicValueEnum::IntValue(val) => val.cast(cast_data),
BasicValueEnum::FloatValue(val) => val.cast(cast_data),
BasicValueEnum::PointerValue(val) => val.cast(cast_data),
BasicValueEnum::ArrayValue(val) => val.cast(cast_data),
_ => self,
}
}
}
impl<'ctx, 'cast> Castable<'ctx, 'cast> for IntValue<'ctx> {
fn cast(self, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
let lsize = cast_data.target_type.get_size_in_bits(cast_data.index).unwrap();
match cast_data.target_type {
DataTypeInformation::Integer { .. } => {
//its important to use the real type's size here, because we may have an i1 which is annotated as BOOL (8 bit)
let rsize = self.get_type().get_bit_width();
if lsize < rsize {
//Truncate
self.truncate(lsize, cast_data)
} else {
//Expand
self.promote(lsize, cast_data)
}
}
DataTypeInformation::Float { .. } => {
let float_type = get_llvm_float_type(cast_data.llvm.context, lsize, "Float");
if cast_data.value_type.is_signed_int() {
cast_data.llvm.builder.build_signed_int_to_float(self, float_type, "").into()
} else {
cast_data.llvm.builder.build_unsigned_int_to_float(self, float_type, "").into()
}
}
DataTypeInformation::Pointer { .. } => {
let Ok(associated_type) =
cast_data.llvm_type_index.get_associated_type(cast_data.target_type.get_name())
else {
unreachable!(
"Target type of cast instruction does not exist: {}",
cast_data.target_type.get_name()
)
};
cast_data.llvm.builder.build_int_to_ptr(self, associated_type.into_pointer_type(), "").into()
}
_ => unreachable!("Cannot cast integer value to {}", cast_data.target_type.get_name()),
}
}
}
impl<'ctx, 'cast> Castable<'ctx, 'cast> for FloatValue<'ctx> {
fn cast(self, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
let rsize = &cast_data.value_type.get_size_in_bits(cast_data.index).unwrap();
match cast_data.target_type {
DataTypeInformation::Float { size: lsize, .. } => {
if lsize < rsize {
self.truncate(*lsize, cast_data)
} else {
self.promote(*lsize, cast_data)
}
}
DataTypeInformation::Integer { signed, size: lsize, .. } => {
let int_type = get_llvm_int_type(cast_data.llvm.context, *lsize, "Integer");
if *signed {
cast_data.llvm.builder.build_float_to_signed_int(self, int_type, "").into()
} else {
cast_data.llvm.builder.build_float_to_unsigned_int(self, int_type, "").into()
}
}
_ => unreachable!("Cannot cast floating-point value to {}", cast_data.target_type.get_name()),
}
}
}
impl<'ctx, 'cast> Castable<'ctx, 'cast> for PointerValue<'ctx> {
fn cast(self, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
match &cast_data.target_type {
DataTypeInformation::Integer { size: lsize, .. } => cast_data
.llvm
.builder
.build_ptr_to_int(self, get_llvm_int_type(cast_data.llvm.context, *lsize, ""), "")
.into(),
DataTypeInformation::Pointer { .. } => {
let Ok(target_ptr_type) =
cast_data.llvm_type_index.get_associated_type(cast_data.target_type.get_name())
else {
unreachable!(
"Target type of cast instruction does not exist: {}",
cast_data.target_type.get_name()
)
};
if BasicValueEnum::from(self).get_type() != target_ptr_type {
// bit-cast necessary
cast_data.llvm.builder.build_bitcast(self, target_ptr_type, "")
} else {
//this is ok, no cast required
self.into()
}
}
DataTypeInformation::Struct {
source: StructSource::Internal(InternalType::VariableLengthArray { .. }),
..
} => {
// we are dealing with an auto-deref vla parameter. first we have to deref our array and build the fat pointer
let struct_val = cast_data.llvm.builder.build_load(self, "auto_deref").cast(cast_data);
// create a pointer to the generated StructValue
let struct_ptr = cast_data.llvm.builder.build_alloca(struct_val.get_type(), "vla_struct_ptr");
cast_data.llvm.builder.build_store(struct_ptr, struct_val);
struct_ptr.into()
}
_ => unreachable!("Cannot cast pointer value to {}", cast_data.target_type.get_name()),
}
}
}
impl<'ctx, 'cast> Castable<'ctx, 'cast> for ArrayValue<'ctx> {
/// Generates a fat pointer struct for an array if the target type is a VLA,
/// otherwise returns the value as is.
fn cast(self, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
if !cast_data.target_type.is_vla() {
return self.into();
}
let builder = &cast_data.llvm.builder;
let zero = cast_data.llvm.i32_type().const_zero();
let Ok(associated_type) =
cast_data.llvm_type_index.get_associated_type(cast_data.target_type.get_name())
else {
unreachable!(
"Target type of cast instruction does not exist: {}",
cast_data.target_type.get_name()
)
};
// Get array annotation from parent POU and get pointer to array
let Some(StatementAnnotation::Variable { qualified_name, .. }) = cast_data.annotation else {
unreachable!("Undefined reference: {}", cast_data.value_type.get_name())
};
let array_pointer = cast_data
.llvm_type_index
.find_loaded_associated_variable_value(qualified_name.as_str())
.unwrap_or_else(|| unreachable!("passed array must be in the llvm index"));
// gep into the original array. the resulting address will be stored in the VLA struct
let arr_gep = unsafe { builder.build_in_bounds_gep(array_pointer, &[zero, zero], "outer_arr_gep") };
// -- Generate struct & arr_ptr --
let ty = associated_type.into_struct_type();
let vla_struct = builder.build_alloca(ty, "vla_struct");
let Ok(vla_arr_ptr) = builder.build_struct_gep(vla_struct, 0, "vla_array_gep") else {
unreachable!("Must have a valid, GEP-able fat-pointer struct at this stage")
};
let Ok(vla_dimensions_ptr) = builder.build_struct_gep(vla_struct, 1, "vla_dimensions_gep") else {
unreachable!("Must have a valid, GEP-able fat-pointer struct at this stage")
};
// -- Generate dimensions --
let DataTypeInformation::Array { dimensions, .. } = cast_data.value_type else { unreachable!() };
let mut dims = Vec::new();
for dim in dimensions {
dims.push(dim.start_offset.as_int_value(cast_data.index).unwrap());
dims.push(dim.end_offset.as_int_value(cast_data.index).unwrap());
}
// Populate each array element
let dimensions =
dims.iter().map(|it| cast_data.llvm.i32_type().const_int(*it as u64, true)).collect::<Vec<_>>();
let array_value = cast_data.llvm.i32_type().const_array(&dimensions);
// FIXME: should be memcopied, but is an rvalue. can only initialize global variables with value types. any other way for alloca'd variables than using store?
builder.build_store(vla_dimensions_ptr, array_value);
builder.build_store(vla_arr_ptr, arr_gep);
builder.build_load(vla_struct, "")
}
}
impl<'ctx, 'cast> Promotable<'ctx, 'cast> for IntValue<'ctx> {
fn promote(self, lsize: u32, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
let llvm_int_type = get_llvm_int_type(cast_data.llvm.context, lsize, "Integer");
if cast_data.value_type.is_signed_int() {
cast_data.llvm.builder.build_int_s_extend_or_bit_cast(self, llvm_int_type, "")
} else {
cast_data.llvm.builder.build_int_z_extend_or_bit_cast(self, llvm_int_type, "")
}
.into()
}
}
impl<'ctx, 'cast> Promotable<'ctx, 'cast> for FloatValue<'ctx> {
fn promote(self, lsize: u32, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
cast_data
.llvm
.builder
.build_float_ext(self, get_llvm_float_type(cast_data.llvm.context, lsize, "Float"), "")
.into()
}
}
impl<'ctx, 'cast> Truncatable<'ctx, 'cast> for IntValue<'ctx> {
fn truncate(self, lsize: u32, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
cast_data
.llvm
.builder
.build_int_truncate_or_bit_cast(
self,
get_llvm_int_type(cast_data.llvm.context, lsize, "Integer"),
"",
)
.into()
}
}
impl<'ctx, 'cast> Truncatable<'ctx, 'cast> for FloatValue<'ctx> {
fn truncate(self, lsize: u32, cast_data: &CastInstructionData<'ctx, 'cast>) -> BasicValueEnum<'ctx> {
cast_data
.llvm
.builder
.build_float_trunc(self, get_llvm_float_type(cast_data.llvm.context, lsize, "Float"), "")
.into()
}
}