-
Notifications
You must be signed in to change notification settings - Fork 48
/
expression_generator.rs
2748 lines (2539 loc) · 122 KB
/
expression_generator.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020 Ghaith Hachem and Mathias Rieder
use crate::{
codegen::{
debug::{Debug, DebugBuilderEnum},
llvm_index::LlvmTypedIndex,
llvm_typesystem::{cast_if_needed, get_llvm_int_type},
},
index::{
const_expressions::ConstId, ArgumentType, ImplementationIndexEntry, Index, PouIndexEntry,
VariableIndexEntry, VariableType,
},
resolver::{AnnotationMap, AstAnnotations, StatementAnnotation},
typesystem::{
is_same_type_class, DataType, DataTypeInformation, DataTypeInformationProvider, Dimension,
StringEncoding, VarArgs, DINT_TYPE, INT_SIZE, INT_TYPE, LINT_TYPE,
},
};
use inkwell::{
builder::Builder,
types::{BasicType, BasicTypeEnum},
values::{
ArrayValue, BasicMetadataValueEnum, BasicValue, BasicValueEnum, FloatValue, IntValue, PointerValue,
StructValue, VectorValue,
},
AddressSpace, FloatPredicate, IntPredicate,
};
use plc_ast::{
ast::{
flatten_expression_list, AstFactory, AstNode, AstStatement, DirectAccessType, Operator,
ReferenceAccess, ReferenceExpr,
},
literals::AstLiteral,
};
use plc_diagnostics::diagnostics::{Diagnostic, INTERNAL_LLVM_ERROR};
use plc_source::source_location::SourceLocation;
use plc_util::convention::qualified_name;
use std::{collections::HashSet, vec};
use super::{llvm::Llvm, statement_generator::FunctionContext, ADDRESS_SPACE_CONST, ADDRESS_SPACE_GENERIC};
/// the generator for expressions
pub struct ExpressionCodeGenerator<'a, 'b> {
pub llvm: &'b Llvm<'a>,
pub index: &'b Index,
pub(crate) annotations: &'b AstAnnotations,
pub llvm_index: &'b LlvmTypedIndex<'a>,
/// the current function to create blocks in
pub function_context: Option<&'b FunctionContext<'a, 'b>>,
/// The debug context used to create breakpoint information
pub debug: &'b DebugBuilderEnum<'a>,
/// the string-prefix to use for temporary variables
pub temp_variable_prefix: String,
/// the string-suffix to use for temporary variables
pub temp_variable_suffix: String,
// the function on how to obtain the the length to use for the string
string_len_provider: fn(type_length_declaration: usize, actual_length: usize) -> usize,
}
/// context information to generate a parameter
#[derive(Debug)]
struct CallParameterAssignment<'a, 'b> {
/// the assignmentstatement in the call-argument list (a:=3)
assignment_statement: &'b AstNode,
/// the name of the function we're calling
function_name: &'b str,
/// the position of the argument in the POU's argument's list
index: u32,
/// a pointer to the struct instance that carries the call's arguments
parameter_struct: PointerValue<'a>,
}
#[derive(Debug)]
pub enum ExpressionValue<'ink> {
/// A Locator-Value
/// An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).
LValue(PointerValue<'ink>),
/// An expression that does not represent an object occupying some identifiable location in memory.
RValue(BasicValueEnum<'ink>),
}
impl<'ink> ExpressionValue<'ink> {
/// returns the value represented by this ExpressionValue
pub fn get_basic_value_enum(&self) -> BasicValueEnum<'ink> {
match self {
ExpressionValue::LValue(it) => it.as_basic_value_enum(),
ExpressionValue::RValue(it) => it.to_owned(),
}
}
/// returns the given expression value as an r-value which means that it will load
/// the pointer, if this is an l_value
pub fn as_r_value(&self, llvm: &Llvm<'ink>, load_name: Option<String>) -> BasicValueEnum<'ink> {
match self {
ExpressionValue::LValue(it) => llvm.load_pointer(it, load_name.as_deref().unwrap_or("")),
ExpressionValue::RValue(it) => it.to_owned(),
}
}
}
impl<'ink, 'b> ExpressionCodeGenerator<'ink, 'b> {
/// creates a new expression generator
///
/// - `llvm` dependencies used to generate llvm IR
/// - `index` the index / global symbol table
/// - `type_hint` an optional type hint for generating literals
/// - `function_context` the current function to create blocks
pub fn new(
llvm: &'b Llvm<'ink>,
index: &'b Index,
annotations: &'b AstAnnotations,
llvm_index: &'b LlvmTypedIndex<'ink>,
function_context: &'b FunctionContext<'ink, 'b>,
debug: &'b DebugBuilderEnum<'ink>,
) -> ExpressionCodeGenerator<'ink, 'b> {
ExpressionCodeGenerator {
llvm,
index,
llvm_index,
annotations,
function_context: Some(function_context),
debug,
temp_variable_prefix: "load_".to_string(),
temp_variable_suffix: "".to_string(),
string_len_provider: |_, actual_length| actual_length, //when generating string-literals in a body, use the actual length
}
}
/// creates a new expression generator without a function context
/// this expression generator cannot generate all expressions. It can only generate
/// expressions that need no blocks (e.g. literals, references, etc.)
///
/// - `llvm` dependencies used to generate llvm IR
/// - `index` the index / global symbol table
/// - `type_hint` an optional type hint for generating literals
pub fn new_context_free(
llvm: &'b Llvm<'ink>,
index: &'b Index,
annotations: &'b AstAnnotations,
llvm_index: &'b LlvmTypedIndex<'ink>,
) -> ExpressionCodeGenerator<'ink, 'b> {
ExpressionCodeGenerator {
llvm,
index,
llvm_index,
annotations,
function_context: None,
debug: &DebugBuilderEnum::None,
temp_variable_prefix: "load_".to_string(),
temp_variable_suffix: "".to_string(),
string_len_provider: |type_length_declaration, _| type_length_declaration, //when generating string-literals in declarations, use the declared length
}
}
/// returns the function context or returns a Compile-Error
pub fn get_function_context(
&self,
statement: &AstNode,
) -> Result<&'b FunctionContext<'ink, 'b>, Diagnostic> {
self.function_context.ok_or_else(|| Diagnostic::missing_function(statement.get_location()))
}
/// entry point into the expression generator.
/// generates the given expression and returns the resulting BasicValueEnum
pub fn generate_expression(&self, expression: &AstNode) -> Result<BasicValueEnum<'ink>, Diagnostic> {
// If the expression was replaced by the resolver, generate the replacement
if let Some(StatementAnnotation::ReplacementAst { statement }) = self.annotations.get(expression) {
// we trust that the validator only passed us valid parameters (so left & right should be same type)
return self.generate_expression(statement);
}
let v = self
.generate_expression_value(expression)?
.as_r_value(self.llvm, self.get_load_name(expression))
.as_basic_value_enum();
let Some(target_type) = self.annotations.get_type_hint(expression, self.index) else {
// no type-hint -> we can return the value as is
return Ok(v);
};
let actual_type = self.annotations.get_type_or_void(expression, self.index);
Ok(cast_if_needed!(self, target_type, actual_type, v, self.annotations.get(expression)))
}
fn register_debug_location(&self, statement: &AstNode) {
let function_context =
self.function_context.expect("Cannot generate debug info without function context");
let line = statement.get_location().get_line_plus_one();
let column = statement.get_location().get_column();
self.debug.set_debug_location(self.llvm, &function_context.function, line, column);
}
pub fn generate_expression_value(
&self,
expression: &AstNode,
) -> Result<ExpressionValue<'ink>, Diagnostic> {
//see if this is a constant - maybe we can short curcuit this codegen
if let Some(StatementAnnotation::Variable {
qualified_name, constant: true, resulting_type, ..
}) = self.annotations.get(expression)
{
if !self.index.get_type_information_or_void(resulting_type).is_aggregate() {
match self.generate_constant_expression(qualified_name, expression) {
// We return here if constant propagation worked
Ok(expr) => return Ok(expr),
// ...and fall-back to generating the expression further down if it didn't
Err(why) => log::info!("{why}"),
}
}
}
// generate the expression
match expression.get_stmt() {
AstStatement::ReferenceExpr(data) => {
let res =
self.generate_reference_expression(&data.access, data.base.as_deref(), expression)?;
let val = match res {
ExpressionValue::LValue(val) => {
ExpressionValue::LValue(self.auto_deref_if_necessary(val, expression))
}
ExpressionValue::RValue(val) => {
let val = if val.is_pointer_value() {
self.auto_deref_if_necessary(val.into_pointer_value(), expression)
.as_basic_value_enum()
} else {
val
};
ExpressionValue::RValue(val)
}
};
Ok(val)
}
AstStatement::BinaryExpression(data) => self
.generate_binary_expression(&data.left, &data.right, &data.operator, expression)
.map(ExpressionValue::RValue),
AstStatement::CallStatement(data) => {
self.generate_call_statement(&data.operator, data.parameters.as_deref())
}
AstStatement::UnaryExpression(data) => {
self.generate_unary_expression(&data.operator, &data.value).map(ExpressionValue::RValue)
}
// TODO: Hardware access needs to be evaluated, see #648
AstStatement::HardwareAccess { .. } => {
Ok(ExpressionValue::RValue(self.llvm.i32_type().const_zero().into()))
}
AstStatement::ParenExpression(expr) => self.generate_expression_value(expr),
//fallback
_ => self.generate_literal(expression),
}
}
/// Propagate the constant value of the constant reference to `qualified_name`.
/// - `qualified _name` the qualified name of the referenced constant variable we want to propagate
/// - `expression` the original expression
fn generate_constant_expression(
&self,
qualified_name: &str,
expression: &AstNode,
) -> Result<ExpressionValue<'ink>, Diagnostic> {
let const_expression = self
.index
// try to find a constant variable
.find_variable(None, &qualified_name.split('.').collect::<Vec<_>>())
// or else try to find an enum element
.or_else(|| self.index.find_qualified_enum_element(qualified_name))
// if this is no constant we have a problem
.filter(|v| v.is_constant())
.and_then(|v| v.initial_value)
// fetch the constant's initial value fron the const-expressions arena
.and_then(|constant_variable| {
self.index.get_const_expressions().get_resolved_constant_statement(&constant_variable)
})
.ok_or_else(|| {
// We'll _probably_ land here because we're dealing with aggregate types, see also
// https://github.com/PLC-lang/rusty/issues/288
let message = format!("Cannot propagate constant value for '{qualified_name:}'");
Diagnostic::codegen_error(message, expression.get_location())
})?;
// generate the resulting constant-expression (which should be a Value, no ptr-reference)
self.generate_expression_value(const_expression)
}
/// generates a binary expression (e.g. a + b, x AND y, etc.) and returns the resulting `BasicValueEnum`
/// - `left` the AstStatement left of the operator
/// - `right` the AstStatement right of the operator
/// - `operator` the binary expression's operator
/// - `expression` the whole expression for diagnostic reasons
fn generate_binary_expression(
&self,
left: &AstNode,
right: &AstNode,
operator: &Operator,
expression: &AstNode,
) -> Result<BasicValueEnum<'ink>, Diagnostic> {
let l_type_hint = self.get_type_hint_for(left)?;
let ltype = self.index.get_intrinsic_type_by_name(l_type_hint.get_name()).get_type_information();
let r_type_hint = self.get_type_hint_for(right)?;
let rtype = self.index.get_intrinsic_type_by_name(r_type_hint.get_name()).get_type_information();
if ltype.is_bool() && rtype.is_bool() {
return self.generate_bool_binary_expression(operator, left, right);
}
if ltype.is_int() && rtype.is_int() {
Ok(self.create_llvm_int_binary_expression(
operator,
self.generate_expression(left)?,
self.generate_expression(right)?,
))
} else if ltype.is_float() && rtype.is_float() {
Ok(self.create_llvm_float_binary_expression(
operator,
self.generate_expression(left)?,
self.generate_expression(right)?,
))
} else if (ltype.is_pointer() && rtype.is_int())
|| (ltype.is_int() && rtype.is_pointer())
|| (ltype.is_pointer() && rtype.is_pointer())
{
self.create_llvm_binary_expression_for_pointer(operator, left, ltype, right, rtype, expression)
} else {
self.create_llvm_generic_binary_expression(left, right, expression)
}
}
pub fn generate_direct_access_index(
&self,
access: &DirectAccessType,
index: &AstNode,
access_type: &DataTypeInformation,
target_type: &DataType,
) -> Result<IntValue<'ink>, Diagnostic> {
let reference = self.generate_expression(index)?;
//Load the reference
if reference.is_int_value() {
//This cast is needed to convert the index/reference to the type of original expression
//being accessed.
//The reason is that llvm expects a shift operation to happen on the same type, and
//this is what the direct access will eventually end up in.
let reference =
cast_if_needed!(self, target_type, self.get_type_hint_for(index)?, reference, None)
.into_int_value();
//Multiply by the bitwitdh
if access.get_bit_width() > 1 {
let bitwidth =
reference.get_type().const_int(access.get_bit_width(), access_type.is_signed_int());
Ok(self.llvm.builder.build_int_mul(reference, bitwidth, ""))
} else {
Ok(reference)
}
} else {
Err(Diagnostic::new(format!("Cannot cast from {} to Integer Type", access_type.get_name()))
.with_error_code("E051")
.with_location(index.get_location()))
}
}
/// generates a Unary-Expression e.g. -<expr> or !<expr>
fn generate_unary_expression(
&self,
unary_operator: &Operator,
expression: &AstNode,
) -> Result<BasicValueEnum<'ink>, Diagnostic> {
let value = match unary_operator {
Operator::Not => {
let operator = self.generate_expression(expression)?.into_int_value();
let operator = if self
.get_type_hint_for(expression)
.map(|it| it.get_type_information().is_bool())
.unwrap_or_default()
{
to_i1(operator, &self.llvm.builder)
} else {
operator
};
Ok(self.llvm.builder.build_not(operator, "tmpVar").as_basic_value_enum())
}
Operator::Minus => {
let generated_exp = self.generate_expression(expression)?;
if generated_exp.is_float_value() {
Ok(self
.llvm
.builder
.build_float_neg(generated_exp.into_float_value(), "tmpVar")
.as_basic_value_enum())
} else if generated_exp.is_int_value() {
Ok(self
.llvm
.builder
.build_int_neg(generated_exp.into_int_value(), "tmpVar")
.as_basic_value_enum())
} else {
Err(Diagnostic::codegen_error(
"Negated expression must be numeric",
expression.get_location(),
))
}
}
_ => unimplemented!(),
};
value
}
/// generates the given call-statement <operator>(<parameters>)
/// returns the call's result as a BasicValueEnum (may be a void-type for PROGRAMs)
///
/// - `operator` - the expression that points to the callable instance (e.g. a PROGRAM, FUNCTION or FUNCTION_BLOCK instance)
/// - `parameters` - an optional StatementList of parameters
pub fn generate_call_statement(
&self,
operator: &AstNode,
parameters: Option<&AstNode>,
) -> Result<ExpressionValue<'ink>, Diagnostic> {
// find the pou we're calling
let pou = self.annotations.get_call_name(operator).zip(self.annotations.get_qualified_name(operator))
.and_then(|(call_name, qualified_name)| self.index.find_pou(call_name)
// for some functions (builtins) the call name does not exist in the index, we try to call with the originally defined generic functions
.or_else(|| self.index.find_pou(qualified_name)))
.or_else(||
// some rare situations have a callstatement that's not properly annotated (e.g. checkRange-call of ranged datatypes)
if let Some(name) = operator.get_flat_reference_name() {
self.index.find_pou(name)
} else {
None
})
.ok_or_else(|| Diagnostic::cannot_generate_call_statement(operator))?;
// find corresponding implementation
let implementation = pou
.find_implementation(self.index)
.ok_or_else(|| Diagnostic::cannot_generate_call_statement(operator))?;
let parameters_list = parameters.map(flatten_expression_list).unwrap_or_default();
let implementation_name = implementation.get_call_name();
// if the function is builtin, generate a basic value enum for it
if let Some(builtin) = self.index.get_builtin_function(implementation_name) {
// adr, ref, etc.
return builtin.codegen(self, parameters_list.as_slice(), operator.get_location());
}
let mut arguments_list = self.generate_pou_call_arguments_list(
pou,
parameters_list.as_slice(),
implementation,
operator,
self.get_function_context(operator)?,
)?;
let function = self
.llvm_index
.find_associated_implementation(implementation_name) // using the non error option to control the output error
.ok_or_else(|| {
Diagnostic::codegen_error(
format!("No callable implementation associated to {implementation_name:?}"),
operator.get_location(),
)
})?;
// generate the debug statetment for a call
self.register_debug_location(operator);
// if this is a function that returns an aggregate type we need to allocate an out.pointer
let by_ref_func_out: Option<PointerValue> = if let PouIndexEntry::Function { return_type, .. } = pou {
let data_type = self.index.get_effective_type_or_void_by_name(return_type);
if data_type.is_aggregate_type() {
// this is a function call with a return variable fed as an out-pointer
let llvm_type = self.llvm_index.get_associated_type(data_type.get_name())?;
let out_pointer = self.llvm.create_local_variable("", &llvm_type);
// add the out-ptr as its first parameter
arguments_list.insert(0, out_pointer.into());
Some(out_pointer)
} else {
None
}
} else {
None
};
// if the target is a function, declare the struct locally
// assign all parameters into the struct values
let call = &self.llvm.builder.build_call(function, &arguments_list, "call");
// so grab either:
// - the out-pointer if we generated one in by_ref_func_out
// - or the call's return value
// - or a null-ptr
let value = by_ref_func_out.map(|it| Ok(ExpressionValue::LValue(it))).unwrap_or_else(|| {
let v = call.try_as_basic_value().either(Ok, |_| {
// we return an uninitialized int pointer for void methods :-/
// dont deref it!!
Ok(get_llvm_int_type(self.llvm.context, INT_SIZE, INT_TYPE)
.ptr_type(AddressSpace::from(ADDRESS_SPACE_CONST))
.const_null()
.as_basic_value_enum())
});
v.map(ExpressionValue::RValue)
});
// after the call we need to copy the values for assigned outputs
// this is only necessary for outputs defined as `rusty::index::ArgumentType::ByVal` (PROGRAM, FUNCTION_BLOCK)
// FUNCTION outputs are defined as `rusty::index::ArgumentType::ByRef`
if !pou.is_function() {
let parameter_struct = match arguments_list.first() {
Some(v) => v.into_pointer_value(),
None => self.generate_lvalue(operator)?,
};
self.assign_output_values(parameter_struct, implementation_name, parameters_list)?
}
value
}
/// copies the output values to the assigned output variables
/// - `parameter_struct` a pointer to a struct-instance that holds all function-parameters
/// - `function_name` the name of the callable
/// - `parameters` vec of passed parameters to the call
fn assign_output_values(
&self,
parameter_struct: PointerValue<'ink>,
function_name: &str,
parameters: Vec<&AstNode>,
) -> Result<(), Diagnostic> {
for (index, assignment_statement) in parameters.into_iter().enumerate() {
self.assign_output_value(&CallParameterAssignment {
assignment_statement,
function_name,
index: index as u32,
parameter_struct,
})?
}
Ok(())
}
fn assign_output_value(&self, param_context: &CallParameterAssignment) -> Result<(), Diagnostic> {
match param_context.assignment_statement.get_stmt() {
AstStatement::OutputAssignment(data) | AstStatement::Assignment(data) => self
.generate_explicit_output_assignment(
param_context.parameter_struct,
param_context.function_name,
&data.left,
&data.right,
),
_ => self.generate_output_assignment(param_context),
}
}
fn generate_output_assignment(&self, param_context: &CallParameterAssignment) -> Result<(), Diagnostic> {
let builder = &self.llvm.builder;
let expression = param_context.assignment_statement;
let parameter_struct = param_context.parameter_struct;
let function_name = param_context.function_name;
let index = param_context.index;
if let Some(parameter) = self.index.get_declared_parameter(function_name, index) {
if matches!(parameter.get_variable_type(), VariableType::Output)
&& !matches!(expression.get_stmt(), AstStatement::EmptyStatement { .. })
{
{
let assigned_output = self.generate_lvalue(expression)?;
let assigned_output_type =
self.annotations.get_type_or_void(expression, self.index).get_type_information();
let output = builder.build_struct_gep(parameter_struct, index, "").map_err(|_| {
Diagnostic::codegen_error(
format!("Cannot build generate parameter: {parameter:#?}"),
parameter.source_location.clone(),
)
})?;
let output_value_type =
self.index.get_type_information_or_void(parameter.get_type_name());
//Special string handling
if (assigned_output_type.is_string() && output_value_type.is_string())
|| (assigned_output_type.is_struct() && output_value_type.is_struct())
|| (assigned_output_type.is_array() && output_value_type.is_array())
{
self.generate_string_store(
assigned_output,
assigned_output_type,
expression.get_location(),
output,
output_value_type,
parameter.source_location.clone(),
)?;
} else {
let output_value = builder.build_load(output, "");
builder.build_store(assigned_output, output_value);
}
}
}
}
Ok(())
}
fn generate_explicit_output_assignment(
&self,
parameter_struct: PointerValue<'ink>,
function_name: &str,
left: &AstNode,
right: &AstNode,
) -> Result<(), Diagnostic> {
if let Some(StatementAnnotation::Variable { qualified_name, .. }) = self.annotations.get(left) {
let parameter = self
.index
.find_fully_qualified_variable(qualified_name)
.ok_or_else(|| Diagnostic::unresolved_reference(qualified_name, left.get_location()))?;
let index = parameter.get_location_in_parent();
self.assign_output_value(&CallParameterAssignment {
assignment_statement: right,
function_name,
index,
parameter_struct,
})?
};
Ok(())
}
/// generates the argument list for a call to a pou
/// a call to a function returns a Vec with all parameters for the function,
/// a call to a Program/Fb will return a Vec with a single struct carrying all parameters
fn generate_pou_call_arguments_list(
&self,
pou: &PouIndexEntry,
passed_parameters: &[&AstNode],
implementation: &ImplementationIndexEntry,
operator: &AstNode,
function_context: &'b FunctionContext<'ink, 'b>,
) -> Result<Vec<BasicMetadataValueEnum<'ink>>, Diagnostic> {
let arguments_list = if matches!(pou, PouIndexEntry::Function { .. }) {
// we're calling a function
let declared_parameters = self.index.get_declared_parameters(implementation.get_type_name());
self.generate_function_arguments(pou, passed_parameters, declared_parameters)?
} else {
// no function
let (class_ptr, call_ptr) = match pou {
PouIndexEntry::Method { .. } => {
let class_ptr = self.generate_lvalue(operator)?;
let call_ptr =
self.allocate_function_struct_instance(implementation.get_call_name(), operator)?;
(Some(class_ptr), call_ptr)
}
// TODO: find a more reliable way to make sure if this is a call into a local action!!
PouIndexEntry::Action { .. }
if matches!(
operator.get_stmt(),
AstStatement::ReferenceExpr(ReferenceExpr { base: None, .. })
) =>
{
// special handling for local actions, get the parameter from the function context
function_context
.function
.get_first_param()
.map(|call_ptr| (None, call_ptr.into_pointer_value()))
.ok_or_else(|| Diagnostic::cannot_generate_call_statement(operator))?
}
_ => {
let call_ptr = self.generate_lvalue(operator)?;
(None, call_ptr)
}
};
// generate the pou call assignments
self.generate_stateful_pou_arguments(
implementation.get_call_name(),
class_ptr,
call_ptr,
passed_parameters,
)?
};
Ok(arguments_list)
}
fn generate_function_arguments(
&self,
pou: &PouIndexEntry,
passed_parameters: &[&AstNode],
declared_parameters: Vec<&VariableIndexEntry>,
) -> Result<Vec<BasicMetadataValueEnum<'ink>>, Diagnostic> {
let mut result = Vec::new();
let mut variadic_parameters = Vec::new();
let mut passed_param_indices = Vec::new();
for (i, parameter) in passed_parameters.iter().enumerate() {
let (i, parameter, _) = get_implicit_call_parameter(parameter, &declared_parameters, i)?;
// parameter_info includes the declaration type and type name
let parameter_info = declared_parameters
.get(i)
.map(|it| {
let name = it.get_type_name();
if let Some(DataTypeInformation::Pointer { inner_type_name, auto_deref: true, .. }) =
self.index.find_effective_type_info(name)
{
// for auto_deref pointers (VAR_INPUT {ref}, VAR_IN_OUT) we call generate_argument_by_ref()
// we need the inner_type and not pointer to type otherwise we would generate a double pointer
Some((it.get_declaration_type(), inner_type_name.as_str()))
} else {
Some((it.get_declaration_type(), name))
}
})
// TODO : Is this idomatic, we need to wrap in ok because the next step does not necessarily fail
.map(Ok)
// None -> possibly variadic
.unwrap_or_else(|| {
// if we are dealing with a variadic function, we can accept all extra parameters
if pou.is_variadic() {
variadic_parameters.push(parameter);
Ok(None)
} else {
// we are not variadic, we have too many parameters here
Err(Diagnostic::codegen_error("Too many parameters", parameter.get_location()))
}
})?;
if let Some((declaration_type, type_name)) = parameter_info {
let argument: BasicValueEnum = if declaration_type.is_by_ref() {
let declared_parameter = declared_parameters.get(i);
self.generate_argument_by_ref(parameter, type_name, declared_parameter.copied())?
} else {
// by val
if !parameter.is_empty_statement() {
self.generate_argument_by_val(type_name, parameter)?
} else if let Some(param) = declared_parameters.get(i) {
self.generate_empty_expression(param)?
} else {
unreachable!("Statement param must have an index entry at this point.");
}
};
result.push((i, argument));
}
passed_param_indices.push(i);
}
// handle missing parameters, generate empty expression
if declared_parameters.len() > passed_param_indices.len() {
for (i, param) in declared_parameters.into_iter().enumerate() {
if !passed_param_indices.contains(&i) {
let generated_exp = self.generate_empty_expression(param)?;
result.push((i, generated_exp));
}
}
}
// push variadic collection and optionally the variadic size
if pou.is_variadic() {
let last_location = result.len();
for (i, parameter) in
self.generate_variadic_arguments_list(pou, &variadic_parameters)?.into_iter().enumerate()
{
result.push((i + last_location, parameter));
}
}
result.sort_by(|(idx_a, _), (idx_b, _)| idx_a.cmp(idx_b));
Ok(result.into_iter().map(|(_, v)| v.into()).collect::<Vec<BasicMetadataValueEnum>>())
}
fn generate_argument_by_val(
&self,
type_name: &str,
param_statement: &AstNode,
) -> Result<BasicValueEnum<'ink>, Diagnostic> {
let Some(type_info) = self.index.find_effective_type_by_name(type_name) else {
return self.generate_expression(param_statement);
};
if type_info.is_string() {
return self.generate_string_argument(type_info, param_statement);
}
// https://github.com/PLC-lang/rusty/issues/1037:
// This if-statement covers the case where we want to convert a pointer into its actual
// type, e.g. if an argument is passed into a function A by-ref (INOUT) which in turn is
// passed into another function B by-val (INPUT) then the pointer argument in function A has
// to be bit-cast into its actual type before passing it into function B.
if type_info.is_aggregate_type() && !type_info.is_vla() {
let deref = self.generate_expression_value(param_statement)?;
if deref.get_basic_value_enum().is_pointer_value() {
let ty = self.llvm_index.get_associated_type(type_name)?;
let cast = self.llvm.builder.build_bitcast(
deref.get_basic_value_enum(),
ty.ptr_type(AddressSpace::from(ADDRESS_SPACE_GENERIC)),
"",
);
let load = self.llvm.builder.build_load(
cast.into_pointer_value(),
&self.get_load_name(param_statement).unwrap_or_default(),
);
if let Some(target_ty) = self.annotations.get_type_hint(param_statement, self.index) {
let actual_ty = self.annotations.get_type_or_void(param_statement, self.index);
let annotation = self.annotations.get(param_statement);
return Ok(cast_if_needed!(self, target_ty, actual_ty, load, annotation));
}
return Ok(load);
}
}
// Fallback
self.generate_expression(param_statement)
}
/// Before passing a string to a function, it is copied to a new string with the
/// appropriate size for the called function
fn generate_string_argument(
&self,
type_info: &DataType,
argument: &AstNode,
) -> Result<BasicValueEnum<'ink>, Diagnostic> {
// allocate a temporary string of correct size and pass it
let llvm_type = self
.llvm_index
.find_associated_type(type_info.get_name())
.ok_or_else(|| Diagnostic::unknown_type(type_info.get_name(), argument.get_location()))?;
let temp_variable = self.llvm.builder.build_alloca(llvm_type, "");
self.llvm
.builder
.build_memset(
temp_variable,
1,
self.llvm.context.i8_type().const_zero(),
llvm_type
.size_of()
.ok_or_else(|| Diagnostic::unknown_type(type_info.get_name(), argument.get_location()))?,
)
.map_err(|it| Diagnostic::codegen_error(it, argument.get_location()))?;
self.generate_store(temp_variable, type_info.get_type_information(), argument)?;
Ok(self.llvm.builder.build_load(temp_variable, ""))
}
/// generates a value that is passed by reference
/// this generates and returns a PointerValue
/// pointing to the given `argument`
fn generate_argument_by_ref(
&self,
argument: &AstNode,
type_name: &str,
declared_parameter: Option<&VariableIndexEntry>,
) -> Result<BasicValueEnum<'ink>, Diagnostic> {
if argument.is_empty_statement() {
// Uninitialized var_output / var_in_out
let v_type = self
.llvm_index
.find_associated_type(type_name)
.ok_or_else(|| Diagnostic::unknown_type(type_name, argument.get_location()))?;
let ptr_value = self.llvm.builder.build_alloca(v_type, "");
if let Some(p) = declared_parameter {
if let Some(initial_value) =
self.get_initial_value(&p.initial_value, &self.get_parameter_type(p))
{
let value = self.generate_expression(initial_value)?;
self.llvm.builder.build_store(ptr_value, value);
}
}
return Ok(ptr_value.into());
}
// Generate the element pointer, then...
let value = {
let value = self.generate_expression_value(argument)?;
match value {
ExpressionValue::LValue(v) => v,
ExpressionValue::RValue(_v) => {
// Passed a literal to a byref parameter?
let value = self.generate_expression(argument)?;
let argument = self.llvm.builder.build_alloca(value.get_type(), "");
self.llvm.builder.build_store(argument, value);
argument
}
}
};
// ...check if we can bitcast a reference to their hinted type
if let Some(hint) = self.annotations.get_type_hint(argument, self.index) {
let actual_type = self.annotations.get_type_or_void(argument, self.index);
let actual_type_info = self.index.find_elementary_pointer_type(&actual_type.information);
let target_type_info = self.index.find_elementary_pointer_type(&hint.information);
if target_type_info.is_vla() {
// XXX: Calling `cast_if_needed` will result in an `alloca` call for EVERY function call.
// LLVM might be able to optimize it away but ideally we find a solution for this at some
// point? For a more in-depth description see the `pass` function in `vla_adr.rs`
return Ok(cast_if_needed!(
self,
hint,
actual_type,
value.into(),
self.annotations.get(argument)
));
};
// From https://llvm.org/docs/LangRef.html#bitcast-to-instruction: The ‘bitcast’ instruction takes
// a value to cast, which must be a **non-aggregate** first class value [...]
if !actual_type_info.is_aggregate() && actual_type_info != target_type_info {
return Ok(self.llvm.builder.build_bitcast(
value,
self.llvm_index.get_associated_type(hint.get_name())?,
"",
));
}
}
// ...check if we can bitcast an array to a pointer, i.e. `[81 x i8]*` should be passed as a `i8*`
if value.get_type().get_element_type().is_array_type() {
let res = self.llvm.builder.build_bitcast(
value,
value
.get_type()
.get_element_type()
.into_array_type()
.get_element_type()
.ptr_type(AddressSpace::from(ADDRESS_SPACE_GENERIC)),
"",
);
return Ok(res.into_pointer_value().into());
}
// ...otherwise no bitcasting was needed, thus return the generated element pointer as is
Ok(value.into())
}
pub fn generate_variadic_arguments_list(
&self,
pou: &PouIndexEntry,
variadic_params: &[&AstNode],
) -> Result<Vec<BasicValueEnum<'ink>>, Diagnostic> {
// get the real varargs from the index
if let Some((var_args, argument_type)) = self
.index
.get_variadic_member(pou.get_name())
.and_then(|it| it.get_varargs().zip(Some(it.get_declaration_type())))
{
let generated_params = variadic_params
.iter()
.map(|param_statement| {
self.get_type_hint_for(param_statement).map(|it| it.get_name()).and_then(|type_name| {
// if the variadic is defined in a by_ref block, we need to pass the argument as reference
if argument_type.is_by_ref() {
self.generate_argument_by_ref(
param_statement,
type_name,
self.index.get_variadic_member(pou.get_name()),
)
} else {
self.generate_argument_by_val(type_name, param_statement)
}
})
})
.collect::<Result<Vec<_>, _>>()?;
// for sized variadics we create an array and store all the arguments in that array
if let VarArgs::Sized(Some(type_name)) = var_args {
let ty = self.llvm_index.get_associated_type(type_name).map(|it| {
if argument_type.is_by_ref() && it.is_array_type() {
it.into_array_type().get_element_type()
} else {
it
}
})?;
// if the variadic argument is ByRef, wrap it in a pointer.
let ty = if argument_type.is_by_ref() {
ty.ptr_type(AddressSpace::from(ADDRESS_SPACE_GENERIC)).into()
} else {
ty
};
let size = generated_params.len();
let size_param = self.llvm.i32_type().const_int(size as u64, true);
let arr = ty.array_type(size as u32);
let arr_storage = self.llvm.builder.build_alloca(arr, "");
for (i, ele) in generated_params.iter().enumerate() {
let ele_ptr = self.llvm.load_array_element(
arr_storage,
&[
self.llvm.context.i32_type().const_zero(),
self.llvm.context.i32_type().const_int(i as u64, true),
],
"",
)?;
self.llvm.builder.build_store(ele_ptr, *ele);
}
// bitcast the array to pointer so it matches the declared function signature
let arr_storage = self.llvm.builder.build_bitcast(
arr_storage,
ty.ptr_type(AddressSpace::from(ADDRESS_SPACE_GENERIC)),
"",
);
Ok(vec![size_param.into(), arr_storage])