-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwnt_FunctionExpression.cpp
2542 lines (2112 loc) · 100 KB
/
wnt_FunctionExpression.cpp
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
/*=====================================================================
FunctionExpression.cpp
----------------------
Copyright Glare Technologies Limited 2016 -
Generated at 2011-04-30 18:53:38 +0100
=====================================================================*/
#include "wnt_FunctionExpression.h"
#include "wnt_ASTNode.h"
#include "wnt_SourceBuffer.h"
#include "wnt_RefCounting.h"
#include "wnt_VectorLiteral.h"
#include "wnt_FunctionDefinition.h"
#include "wnt_VArrayLiteral.h"
#include "wnt_Variable.h"
#include "wnt_LetASTNode.h"
#include "wnt_LetBlock.h"
#include "VirtualMachine.h"
#include "VMState.h"
#include "Value.h"
#include "CompiledValue.h"
#include "Linker.h"
#include "BuiltInFunctionImpl.h"
#include "LLVMUtils.h"
#include "LLVMTypeUtils.h"
#include "ProofUtils.h"
#include "wnt_IfExpression.h"
#include "utils/StringUtils.h"
#include "utils/ConPrint.h"
#include "utils/ContainerUtils.h"
#include "maths/mathstypes.h"
#ifdef _MSC_VER // If compiling with Visual C++
#pragma warning(push, 0) // Disable warnings
#endif
#include "llvm/IR/Type.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/ExecutionEngine/Interpreter.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/Support/raw_ostream.h"
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Intrinsics.h>
#ifdef _MSC_VER
#pragma warning(pop) // Re-enable warnings
#endif
#include <iostream>
using std::vector;
using std::string;
namespace Winter
{
static const bool VERBOSE_EXEC = false;
FunctionExpression::FunctionExpression(const SrcLocation& src_loc)
: ASTNode(FunctionExpressionType, src_loc),
static_target_function(NULL),
proven_defined(false)
{
}
FunctionExpression::FunctionExpression(const SrcLocation& src_loc, const std::string& func_name, const ASTNodeRef& arg0) // 1-arg function
: ASTNode(FunctionExpressionType, src_loc),
static_target_function(NULL),
proven_defined(false)
{
static_function_name = func_name;
argument_expressions.push_back(arg0);
}
FunctionExpression::FunctionExpression(const SrcLocation& src_loc, const std::string& func_name, const ASTNodeRef& arg0, const ASTNodeRef& arg1) // 2-arg function
: ASTNode(FunctionExpressionType, src_loc),
static_target_function(NULL),
proven_defined(false)
{
static_function_name = func_name;
argument_expressions.push_back(arg0);
argument_expressions.push_back(arg1);
}
typedef float (* FLOAT1_TO_FLOAT_TYPE)(float);
typedef float (* FLOAT2_TO_FLOAT_TYPE)(float, float);
typedef double (* DOUBLE1_TO_DOUBLE_TYPE)(double);
typedef double (* DOUBLE2_TO_DOUBLE_TYPE)(double, double);
typedef bool (* FLOAT1_TO_BOOL_TYPE)(float);
typedef bool (* DOUBLE1_TO_BOOL_TYPE)(double);
ValueRef FunctionExpression::exec(VMState& vmstate)
{
if(VERBOSE_EXEC) conPrint(vmstate.indent() + "FunctionExpression, target_name=" + this->functionName() + "\n");
if(vmstate.func_args_start.size() > 1000)
throw ExceptionWithPosition("Function call level too deep, aborting.", errorContext(this));
if(this->static_target_function != NULL && this->static_target_function->external_function.nonNull())
{
// For external functions with certain type signatures, we can call the native function directly:
if(static_target_function->returnType()->getType() == Type::FloatType)
{
if(static_target_function->args.size() == 1 && (static_target_function->args[0].type->getType() == Type::FloatType))
{
if(this->argument_expressions.size() != 1) throw ExceptionWithPosition("Invalid num args.", errorContext(this));
ValueRef arg0 = this->argument_expressions[0]->exec(vmstate);
FLOAT1_TO_FLOAT_TYPE f = (FLOAT1_TO_FLOAT_TYPE)this->static_target_function->external_function->func;
return new FloatValue(f(checkedCast<FloatValue>(arg0)->value));
}
else if(static_target_function->args.size() == 2 &&
(static_target_function->args[0].type->getType() == Type::FloatType) &&
(static_target_function->args[1].type->getType() == Type::FloatType))
{
if(this->argument_expressions.size() != 2) throw ExceptionWithPosition("Invalid num args.", errorContext(this));
ValueRef arg0 = this->argument_expressions[0]->exec(vmstate);
ValueRef arg1 = this->argument_expressions[1]->exec(vmstate);
FLOAT2_TO_FLOAT_TYPE f = (FLOAT2_TO_FLOAT_TYPE)this->static_target_function->external_function->func;
return new FloatValue(f(checkedCast<FloatValue>(arg0)->value, checkedCast<FloatValue>(arg1)->value));
}
}
if(static_target_function->returnType()->getType() == Type::DoubleType)
{
if(static_target_function->args.size() == 1 && (static_target_function->args[0].type->getType() == Type::DoubleType))
{
if(this->argument_expressions.size() != 1) throw ExceptionWithPosition("Invalid num args.", errorContext(this));
ValueRef arg0 = this->argument_expressions[0]->exec(vmstate);
DOUBLE1_TO_DOUBLE_TYPE f = (DOUBLE1_TO_DOUBLE_TYPE)this->static_target_function->external_function->func;
return new DoubleValue(f(checkedCast<DoubleValue>(arg0)->value));
}
else if(static_target_function->args.size() == 2 &&
(static_target_function->args[0].type->getType() == Type::DoubleType) &&
(static_target_function->args[1].type->getType() == Type::DoubleType))
{
if(this->argument_expressions.size() != 2) throw ExceptionWithPosition("Invalid num args.", errorContext(this));
ValueRef arg0 = this->argument_expressions[0]->exec(vmstate);
ValueRef arg1 = this->argument_expressions[1]->exec(vmstate);
DOUBLE2_TO_DOUBLE_TYPE f = (DOUBLE2_TO_DOUBLE_TYPE)this->static_target_function->external_function->func;
return new DoubleValue(f(checkedCast<DoubleValue>(arg0)->value, checkedCast<DoubleValue>(arg1)->value));
}
}
if(static_target_function->returnType()->getType() == Type::BoolType)
{
if(static_target_function->args.size() == 1 && (static_target_function->args[0].type->getType() == Type::FloatType))
{
if(this->argument_expressions.size() != 1)
throw ExceptionWithPosition("Invalid num args.", errorContext(this));
ValueRef arg0 = this->argument_expressions[0]->exec(vmstate);
FLOAT1_TO_BOOL_TYPE f = (FLOAT1_TO_BOOL_TYPE)this->static_target_function->external_function->func;
return new BoolValue(f(checkedCast<FloatValue>(arg0)->value));
}
if(static_target_function->args.size() == 1 && (static_target_function->args[0].type->getType() == Type::DoubleType))
{
if(this->argument_expressions.size() != 1)
throw ExceptionWithPosition("Invalid num args.", errorContext(this));
ValueRef arg0 = this->argument_expressions[0]->exec(vmstate);
DOUBLE1_TO_BOOL_TYPE f = (DOUBLE1_TO_BOOL_TYPE)this->static_target_function->external_function->func;
return new BoolValue(f(checkedCast<DoubleValue>(arg0)->value));
}
}
// Else call the interpreted function.
vector<ValueRef> args;
for(unsigned int i=0; i<this->argument_expressions.size(); ++i)
args.push_back(this->argument_expressions[i]->exec(vmstate));
ValueRef result = this->static_target_function->external_function->interpreted_func(args);
return result;
}
// Get target function from the expression that returns the function
ValueRef base_target_function_val;
const FunctionValue* target_func_val = NULL;
FunctionDefinition* use_target_func;
if(static_target_function)
{
use_target_func = static_target_function;
}
else
{
if(this->get_func_expr.isNull())
throw ExceptionWithPosition("Function is not bound.", errorContext(this));
base_target_function_val = this->get_func_expr->exec(vmstate);
target_func_val = checkedCast<FunctionValue>(base_target_function_val);
use_target_func = target_func_val->func_def;
}
// Push arguments onto argument stack
const size_t initial_arg_stack_size = vmstate.argument_stack.size();
for(unsigned int i=0; i<this->argument_expressions.size(); ++i)
{
vmstate.argument_stack.push_back(this->argument_expressions[i]->exec(vmstate));
if(VERBOSE_EXEC)
{
//std::cout << indent(vmstate) << "Pushed arg " << vmstate.argument_stack.back()->toString() << "\n";
//printStack(vmstate);
}
}
// If the target function is an anon function and has captured values, push that onto the stack
if(use_target_func->is_anon_func)// use_captured_vars)
{
assert(target_func_val);
vmstate.argument_stack.push_back(target_func_val->captured_vars.getPointer());
}
// Execute target function
vmstate.func_args_start.push_back((unsigned int)initial_arg_stack_size);
if(VERBOSE_EXEC)
conPrint(vmstate.indent() + "Calling " + use_target_func->sig.toString() + ", func_args_start: " + toString(vmstate.func_args_start.back()) + "\n");
ValueRef ret = use_target_func->invoke(vmstate);
vmstate.func_args_start.pop_back();
// Remove arguments from stack
vmstate.argument_stack.resize(initial_arg_stack_size);
return ret;
}
bool FunctionExpression::doesFunctionTypeMatch(const TypeRef& type)
{
if(type->getType() != Type::FunctionType)
return false;
const Function* func = static_cast<const Function*>(type.getPointer());
std::vector<TypeRef> arg_types(this->argument_expressions.size());
for(unsigned int i=0; i<arg_types.size(); ++i)
{
arg_types[i] = this->argument_expressions[i]->type();
if(arg_types[i].isNull())
return false;
}
if(arg_types.size() != func->arg_types.size())
return false;
for(unsigned int i=0; i<arg_types.size(); ++i)
if(!(*(arg_types[i]) == *(func->arg_types[i])))
return false;
return true;
}
/*static bool couldCoerceFunctionCall(vector<ASTNodeRef>& argument_expressions, FunctionDefinitionRef func)
{
if(func->args.size() != argument_expressions.size())
return false;
for(size_t i=0; i<argument_expressions.size(); ++i)
{
if(*func->args[i].type == *argument_expressions[i]->type())
{
}
else if( func->args[i].type->getType() == Type::FloatType &&
argument_expressions[i]->nodeType() == ASTNode::IntLiteralType &&
isIntExactlyRepresentableAsFloat(static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value))
{
}
else
return false;
}
return true;
}*/
/*static bool isTargetDefinedBeforeAllInStack(const std::vector<FunctionDefinition*>& func_def_stack, const FunctionDefinition* target_function)
{
if(!target_function->srcLocation().isValid()) // If target is a built-in function etc.. then there are no ordering problems.
return true;
for(size_t i=0; i<func_def_stack.size(); ++i)
if(target_function->order_num >= func_def_stack[i]->order_num)
return false;
return true;
}*/
void FunctionExpression::tryCoerceIntArgsToDoubles(Linker& linker, const std::vector<TypeVRef>& argtypes, int effective_callsite_order_num)
{
if(this->static_target_function)
return;
vector<TypeVRef> coerced_argtypes = argtypes;
for(size_t i=0; i<argtypes.size(); ++i)
{
if( argument_expressions[i]->nodeType() == ASTNode::IntLiteralType &&
isIntExactlyRepresentableAsDouble(static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value))
{
coerced_argtypes[i] = new Double();
}
}
// Try again with our coerced arguments
const FunctionSignature coerced_sig(this->static_function_name, coerced_argtypes);
this->static_target_function = linker.findMatchingFunction(coerced_sig, this->srcLocation(), effective_callsite_order_num/*&payload.func_def_stack*/).getPointer();
if(this->static_target_function/* && isTargetDefinedBeforeAllInStack(payload.func_def_stack, target_function)*/) // Disallow recursion for now: Check the linked function is not the current function.
{
// Success! We need to actually change the argument expressions now
for(size_t i=0; i<argument_expressions.size(); ++i)
{
if( argument_expressions[i]->nodeType() == ASTNode::IntLiteralType &&
isIntExactlyRepresentableAsDouble(static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value))
{
// Replace int literal with double literal
this->argument_expressions[i] = new DoubleLiteral(
(float)static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value,
argument_expressions[i]->srcLocation()
);
}
}
}
}
void FunctionExpression::tryCoerceIntArgsToFloats(Linker& linker, const std::vector<TypeVRef>& argtypes, int effective_callsite_order_num)
{
if(this->static_target_function)
return;
vector<TypeVRef> coerced_argtypes = argtypes;
for(size_t i=0; i<argtypes.size(); ++i)
{
if( argument_expressions[i]->nodeType() == ASTNode::IntLiteralType &&
isIntExactlyRepresentableAsFloat(static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value))
{
coerced_argtypes[i] = new Float();
}
}
// Try again with our coerced arguments
const FunctionSignature coerced_sig(this->static_function_name, coerced_argtypes);
this->static_target_function = linker.findMatchingFunction(coerced_sig, this->srcLocation(), effective_callsite_order_num/*&payload.func_def_stack*/).getPointer();
if(this->static_target_function/* && isTargetDefinedBeforeAllInStack(payload.func_def_stack, target_function)*/) // Disallow recursion for now: Check the linked function is not the current function.
{
// Success! We need to actually change the argument expressions now
for(size_t i=0; i<argument_expressions.size(); ++i)
{
if( argument_expressions[i]->nodeType() == ASTNode::IntLiteralType &&
isIntExactlyRepresentableAsFloat(static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value))
{
// Replace int literal with float literal
this->argument_expressions[i] = new FloatLiteral(
(float)static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value,
argument_expressions[i]->srcLocation()
);
}
}
}
}
// Statically bind to global function definition.
void FunctionExpression::bindFunction(Linker& linker, TraversalPayload& payload, std::vector<ASTNode*>& stack)
{
// Return if we have already bound this function in an earlier pass.
if(this->static_function_name.empty() || static_target_function != NULL)
return;
// We want to find a function that matches our argument expression types, and the function name
{
vector<TypeVRef> argtypes;
for(unsigned int i=0; i<this->argument_expressions.size(); ++i)
{
const TypeRef arg_expr_type = this->argument_expressions[i]->type();
if(arg_expr_type.isNull())
return; // Don't try and bind if we have a null type
argtypes.push_back(TypeVRef(arg_expr_type));
}
const FunctionSignature sig(this->static_function_name, argtypes);
// Work out effective call site position.
int effective_callsite_order_num = 1000000000;
if(payload.current_named_constant)
effective_callsite_order_num = payload.current_named_constant->order_num;
for(size_t z=0; z<payload.func_def_stack.size(); ++z)
effective_callsite_order_num = myMin(effective_callsite_order_num, payload.func_def_stack[z]->order_num);
// Try and resolve to internal function.
this->static_target_function = linker.findMatchingFunction(sig, this->srcLocation(), effective_callsite_order_num/*&payload.func_def_stack*/).getPointer();
if(this->static_target_function/* && isTargetDefinedBeforeAllInStack(payload.func_def_stack, target_function)*/) // Disallow recursion for now: Check the linked function is not the current function.
{
}
else
{
// Try and promote integer args to double args.
// TODO: try all possible coercion combinations.
// This is not really the best way of doing this type coercion, the old approach of matching by name is better.
if(linker.try_coerce_int_to_double_first)
{
tryCoerceIntArgsToDoubles(linker, argtypes, effective_callsite_order_num);
tryCoerceIntArgsToFloats(linker, argtypes, effective_callsite_order_num);
}
else
{
tryCoerceIntArgsToFloats(linker, argtypes, effective_callsite_order_num);
tryCoerceIntArgsToDoubles(linker, argtypes, effective_callsite_order_num);
}
/*vector<FunctionDefinitionRef> funcs;
linker.getFuncsWithMatchingName(sig.name, funcs);
vector<FunctionDefinitionRef> possible_matches;
for(size_t z=0; z<funcs.size(); ++z)
if(couldCoerceFunctionCall(argument_expressions, funcs[z]))
possible_matches.push_back(funcs[z]);
if(possible_matches.size() == 1)
{
for(size_t i=0; i<argument_expressions.size(); ++i)
{
if( possible_matches[0]->args[i].type->getType() == Type::FloatType &&
argument_expressions[i]->nodeType() == ASTNode::IntLiteralType &&
isIntExactlyRepresentableAsFloat(static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value))
{
// Replace int literal with float literal
this->argument_expressions[i] = ASTNodeRef(new FloatLiteral(
(float)static_cast<IntLiteral*>(argument_expressions[i].getPointer())->value,
argument_expressions[i]->srcLocation()
));
}
}
this->target_function = possible_matches[0].getPointer();
this->binding_type = BoundToGlobalDef;
}
else if(possible_matches.size() > 1)
{
string s = "Found more than one possible match for overloaded function: \n";
for(size_t z=0; z<possible_matches.size(); ++z)
s += possible_matches[z]->sig.toString() + "\n";
throw BaseException(s + "." , errorContext(*this));
}*/
}
if(this->static_target_function)
this->static_target_function->num_uses++;
//TEMP: don't fail now, maybe we can bind later.
//if(this->binding_type == Unbound)
// throw BaseException("Failed to find function '" + sig.toString() + "'." , errorContext(*this));
}
}
static bool varWithNameIsInScope(const std::string& name, TraversalPayload& payload, std::vector<ASTNode*>& stack)
{
for(int s = (int)stack.size() - 1; s >= 0; --s) // Walk up the stack of ancestor nodes
{
if(stack[s]->nodeType() == ASTNode::FunctionDefinitionType) // If node is a function definition:
{
FunctionDefinition* def = static_cast<FunctionDefinition*>(stack[s]);
for(unsigned int i=0; i<def->args.size(); ++i) // For each argument to the function:
if(def->args[i].name == name) // If the argument name matches this variable name:
if(def->args[i].type->getType() == Type::FunctionType) // Since this is a function argument, we can tell its scope. Only consider it if it has function type.
return true;
}
else if(stack[s]->nodeType() == ASTNode::LetBlockType)
{
LetBlock* let_block = static_cast<LetBlock*>(stack[s]);
for(unsigned int i=0; i<let_block->lets.size(); ++i)
{
// If the variable we are tring to bind is in a let expression for the current Let Block, then
// we only want to bind to let variables from let expressions that are *before* the current let expression.
// In cases like
// let
// x = x
// This avoids the x expression on the right binding to the x Let node on the left.
// In cases like this:
// let
// z = y
// y = x
// it also prevent y from binding to the y from the line below. (which could cause a cycle of references)
if((s + 1 < (int)stack.size()) && (stack[s+1]->nodeType() == ASTNode::LetType) && (let_block->lets[i].getPointer() == stack[s+1]))
{
// We have reached the let expression for the current variable we are tring to bind, so don't try and bind with let variables equal to or past this one.
break;
}
else
{
for(size_t v=0; v<let_block->lets[i]->vars.size(); ++v)
if(let_block->lets[i]->vars[v].name == name)
return true;
}
}
}
}
// Consider named constants
Linker::NamedConstantMap::iterator name_res = payload.linker->named_constant_map.find(name);
if(name_res != payload.linker->named_constant_map.end())
{
const NamedConstant* target_named_constant = name_res->second.getPointer();
// Only bind to a named constant defined earlier, and only bind to a named constant earlier than all functions we are defining.
if((!payload.current_named_constant || target_named_constant->order_num < payload.current_named_constant->order_num) &&
isTargetDefinedBeforeAllInStack(payload.func_def_stack, target_named_constant->order_num))
return true;
}
return false;
}
void FunctionExpression::traverse(TraversalPayload& payload, std::vector<ASTNode*>& stack)
{
//if(payload.operation == TraversalPayload::ConstantFolding)
//{
// for(size_t i=0; i<argument_expressions.size(); ++i)
// if(shouldFoldExpression(argument_expressions[i], payload))
// {
// try
// {
// argument_expressions[i] = foldExpression(argument_expressions[i], payload);
// payload.tree_changed = true;
// }
// catch(BaseException& )
// {
// // An invalid operation was performed, such as dividing by zero, while trying to eval the AST node.
// // In this case we will consider the folding as not taking place.
// }
// }
//}
/*else */if(payload.operation == TraversalPayload::TypeCoercion)
{
}
else if(payload.operation == TraversalPayload::CustomVisit)
{
if(payload.custom_visitor.nonNull())
payload.custom_visitor->visit(*this, payload);
}
// NOTE: we want to do a post-order traversal here.
// This is because we want our argument expressions to be linked first.
// If we have a get_func_expr, and it is a variable, and if there are no such names in scope to bind to,
// then convert to a 'static' function binding, so we can do stuff like function overloading.
if(payload.operation == TraversalPayload::BindVariables)
{
if(get_func_expr.nonNull() && (get_func_expr->nodeType() == ASTNode::VariableASTNodeType))
{
if((get_func_expr.downcastToPtr<Variable>()->binding_type == Variable::BindingType_Unbound) && !varWithNameIsInScope(get_func_expr.downcastToPtr<Variable>()->name, payload, stack))
{
// Convert to static function
this->static_function_name = get_func_expr.downcastToPtr<Variable>()->name;
get_func_expr = NULL;
}
}
// Convert get_func_expr variable expressions bound to a global def to direct static bindings. This kind of conversion may be possible after inlining.
// NOTE: there is is probably a better way of doing this.
if(!this->static_target_function && get_func_expr.nonNull())
{
if(this->get_func_expr->nodeType() == ASTNode::VariableASTNodeType &&
this->get_func_expr.downcastToPtr<Variable>()->binding_type == Variable::BindingType_GlobalDef)
{
this->static_target_function = this->get_func_expr.downcastToPtr<Variable>()->bound_function;
this->get_func_expr = NULL;
}
}
}
stack.push_back(this);
if(get_func_expr.nonNull())
this->get_func_expr->traverse(payload, stack);
for(unsigned int i=0; i<this->argument_expressions.size(); ++i)
this->argument_expressions[i]->traverse(payload, stack);
if(payload.operation == TraversalPayload::InlineFunctionCalls)
{
checkInlineExpression(payload, stack);
}
else if(payload.operation == TraversalPayload::BindVariables) // LinkFunctions)
{
// If this is a generic function, we can't try and bind function expressions yet,
// because the binding depends on argument type due to function overloading, so we have to wait
// until we know the concrete type.
if(payload.func_def_stack.empty() || !payload.func_def_stack.back()->isGenericFunction())
bindFunction(*payload.linker, payload, stack);
// Set shuffle mask now
if(this->static_target_function && ::hasPrefix(this->static_target_function->sig.name, "shuffle"))
{
assert(this->argument_expressions.size() == 2);
if(!this->argument_expressions[1]->isConstant())
throw ExceptionWithPosition("Second arg to shuffle must be constant", errorContext(this));
try
{
VMState vmstate;
vmstate.func_args_start.push_back(0);
ValueRef res = this->argument_expressions[1]->exec(vmstate);
const VectorValue* res_v = checkedCast<VectorValue>(res);
std::vector<int> mask(res_v->e.size());
for(size_t i=0; i<mask.size(); ++i)
{
if(res_v->e[i]->valueType() != Value::ValueType_Int)
throw ExceptionWithPosition("Element in shuffle mask was not an integer.", errorContext(this));
const int64 index = static_cast<IntValue*>(res_v->e[i].getPointer())->value;
mask[i] = (int)index;
}
assert(this->static_target_function->built_in_func_impl.nonNull());
assert(this->static_target_function->built_in_func_impl->builtInType() == BuiltInFunctionImpl::BuiltInType_ShuffleBuiltInFunc);
static_cast<ShuffleBuiltInFunc*>(this->static_target_function->built_in_func_impl.getPointer())->setShuffleMask(mask);
}
catch(ExceptionWithPosition& e)
{
throw ExceptionWithPosition("Failed to eval second arg of shuffle: " + e.what(), errorContext(this));
}
}
// Set second arg now for elem(tuple, i)
else if(this->static_target_function && this->static_target_function->sig.name == "elem" && static_target_function->sig.param_types[0]->getType() == Type::TupleTypeType)
{
assert(this->argument_expressions.size() == 2);
if(!this->argument_expressions[1]->isConstant())
throw ExceptionWithPosition("Second arg to elem(tuple, i) must be constant", errorContext(this));
int64 index;
try
{
VMState vmstate;
vmstate.func_args_start.push_back(0);
ValueRef res = this->argument_expressions[1]->exec(vmstate);
const IntValue* res_i = checkedCast<IntValue>(res.getPointer());
index = res_i->value;
}
catch(ExceptionWithPosition& e)
{
throw ExceptionWithPosition("Failed to eval second arg of elem(tuple, i): " + e.what(), errorContext(this));
}
assert(this->static_target_function->built_in_func_impl.nonNull());
assert(this->static_target_function->built_in_func_impl->builtInType() == BuiltInFunctionImpl::BuiltInType_GetTupleElementBuiltInFunc);
GetTupleElementBuiltInFunc* tuple_elem_func = static_cast<GetTupleElementBuiltInFunc*>(this->static_target_function->built_in_func_impl.getPointer());
// bounds check index.
if(index < 0 || index >= (int64)tuple_elem_func->tuple_type->component_types.size())
throw ExceptionWithPosition("Second argument to tuple elem() function is out of range.", errorContext(*this));
tuple_elem_func->setIndex((int)index);//TODO: remove cast
// Set proper return type for function definition.
this->static_target_function->declared_return_type = tuple_elem_func->tuple_type->component_types[index];
}
else if(this->static_target_function && this->static_target_function->sig.name == "fold")
{
// TEMP: specialise fold for the passed in function now.
//if(this->binding_type == BoundToGlobalDef)
//{
assert(this->static_target_function->built_in_func_impl.nonNull());
assert(this->static_target_function->built_in_func_impl->builtInType() == BuiltInFunctionImpl::BuiltInType_ArrayFoldBuiltInFunc);
ArrayFoldBuiltInFunc* fold_func = static_cast<ArrayFoldBuiltInFunc*>(this->static_target_function->built_in_func_impl.getPointer());
// Eval first arg (to get function 'f')
try
{
VMState vmstate;
vmstate.func_args_start.push_back(0);
ValueRef res = this->argument_expressions[0]->exec(vmstate);
const FunctionValue* res_f = checkedCast<FunctionValue>(res);
fold_func->specialiseForFunctionArg(res_f->func_def);
}
catch(ExceptionWithPosition& e)
{
throw ExceptionWithPosition("Failed to eval first arg of fold " + e.what(), errorContext(this));
}
//}
}
else if(this->static_target_function && this->static_target_function->sig.name == "map")
{
// TEMP: specialise map for the passed in function now.
//if(this->binding_type == BoundToGlobalDef)
//{
assert(this->static_target_function->built_in_func_impl.nonNull());
assert(this->static_target_function->built_in_func_impl->builtInType() == BuiltInFunctionImpl::BuiltInType_ArrayMapBuiltInFunc);
ArrayMapBuiltInFunc* map_func = static_cast<ArrayMapBuiltInFunc*>(this->static_target_function->built_in_func_impl.getPointer());
// Eval first arg (to get function 'f')
try
{
VMState vmstate;
vmstate.func_args_start.push_back(0);
ValueRef res = this->argument_expressions[0]->exec(vmstate);
const FunctionValue* res_f = checkedCast<FunctionValue>(res);
map_func->specialiseForFunctionArg(res_f->func_def);
}
catch(ExceptionWithPosition& e)
{
throw ExceptionWithPosition("Failed to eval first arg of map " + e.what(), errorContext(this));
}
//}
}
if(payload.check_bindings && get_func_expr.isNull() && (static_target_function == NULL)) //this->binding_type == Unbound)
{
//throw BaseException("Failed to find function '" + this->function_name + "' for the given argument types." + errorContext(*this));
vector<TypeVRef> argtypes;
for(unsigned int i=0; i<this->argument_expressions.size(); ++i)
{
const TypeRef arg_expr_type = this->argument_expressions[i]->type(); // may be NULL
if(arg_expr_type.isNull())
throw ExceptionWithPosition("Failed to find function '" + this->static_function_name + "', argument " + toString(i + 1) + " had unknown type.", errorContext(*this));
argtypes.push_back(TypeVRef(arg_expr_type));
}
const FunctionSignature sig(this->static_function_name, argtypes);
std::string msg = "Failed to find function '" + sig.toString() + "'.";
// Print out signatures of other functions with the same name
std::vector<FunctionDefinitionRef> funcs_same_name;
payload.linker->getFuncsWithMatchingName(this->static_function_name, funcs_same_name);
if(!funcs_same_name.empty())
{
msg += "\nOther functions with the same name: \n";
for(size_t i=0; i<funcs_same_name.size(); ++i)
msg += funcs_same_name[i]->sig.toString() + "\n";
}
throw ExceptionWithPosition(msg, errorContext(this));
}
}
else if(payload.operation == TraversalPayload::CheckInDomain)
{
checkInDomain(payload, stack);
this->proven_defined = true;
}
else if(payload.operation == TraversalPayload::TypeCheck)
{
// If the function is bound at runtime, need to do some type-checking here.
if(this->get_func_expr.nonNull())
{
const TypeRef get_func_expr_type = this->get_func_expr->type();
if(get_func_expr_type->getType() != Type::FunctionType)
throw ExceptionWithPosition("expression did not have function type.", errorContext(*get_func_expr));
const Function* function_type = get_func_expr_type.downcastToPtr<Function>();
if(function_type->arg_types.size() != argument_expressions.size())
throw ExceptionWithPosition("Incorrect number of arguments for function.", errorContext(*get_func_expr));
for(size_t i=0; i<function_type->arg_types.size(); ++i)
{
if(*argument_expressions[i]->type() != *function_type->arg_types[i])
throw ExceptionWithPosition("Invalid type for argument: argument type was " + argument_expressions[i]->type()->toString() + ", expected type " + function_type->arg_types[i]->toString() + ".", errorContext(*get_func_expr));
}
}
// Check the argument expression types still match the function argument types.
// They may have changed due to e.g. type coercion from int->float, in which case they won't be valid any more.
/*vector<TypeRef> argtypes(argument_expressions.size());
for(size_t i=0; i<argument_expressions.size(); ++i)
argtypes[i] = argument_expressions[i]->type();
if(this->binding_type == BoundToGlobalDef)
{
for(size_t i=0; i<argument_expressions.size(); ++i)
if(*argument_expressions[i]->type() != *target_function->args[i].type)
}*/
//if(this->binding_type == Unbound)
//{
// vector<TypeRef> argtypes;
// //bool has_null_argtype = false;
// for(unsigned int i=0; i<this->argument_expressions.size(); ++i)
// {
// argtypes.push_back(this->argument_expressions[i]->type());
// //if(argtypes.back().isNull())
// // has_null_argtype = true;
// }
// /*if(has_null_argtype)
// {
// throw BaseException("Failed to find function '" + this->function_name + "'." + errorContext(*this));
// }
// else*/
// {
// const FunctionSignature sig(this->function_name, argtypes);
//
// throw BaseException("Failed to find function '" + sig.toString() + "'." + errorContext(*this));
// }
//}
if(this->static_target_function)//this->binding_type == BoundToGlobalDef)
{
// Check shuffle mask (arg 1) is a vector of ints
if(::hasPrefix(this->static_target_function->sig.name, "shuffle"))
{
// TODO
}
}
}
else if(payload.operation == TraversalPayload::ComputeCanConstantFold)
{
// TODO: check function is bound etc..?
if(this->static_target_function)
{
// If the target function is an external function, but the function ptr is null, we can't call it, so don't try and constant fold.
if(this->static_target_function->external_function.nonNull() && this->static_target_function->external_function->func == NULL)
this->can_maybe_constant_fold = false;
else
{
/*this->can_constant_fold = true;
for(size_t i=0; i<argument_expressions.size(); ++i)
can_constant_fold = can_constant_fold && argument_expressions[i]->can_constant_fold;
this->can_constant_fold = this->can_constant_fold && expressionIsWellTyped(*this, payload);*/
this->can_maybe_constant_fold = true;
for(size_t i=0; i<argument_expressions.size(); ++i)
{
const bool arg_is_literal = checkFoldExpression(argument_expressions[i], payload, stack);
this->can_maybe_constant_fold = this->can_maybe_constant_fold && arg_is_literal;
}
}
}
else
this->can_maybe_constant_fold = false;
}
else if(payload.operation == TraversalPayload::DeadFunctionElimination)
{
// if we have traversed here in the DeadFunctionElimination pass, we know this function is reachable.
if(this->static_target_function)
{
payload.reachable_nodes.insert(this->static_target_function); // Mark as alive
if(payload.processed_nodes.find(this->static_target_function) == payload.processed_nodes.end()) // If not processed yet:
payload.nodes_to_process.push_back(this->static_target_function); // Add to to-process list
}
}
else if(payload.operation == TraversalPayload::CountFunctionCalls)
{
if(this->static_target_function)
payload.calls_to_func_count[this->static_target_function]++;
else if(this->get_func_expr.nonNull())
{
// Walk up the tree until we get to a node that is not a variable bound to a let node:
ASTNode* cur = this->get_func_expr.getPointer();
while((cur->nodeType() == ASTNode::VariableASTNodeType) && (((Variable*)cur)->binding_type == Variable::BindingType_Let))
cur = ((Variable*)cur)->bound_let_node->expr.getPointer();
if(cur->nodeType() == ASTNode::FunctionDefinitionType)
payload.calls_to_func_count[(FunctionDefinition*)cur]++;
else if(cur->nodeType() == ASTNode::VariableASTNodeType && ((Variable*)cur)->binding_type == Variable::BindingType_GlobalDef)
payload.calls_to_func_count[((Variable*)cur)->bound_function]++;
}
}
stack.pop_back();
}
/*
If node 'e' is a function expression, inline the target function by replacing e with the target function body.
*/
void FunctionExpression::checkInlineExpression(TraversalPayload& payload, std::vector<ASTNode*>& stack)
{
FunctionDefinition* target_func = NULL;
bool is_beta_reduction = false; // Is this a lambda being applied directly, e.g. an expression like "(\\(float y) : y*y) (x)" ?
if(this->static_target_function)
{
target_func = this->static_target_function;
}
else if(this->get_func_expr.nonNull())
{
if(this->get_func_expr->nodeType() == ASTNode::FunctionDefinitionType)
{
target_func = this->get_func_expr.downcastToPtr<FunctionDefinition>();
is_beta_reduction = true;
}
else
{
// Walk up the tree until we get to a node that is not a variable bound to a let node:
ASTNode* cur = this->get_func_expr.getPointer();
while((cur->nodeType() == ASTNode::VariableASTNodeType) && (((Variable*)cur)->binding_type == Variable::BindingType_Let))
cur = ((Variable*)cur)->bound_let_node->expr.getPointer();
if(cur->nodeType() == ASTNode::FunctionDefinitionType)
target_func = (FunctionDefinition*)cur;
else if(cur->nodeType() == ASTNode::VariableASTNodeType && ((Variable*)cur)->binding_type == Variable::BindingType_GlobalDef)
target_func = ((Variable*)cur)->bound_function;
}
/*else if(func_expr->get_func_expr->isConstant())
{
//if(func_expr->get_func_expr.isType<Variable>())
//{
// const Variable* var = func_expr->get_func_expr
try
{
VMState vmstate;
vmstate.capture_vars = false;
vmstate.func_args_start.push_back(0);
ValueRef base_target_function_val = func_expr->get_func_expr->exec(vmstate);
const FunctionValue* target_func_val = checkedCast<FunctionValue>(base_target_function_val);
target_func = target_func_val->func_def;
}
catch(BaseException&)
{
}
}*/
}
const bool verbose = false;
// If we are optimising for OpenCL, and the target function has the opencl_noinline attribute, don't inline.
const bool opencl_allow_inline = (payload.linker == NULL) || !payload.linker->optimise_for_opencl || !target_func || (payload.linker->optimise_for_opencl && !target_func->opencl_noinline);
if(verbose && !opencl_allow_inline)
conPrint("Not inlining due to opencl_noinline attribute.");
if(target_func && !target_func->noinline && opencl_allow_inline && !target_func->isExternalFunction() && target_func->body.nonNull()) // If is potentially inlinable:
{
if(verbose) conPrint("\n=================== Considering inlining function call =====================\n");
if(verbose) conPrint("target func: " + target_func->sig.toString());
const int call_count = payload.calls_to_func_count[target_func];
if(verbose) conPrint("target complexity: " + toString(target_func->getSubtreeCodeComplexity()));
const bool target_func_simple = target_func->getSubtreeCodeComplexity() < 20;
// Work out if the argument expressions are 'expensive' to evaluate.
// If they are, don't inline this function expression if the expensive argument expression is duplicated.
// e.g. def f(float x) : x + x + x + x,
// main(float x) : f(sin(x)) would get inlined to main(float x) : sin(x) + sin(x) + sin(x) + sin(x)
//
// NOTE: Instead of not inlining the function body directly, we could inline to a let expression, e.g. to
//
// let f_arg0 = sin(x) in f(f_arg0)
bool expensive_arg_expr_duplicated = false;
for(size_t i=0; i<this->argument_expressions.size(); ++i)
{
bool arg_expr_is_expensive = false;
if(this->argument_expressions[i]->nodeType() == ASTNode::FunctionExpressionType)
{
// Consider function calls expensive, with some exceptions, such as:
// * Call to getfield built-in function (field access)
bool func_call_is_expensive = true;
const FunctionDefinition* arg_target_func = this->argument_expressions[i].downcastToPtr<FunctionExpression>()->static_target_function;