-
Notifications
You must be signed in to change notification settings - Fork 297
/
NFSimplifyExp.mo
1669 lines (1463 loc) · 53.5 KB
/
NFSimplifyExp.mo
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
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package NFSimplifyExp
import Expression = NFExpression;
import Operator = NFOperator;
import Type = NFType;
import Call = NFCall;
import Subscript = NFSubscript;
import NFOperator.Op;
import NFPrefixes.{Variability, Purity};
import NFInstNode.InstNode;
protected
import Dimension = NFDimension;
import Ceval = NFCeval;
import NFCeval.EvalTarget;
import NFFunction.Function;
import ComponentRef = NFComponentRef;
import ExpandExp = NFExpandExp;
import TypeCheck = NFTypeCheck;
import Absyn;
import AbsynUtil;
import ErrorExt;
import Flags;
import Debug;
import Array;
import MetaModelica.Dangerous.listReverseInPlace;
public
function simplifyDump
"wrapper function for simplification to allow dumping before and afterwards"
input Expression exp;
input Boolean includeScope;
output Expression res;
input String name = "";
input String indent = "";
algorithm
res := simplify(exp, includeScope);
if Flags.isSet(Flags.DUMP_SIMPLIFY) and not Expression.isEqual(exp, res) then
print(indent + "### dumpSimplify | " + name + " ###\n");
print(indent + "[BEFORE] " + Expression.toString(exp) + "\n");
print(indent + "[AFTER ] " + Expression.toString(res) + "\n\n");
end if;
end simplifyDump;
function simplify
input output Expression exp;
input Boolean includeScope = false;
algorithm
exp := match exp
case Expression.CREF()
algorithm
exp.cref := ComponentRef.simplifySubscripts(exp.cref);
exp.ty := ComponentRef.getSubscriptedType(exp.cref, includeScope);
then
exp;
case Expression.ARRAY()
guard not exp.literal
algorithm
exp.elements := Array.map(exp.elements, function simplify(includeScope = false));
then
exp;
case Expression.RANGE()
then simplifyRange(exp);
case Expression.RECORD()
algorithm
exp.elements := list(simplify(e) for e in exp.elements);
then
exp;
case Expression.CALL() then simplifyCall(exp);
case Expression.SIZE() then simplifySize(exp);
case Expression.MULTARY() then simplifyMultary(exp);
case Expression.BINARY() then simplifyBinary(exp);
case Expression.UNARY() then simplifyUnary(exp);
case Expression.LBINARY() then simplifyLogicBinary(exp);
case Expression.LUNARY() then simplifyLogicUnary(exp);
case Expression.RELATION() then simplifyRelation(exp);
case Expression.IF() then simplifyIf(exp);
case Expression.CAST() then simplifyCast(simplify(exp.exp), exp.ty);
case Expression.UNBOX() then Expression.UNBOX(simplify(exp.exp), exp.ty);
case Expression.SUBSCRIPTED_EXP() then simplifySubscriptedExp(exp);
case Expression.TUPLE_ELEMENT() then simplifyTupleElement(exp);
case Expression.RECORD_ELEMENT() then simplifyRecordElement(exp);
case Expression.BOX() then Expression.BOX(simplify(exp.exp));
case Expression.MUTABLE() then simplify(Mutable.access(exp.exp));
else exp;
end match;
end simplify;
function simplifyOpt
input output Option<Expression> exp;
protected
Expression e;
algorithm
exp := match exp
case SOME(e) then SOME(simplify(e));
else exp;
end match;
end simplifyOpt;
function simplifyRange
input Expression range;
output Expression exp;
protected
Expression start_exp1, stop_exp1, start_exp2, stop_exp2;
Option<Expression> step_exp1, step_exp2;
Type ty, ty2;
algorithm
Expression.RANGE(ty = ty, start = start_exp1, step = step_exp1, stop = stop_exp1) := range;
start_exp2 := simplify(start_exp1);
step_exp2 := simplifyOpt(step_exp1);
stop_exp2 := simplify(stop_exp1);
ty2 := Type.simplify(ty);
if referenceEq(start_exp1, start_exp2) and
referenceEq(step_exp1, step_exp2) and
referenceEq(stop_exp1, stop_exp2) and
referenceEq(ty, ty2) then
exp := range;
else
ty := TypeCheck.getRangeType(start_exp2, step_exp2, stop_exp2,
Type.arrayElementType(ty), AbsynUtil.dummyInfo);
exp := Expression.RANGE(ty, start_exp2, step_exp2, stop_exp2);
end if;
end simplifyRange;
function simplifyCall
input output Expression callExp;
protected
Call call;
list<Expression> args;
Boolean builtin, is_pure, scalarize;
algorithm
Expression.CALL(call = call) := callExp;
callExp := match call
case Call.TYPED_CALL(arguments = args) guard not Call.isExternal(call)
algorithm
if Flags.isSet(Flags.NF_EXPAND_FUNC_ARGS) then
args := list(if Expression.hasArrayCall(arg) then arg else ExpandExp.expand(arg) for arg in args);
end if;
args := list(simplify(arg) for arg in args);
call.arguments := args;
builtin := Function.isBuiltin(call.fn);
is_pure := not Function.isImpure(call.fn);
// Use Ceval for builtin pure functions with literal arguments.
if builtin then
scalarize := Flags.isSet(Flags.NF_SCALARIZE);
if is_pure and List.all(args, Expression.isLiteral) and (scalarize or Type.isScalar(call.ty)) then
try
callExp := Ceval.evalCall(call, EvalTarget.IGNORE_ERRORS());
else
callExp := Expression.CALL(call);
end try;
else
callExp := simplifyBuiltinCall(Function.nameConsiderBuiltin(call.fn), args, call, expand = scalarize);
end if;
elseif Flags.isSet(Flags.NF_EVAL_CONST_ARG_FUNCS) and is_pure and List.all(args, Expression.isLiteral) then
callExp := simplifyCall2(call);
else
callExp := Expression.CALL(call);
end if;
then
callExp;
case Call.TYPED_CALL(arguments = args)
algorithm
args := list(simplify(arg) for arg in args);
call.arguments := args;
then
Expression.CALL(call);
case Call.TYPED_ARRAY_CONSTRUCTOR() then simplifyArrayConstructor(call);
case Call.TYPED_REDUCTION() then simplifyReduction(call);
else callExp;
end match;
end simplifyCall;
function simplifyCall2
input Call call;
output Expression outExp;
algorithm
ErrorExt.setCheckpoint(getInstanceName());
try
outExp := Ceval.evalCall(call, EvalTarget.IGNORE_ERRORS());
ErrorExt.delCheckpoint(getInstanceName());
else
if Flags.isSet(Flags.FAILTRACE) then
ErrorExt.delCheckpoint(getInstanceName());
Debug.traceln("- " + getInstanceName() + " failed to evaluate " + Call.toString(call) + "\n");
else
ErrorExt.rollBack(getInstanceName());
end if;
outExp := Expression.CALL(call);
end try;
end simplifyCall2;
function simplifyBuiltinCall
input Absyn.Path name;
input list<Expression> args;
input Call call;
input Boolean expand;
output Expression exp;
algorithm
exp := match AbsynUtil.pathFirstIdent(name)
case "cat"
algorithm
exp := ExpandExp.expandBuiltinCat(args, call);
then
exp;
case "delay" then simplifyDelay(args, call);
case "der" then simplifyDer(listHead(args), call);
case "fill" then simplifyFill(listHead(args), listRest(args), call, expand);
case "homotopy" then simplifyHomotopy(args, call);
case "max" then simplifyMinMax(args, call, isMin = false);
case "min" then simplifyMinMax(args, call, isMin = true);
case "ones" then simplifyFill(Expression.INTEGER(1), args, call, expand);
case "product" then simplifySumProduct(listHead(args), call, expand, isSum = false);
case "sum" then simplifySumProduct(listHead(args), call, expand, isSum = true);
case "transpose" then simplifyTranspose(listHead(args), call, expand);
case "vector" then simplifyVector(listHead(args), call);
case "zeros" then simplifyFill(Expression.INTEGER(0), args, call, expand);
case "semiLinear" then simplifySemiLinear(args, call);
case "getInstanceName" then Ceval.evalGetInstanceName(listHead(args));
else Expression.CALL(call);
end match;
end simplifyBuiltinCall;
function simplifySemiLinear
input list<Expression> args;
input Call call;
output Expression exp;
protected
Expression x, m1, m2;
Type ty;
algorithm
{x, m1, m2} := args;
ty := Expression.typeOf(x);
if Expression.isZero(x) or (Expression.isZero(m1) and Expression.isZero(m2)) then
// both slopes x*m1, x*m2 return 0
exp := Expression.makeZero(ty);
elseif Expression.isEqual(m1, m2) then
// both slopes x*m1, x*m2 are equal
exp := Expression.BINARY(x, Operator.makeMul(ty), m1);
else
// no simplification, just return
exp := Expression.CALL(call);
end if;
end simplifySemiLinear;
function simplifyMinMax
input list<Expression> args;
input Call call;
input Boolean isMin;
output Expression exp;
protected
Expression arg;
Type ty;
algorithm
if listLength(args) == 1 then
arg := listHead(args);
ty := Expression.typeOf(arg);
if Type.isEmptyArray(ty) then
ty := Type.arrayElementType(ty);
exp := if isMin then Expression.makeMaxValue(ty) else
Expression.makeMinValue(ty);
else
exp := simplifyReducedArrayConstructor(arg, call);
end if;
else
exp := Expression.CALL(call);
end if;
end simplifyMinMax;
function simplifySumProduct
input Expression arg;
input Call call;
input Boolean expand;
input Boolean isSum;
output Expression exp;
protected
Boolean expanded;
list<Expression> args;
Type ty;
Operator op;
algorithm
if expand then
(exp, expanded) := ExpandExp.expand(arg);
if expanded then
args := Expression.arrayScalarElements(exp);
ty := Type.arrayElementType(Expression.typeOf(arg));
if listEmpty(args) then
exp := if isSum then Expression.makeZero(ty) else Expression.makeOne(ty);
else
exp :: args := args;
op := if isSum then Operator.makeAdd(ty) else
Operator.makeMul(ty);
for e in args loop
exp := Expression.BINARY(exp, op, e);
end for;
end if;
return;
end if;
end if;
exp := simplifyReducedArrayConstructor(arg, call);
end simplifySumProduct;
function simplifyReducedArrayConstructor
input Expression arg;
input Call call;
output Expression exp;
algorithm
exp := match arg
local
Call arr_call;
Function fn;
Type ty;
Variability var;
Purity purity;
case Expression.CALL(call = arr_call as Call.TYPED_ARRAY_CONSTRUCTOR())
guard Type.dimensionCount(arr_call.ty) == 1
algorithm
Call.TYPED_CALL(fn = fn, ty = ty, var = var, purity = purity) := call;
then
Expression.CALL(Call.makeTypedReduction(fn, ty, var, purity, arr_call.exp, arr_call.iters, AbsynUtil.dummyInfo));
else Expression.CALL(call);
end match;
end simplifyReducedArrayConstructor;
function simplifyTranspose
input Expression arg;
input Call call;
input Boolean expand;
output Expression exp;
protected
Expression e;
algorithm
e := if not expand or Expression.hasArrayCall(arg) then arg else ExpandExp.expand(arg);
exp := match e
case Expression.ARRAY()
guard Array.all(e.elements, Expression.isArray)
then Expression.transposeArray(e);
else Expression.CALL(call);
end match;
end simplifyTranspose;
function simplifyVector
input Expression arg;
input Call call;
output Expression exp;
protected
list<Expression> expl;
Boolean is_literal;
Type ty;
algorithm
expl := Expression.arrayScalarElements(arg);
is_literal := Expression.isLiteral(arg);
if is_literal then
// Ranges count as literals, make sure they're expanded.
expl := ExpandExp.expandList(expl);
end if;
if is_literal or List.all(expl, Expression.isScalar) then
ty := Type.arrayElementType(Expression.typeOf(arg));
exp := Expression.makeExpArray(listArray(expl), ty);
else
exp := Expression.CALL(call);
end if;
end simplifyVector;
function simplifyFill
input Expression fillArg;
input list<Expression> dimArgs;
input Call call;
input Boolean expand;
output Expression exp;
algorithm
if List.all(dimArgs, Expression.isLiteral) and expand then
exp := Expression.fillArgs(fillArg, dimArgs);
else
exp := Expression.CALL(call);
end if;
end simplifyFill;
function simplifyHomotopy
input list<Expression> args;
input Call call;
output Expression exp;
algorithm
exp := match Flags.getConfigString(Flags.REPLACE_HOMOTOPY)
case "actual" then listHead(args);
case "simplified" then listHead(listRest(args));
else Expression.CALL(call);
end match;
end simplifyHomotopy;
function simplifyDelay
input list<Expression> args;
input Call call;
output Expression callExp;
protected
Expression exp, delayTime;
algorithm
exp :: delayTime :: _ := args;
if Expression.variability(delayTime) <= Variability.PARAMETER then
delayTime := Ceval.tryEvalExp(delayTime);
if Expression.isZero(delayTime) then
callExp := exp;
return;
end if;
end if;
callExp := Expression.CALL(call);
end simplifyDelay;
function simplifyDer
input Expression arg;
input Call call;
output Expression exp;
algorithm
if Call.variability(call) < Variability.DISCRETE then
exp := Expression.makeZero(Expression.typeOf(arg));
else
exp := Expression.CALL(call);
end if;
end simplifyDer;
function simplifyArrayConstructor
input Call call;
output Expression outExp;
protected
Type ty;
Variability var;
Purity pur;
Expression exp, e;
list<tuple<InstNode, Expression>> iters;
InstNode iter;
Dimension dim;
Integer dim_size;
Boolean expanded;
algorithm
Call.TYPED_ARRAY_CONSTRUCTOR(ty, var, pur, exp, iters) := call;
iters := list((Util.tuple21(i), simplify(Util.tuple22(i))) for i in iters);
outExp := matchcontinue (iters)
case {(iter, e)}
algorithm
Type.ARRAY(dimensions = {dim}) := Expression.typeOf(e);
dim_size := Dimension.size(dim);
if dim_size == 0 then
// Result is Array[0], return empty array expression.
outExp := Expression.makeEmptyArray(ty);
elseif dim_size == 1 then
// Result is Array[1], return array with the single element.
e := ExpandExp.expand(e);
e := Expression.arrayScalarElement(e);
exp := Expression.replaceIterator(exp, iter, e);
exp := Expression.makeArray(ty, listArray({exp}));
outExp := simplify(exp);
elseif Expression.isLiteral(e) and isIteratorSubscriptedArray(exp, iter) then
// If the iterator is only used to subscript array expressions like
// {{1, 2, 3}[i] for i in 1:3}, then we might as well expand it.
(outExp, expanded) := ExpandExp.expandArrayConstructor(exp, ty, iters);
if expanded then
outExp := simplify(outExp);
end if;
else
fail();
end if;
then
outExp;
else
algorithm
exp := simplify(exp);
ty := Type.simplify(ty);
then
Expression.CALL(Call.TYPED_ARRAY_CONSTRUCTOR(ty, var, pur, exp, iters));
end matchcontinue;
end simplifyArrayConstructor;
function isIteratorSubscriptedArray
input Expression exp;
input InstNode iterator;
output Boolean res;
algorithm
res := match exp
case Expression.SUBSCRIPTED_EXP()
then Expression.isArray(exp.exp) and
List.all(exp.subscripts, function Subscript.equalsIterator(iterator = iterator));
else false;
end match;
end isIteratorSubscriptedArray;
function simplifyReduction
input Call call;
output Expression outExp;
algorithm
outExp := match call
local
Expression exp, e;
list<tuple<InstNode, Expression>> iters;
InstNode iter;
Dimension dim;
Integer dim_size;
case Call.TYPED_REDUCTION()
algorithm
iters := list((Util.tuple21(i), simplify(Util.tuple22(i))) for i in call.iters);
then matchcontinue iters
case {(iter, e)}
algorithm
Type.ARRAY(dimensions = {dim}) := Expression.typeOf(e);
dim_size := Dimension.size(dim);
if dim_size == 0 then
// Iteration range is empty, return default value for reduction.
SOME(outExp) := call.defaultExp;
elseif dim_size == 1 then
// Iteration range is one, return reduction expression with iterator value applied.
e := ExpandExp.expand(e);
e := Expression.arrayScalarElement(e);
outExp := Expression.replaceIterator(call.exp, iter, e);
outExp := simplify(outExp);
else
fail();
end if;
then
outExp;
case _
guard call.var <= Variability.STRUCTURAL_PARAMETER
then Ceval.tryEvalExp(Expression.CALL(call));
case _
guard Flags.isSet(Flags.NF_SCALARIZE)
then simplifyReduction2(AbsynUtil.pathString(Function.name(call.fn)), call.exp, iters);
else
algorithm
call.exp := simplify(call.exp);
call.iters := iters;
then
Expression.CALL(call);
end matchcontinue;
end match;
end simplifyReduction;
function simplifyReduction2
input String name;
input Expression exp;
input list<tuple<InstNode, Expression>> iterators;
output Expression outExp;
protected
InstNode iter;
Expression range, default_exp;
Boolean expanded = true;
list<tuple<InstNode, Expression>> iters = {};
Type ty;
Operator op;
algorithm
ty := Expression.typeOf(exp);
// Operator records are problematic since the start value isn't simplified
// away currently.
false := Type.isRecord(Type.arrayElementType(ty));
(default_exp, op) := match name
case "sum" then (Expression.makeZero(ty), Operator.makeAdd(ty));
case "product" then (Expression.makeOne(ty), Operator.makeMul(ty));
end match;
for i in iterators loop
(iter, range) := i;
(range, true) := ExpandExp.expand(range);
iters := (iter, range) :: iters;
end for;
outExp := Expression.foldReduction(simplify(exp), listReverseInPlace(iters),
default_exp, function simplify(includeScope = false), function simplifyBinaryOp(op = op));
end simplifyReduction2;
function simplifySize
input output Expression sizeExp;
algorithm
sizeExp := match sizeExp
local
Expression exp, index;
Dimension dim;
list<Dimension> dims;
case Expression.SIZE(exp, SOME(index))
algorithm
index := simplify(index);
if Expression.isLiteral(index) then
dim := listGet(Type.arrayDims(Expression.typeOf(exp)), Expression.toInteger(index));
if Dimension.isKnown(dim) then
exp := Expression.INTEGER(Dimension.size(dim));
else
exp := Expression.SIZE(exp, SOME(index));
end if;
else
exp := Expression.SIZE(exp, SOME(index));
end if;
then
exp;
case Expression.SIZE()
algorithm
dims := Type.arrayDims(Expression.typeOf(sizeExp.exp));
if List.all(dims, function Dimension.isKnown(allowExp = true)) then
exp := Expression.makeArray(Type.ARRAY(Type.INTEGER(), {Dimension.fromInteger(listLength(dims))}),
listArray(list(Dimension.sizeExp(d) for d in dims)));
else
exp := sizeExp;
end if;
then
exp;
end match;
end simplifySize;
function simplifyMultary
input output Expression exp;
algorithm
exp := match exp
local
Operator operator;
list<Expression> arguments, inv_arguments, const_args, inv_const_args;
Expression new_const, tmp, result;
Operator.MathClassification mcl;
Boolean useConst, isNegative;
// empty multary with addition -> 0
case Expression.MULTARY(arguments = {}, inv_arguments = {}, operator = operator)
guard(Operator.isDashClassification(Operator.getMathClassification(operator)))
then Expression.makeZero(operator.ty);
// empty multary with multiplication -> 1
case Expression.MULTARY(arguments = {}, inv_arguments = {}, operator = operator)
then Expression.makeOne(operator.ty);
// multary with only one argument
case Expression.MULTARY(arguments = {tmp}, inv_arguments = {})
then tmp;
// non-empty multaries
case Expression.MULTARY(arguments = arguments, inv_arguments = inv_arguments, operator = operator) algorithm
// get math classification
mcl := Operator.getMathClassification(operator);
// simplify arguments first
arguments := list(simplify(arg) for arg in arguments);
inv_arguments := list(simplify(arg) for arg in inv_arguments);
(arguments, inv_arguments, isNegative) := simplifyMultarySigns(arguments, inv_arguments, mcl);
// split them into constant and non constant arguments
(const_args, arguments) := List.splitOnTrue(arguments, Expression.isConstNumber);
(inv_const_args, inv_arguments) := List.splitOnTrue(inv_arguments, Expression.isConstNumber);
// combine the constants
new_const := combineConstantNumbers(const_args, inv_const_args, mcl, Operator.typeOf(operator));
// return combined multary expression and check for trivial replacements
// check if the constant is used
useConst := match mcl
case NFOperator.MathClassification.ADDITION guard(Expression.isZero(new_const)) then false;
case NFOperator.MathClassification.MULTIPLICATION guard(Expression.isOne(new_const)) then false;
else true;
end match;
result := match (mcl, arguments, inv_arguments)
// const + {} - {} = const
// const * {} / {} = const
case (_, {}, {}) then new_const;
// 0 + {cr} - {} = cr
// 1 * {cr} / {} = cr
case (_, {tmp}, {}) guard(not useConst) then tmp;
// 0 + {} - {cr} = - cr
case (NFOperator.MathClassification.ADDITION, {}, {tmp}) guard(not useConst)
then Expression.negate(tmp);
// 0 * {...} / {...} = 0
case (NFOperator.MathClassification.MULTIPLICATION, _, _) guard(Expression.isZero(new_const)) then new_const;
// THIS SEEMS LIKE A BAD IDEA STRUCTURALLY
// apply negative constant to inverse list for addition
//case (NFOperator.MathClassification.ADDITION, _, _) guard(Expression.isNegative(new_const) and useConst)
//then Expression.MULTARY(
// arguments = arguments,
// inv_arguments = Expression.negate(new_const) :: inv_arguments,
// operator = operator
// );
else Expression.MULTARY(
arguments = if useConst then new_const :: arguments else arguments,
inv_arguments = inv_arguments,
operator = operator
);
end match;
// negate the expression if there was an odd number of negative arguments (only multiplication)
then if isNegative then Expression.negate(result) else result;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for expression: " + Expression.toString(exp)});
then fail();
end match;
end simplifyMultary;
function simplifyMultarySigns
input list<Expression> arguments;
input list<Expression> inv_arguments;
input Operator.MathClassification mcl;
output list<Expression> new_arguments = {};
output list<Expression> new_inv_arguments = {};
output Boolean isNegative = false; // only relevant for multiplication
algorithm
_ := match mcl
case NFOperator.MathClassification.ADDITION algorithm
// check if arguments are negative
// negate them and swap them to the other list
for arg in listReverse(arguments) loop
if Expression.isNegative(arg) then
new_inv_arguments := Expression.negate(arg) :: new_inv_arguments;
else
new_arguments := arg :: new_arguments;
end if;
end for;
for arg in listReverse(inv_arguments) loop
if Expression.isNegative(arg) then
new_arguments := Expression.negate(arg) :: new_arguments;
else
new_inv_arguments := arg :: new_inv_arguments;
end if;
end for;
then ();
case NFOperator.MathClassification.MULTIPLICATION algorithm
// check if arguments are negative and negate them.
// track if there is an even or odd number of negative arguments
for arg in listReverse(arguments) loop
if Expression.isNegative(arg) then
new_arguments := Expression.negate(arg) :: new_arguments;
isNegative := not isNegative;
else
new_arguments := arg :: new_arguments;
end if;
end for;
for arg in listReverse(inv_arguments) loop
if Expression.isNegative(arg) then
new_inv_arguments := Expression.negate(arg) :: new_inv_arguments;
isNegative := not isNegative;
else
new_inv_arguments := arg :: new_inv_arguments;
end if;
end for;
then ();
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
end simplifyMultarySigns;
function simplifyBinary
input output Expression binaryExp;
protected
Expression e1, e2, se1, se2;
Operator op;
algorithm
Expression.BINARY(e1, op, e2) := binaryExp;
se1 := simplify(e1);
se2 := simplify(e2);
binaryExp := simplifyBinaryOp(se1, op, se2);
if Flags.isSet(Flags.NF_EXPAND_OPERATIONS) and not Expression.hasArrayCall(binaryExp) then
binaryExp := ExpandExp.expand(binaryExp);
end if;
end simplifyBinary;
function simplifyBinaryOp
input Expression exp1;
input Operator op;
input Expression exp2;
output Expression outExp;
import NFOperator.Op;
algorithm
if Expression.isLiteral(exp1) and Expression.isLiteral(exp2) then
outExp := Ceval.evalBinaryOp(ExpandExp.expand(exp1), op, ExpandExp.expand(exp2));
elseif Expression.isArray(exp1) and Expression.isArray(exp2) then
outExp := match op.op
case Op.ADD then simplifyBinaryEW(exp1, op, exp2);
case Op.SUB then simplifyBinaryEW(exp1, op, exp2);
case Op.ADD_EW then simplifyBinaryEW(exp1, op, exp2);
case Op.SUB_EW then simplifyBinaryEW(exp1, op, exp2);
case Op.MUL_EW then simplifyBinaryEW(exp1, op, exp2);
case Op.DIV_EW then simplifyBinaryEW(exp1, op, exp2);
case Op.POW_EW then simplifyBinaryEW(exp1, op, exp2);
else Expression.BINARY(exp1, op, exp2);
end match;
else
outExp := match op.op
case Op.ADD then simplifyBinaryAdd(exp1, op, exp2);
case Op.SUB then simplifyBinarySub(exp1, op, exp2);
case Op.MUL then simplifyBinaryMul(exp1, op, exp2);
case Op.DIV then simplifyBinaryDiv(exp1, op, exp2);
case Op.POW then simplifyBinaryPow(exp1, op, exp2);
else Expression.BINARY(exp1, op, exp2);
end match;
end if;
end simplifyBinaryOp;
function simplifyBinaryAdd
input Expression exp1;
input Operator op;
input Expression exp2;
output Expression outExp;
algorithm
if Expression.isZero(exp1) then
// 0 + e = e
outExp := exp2;
elseif Expression.isZero(exp2) then
// e + 0 = e
outExp := exp1;
elseif Expression.isNegated(exp2) then
// e1 + -(e2) = e1 - e2
outExp := Expression.BINARY(exp1, Operator.invert(op), Expression.negate(exp2));
else
outExp := Expression.BINARY(exp1, op, exp2);
end if;
end simplifyBinaryAdd;
function simplifyBinarySub
input Expression exp1;
input Operator op;
input Expression exp2;
output Expression outExp;
algorithm
if Expression.isZero(exp1) then
// 0 - e = -e
outExp := Expression.UNARY(Operator.makeUMinus(Operator.typeOf(op)), exp2);
elseif Expression.isZero(exp2) then
// e - 0 = e
outExp := exp1;
elseif Expression.isNegated(exp2) then
// e1 - -(e2) = e1 + e2
outExp := Expression.BINARY(exp1, Operator.invert(op), Expression.negate(exp2));
else
outExp := Expression.BINARY(exp1, op, exp2);
end if;
end simplifyBinarySub;
function simplifyBinaryMul
input Expression exp1;
input Operator op;
input Expression exp2;
input Boolean switched = false;
output Expression outExp;
algorithm
outExp := match exp1
// 0 * e = 0
case Expression.INTEGER(value = 0) then exp1;
case Expression.REAL(value = 0.0) then exp1;
// 1 * e = e
case Expression.INTEGER(value = 1) then exp2;
case Expression.REAL(value = 1.0) then exp2;
else
if switched then
Expression.BINARY(exp2, op, exp1)
else
simplifyBinaryMul(exp2, op, exp1, true);
end match;
end simplifyBinaryMul;
function simplifyBinaryDiv
input Expression exp1;
input Operator op;
input Expression exp2;
output Expression outExp;
algorithm
// fix constants
// e / 1 = e
// e / (-1) = -e
// 0 / e = 0 (e <> 0)
outExp :=
if Expression.isOne(exp2) then exp1
elseif Expression.isMinusOne(exp2) then Expression.negate(exp1)
elseif Expression.isZero(exp1) and not Expression.isZero(exp2) then exp1
// fix minus signs
// (-e1)/(-e2) = e1/e2
// e1/(-e2) = -(e1/e2)
// (-e1)/e2 = -(e1/e2)
// e1/e2 = e1/e2
else match (Expression.isNegative(exp1), Expression.isNegative(exp1))
case (true, true) then Expression.BINARY(Expression.negate(exp1), op, Expression.negate(exp2));
case (false, true) then Expression.negate(Expression.BINARY(exp1, op, Expression.negate(exp2)));
case (true, false) then Expression.negate(Expression.BINARY(Expression.negate(exp1), op, exp2));
case (false, false) then Expression.BINARY(exp1, op, exp2);
end match;
end simplifyBinaryDiv;
function simplifyBinaryPow
input Expression exp1;
input Operator op;
input Expression exp2;
output Expression outExp;
algorithm
if Expression.isZero(exp2) then
outExp := Expression.makeOne(Operator.typeOf(op));
elseif Expression.isOne(exp2) then
outExp := exp1;
else
outExp := Expression.BINARY(exp1, op, exp2);
end if;
end simplifyBinaryPow;
function simplifyBinaryEW
input Expression exp1;
input Operator op;
input Expression exp2;
output Expression outExp;
algorithm
outExp := Expression.makeArray(Operator.typeOf(op),
Array.threadMap(Expression.arrayElements(exp1), Expression.arrayElements(exp2),
function simplifyBinaryOp(op = Operator.unlift(op))));
end simplifyBinaryEW;
function simplifyUnary
input output Expression unaryExp;