-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwnt_FunctionDefinition.cpp
1803 lines (1463 loc) · 59.6 KB
/
wnt_FunctionDefinition.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
/*=====================================================================
FunctionDefinition.cpp
-------------------
Copyright Glare Technologies Limited 2016 -
Generated at 2011-04-25 19:15:40 +0100
=====================================================================*/
#include "wnt_FunctionDefinition.h"
#include "wnt_ASTNode.h"
#include "wnt_SourceBuffer.h"
#include "wnt_RefCounting.h"
#include "wnt_Variable.h"
#include "wnt_LetASTNode.h"
#include "VirtualMachine.h"
#include "VMState.h"
#include "Value.h"
#include "Linker.h"
#include "BuiltInFunctionImpl.h"
#include "LLVMUtils.h"
#include "LLVMTypeUtils.h"
#include "utils/StringUtils.h"
#include "utils/ConPrint.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>
#include <llvm/IR/Attributes.h>
#include <llvm/IR/DataLayout.h>
#ifdef _MSC_VER
#pragma warning(pop) // Re-enable warnings
#endif
using std::vector;
using std::string;
namespace Winter
{
static const std::vector<TypeVRef> makeArgTypeVector(const std::vector<FunctionDefinition::FunctionArg>& args)
{
std::vector<TypeVRef> res;
res.reserve(args.size());
for(unsigned int i=0; i<args.size(); ++i)
res.push_back(args[i].type);
return res;
}
FunctionDefinition::FunctionDefinition(const SrcLocation& src_loc, int order_num_, const std::string& name, const std::vector<FunctionArg>& args_,
const ASTNodeRef& body_, const TypeRef& declared_rettype,
const BuiltInFunctionImplRef& impl
)
: ASTNode(FunctionDefinitionType, src_loc),
order_num(order_num_),
args(args_),
body(body_),
declared_return_type(declared_rettype),
built_in_func_impl(impl),
built_llvm_function(NULL),
//use_captured_vars(false),
need_to_emit_captured_var_struct_version(false),
is_anon_func(false),
num_uses(0),
noinline(false),
opencl_noinline(false),
sig(name, makeArgTypeVector(args_)),
llvm_reported_stack_size(-1)
{
// TODO: fix this, make into method
//function_type = TypeRef(new Function(sig.param_types, declared_rettype));
//this->let_exprs_llvm_value = std::vector<llvm::Value*>(this->lets.size(), NULL);
}
FunctionDefinition::~FunctionDefinition()
{
// For any free variables, erase this function definition from the variable's lambda set, as we don't want dangling pointers.
for(auto it = free_variables.begin(); it != free_variables.end(); ++it)
{
(*it)->lambdas.erase(this);
}
}
TypeRef FunctionDefinition::returnType() const
{
if(this->declared_return_type.nonNull())
return this->declared_return_type;
return this->body->type();
}
TypeRef FunctionDefinition::type() const
{
//vector<TypeRef> captured_var_types;
//for(size_t i=0; i<this->captured_vars.size(); ++i)
// captured_var_types.push_back(this->captured_vars[i].type());
const TypeRef return_type = this->returnType();
if(return_type.isNull()) return NULL;
return new Function(makeArgTypeVector(this->args), TypeVRef(return_type), /*use_captured_vars_=*/true);
}
ValueRef FunctionDefinition::exec(VMState& vmstate)
{
// Capture variables
vector<ValueRef> vals;
const auto unique_free_vars = this->getUniqueFreeVarList();
for(auto it = unique_free_vars.begin(); it != unique_free_vars.end(); ++it)
{
Variable* free_var = *it;
// If this free variable is free in more than one lambda, we will need to get the captured value from the captured-val struct of the outer lambda.
const FunctionDefinition* free_in_looser_lambda = NULL;
bool found_this_lambda = false;
for(int q=(int)free_var->enclosing_lambdas.size()-1; q >= 0; --q) // From inner to outer lambda:
{
const FunctionDefinition* func = free_var->enclosing_lambdas[q];
if(func == this)
found_this_lambda = true;
else if(found_this_lambda)
{
if(func->free_variables.count(free_var) > 0)
{
free_in_looser_lambda = func;
break;
}
}
}
if(free_in_looser_lambda)
{
// Get ref to capturedVars structure of values, will be passed in as last arg to function
ValueRef captured_struct = vmstate.argument_stack.back();
const StructureValue* s = checkedCast<StructureValue>(captured_struct.getPointer());
const size_t free_index = free_in_looser_lambda->getFreeIndexForVar(free_var);
ValueRef val = s->fields[free_index];
vals.push_back(val);
}
else if(free_var->binding_type == Variable::BindingType_Argument)
{
vals.push_back(vmstate.argument_stack[vmstate.func_args_start.back() + free_var->arg_index]);
}
else if(free_var->binding_type == Variable::BindingType_Let)
{
LetASTNode* bound_let_node = free_var->bound_let_node;
ValueRef val = free_var->bound_let_node->exec(vmstate);
if(bound_let_node->vars.size() != 1)
{
// Destructuring assignment, return the particular element from the tuple.
const TupleValue* t = checkedCast<TupleValue>(val.getPointer());
val = t->e[free_var->let_var_index];
}
vals.push_back(val);
}
else
{
assert(0);
throw BaseException("internal error 136");
}
}
// Put captured values into the variable struct.
Reference<StructureValue> var_struct = new StructureValue(vals);
return new FunctionValue(this, var_struct);
}
//static void printStack(VMState& vmstate)
//{
// std::cout << indent(vmstate) << "arg Stack: [";
// for(unsigned int i=0; i<vmstate.argument_stack.size(); ++i)
// std::cout << vmstate.argument_stack[i]->toString() + (i + 1 < vmstate.argument_stack.size() ? string(",\n") : string("\n"));
// std::cout << "]\n";
//}
ValueRef FunctionDefinition::invoke(VMState& vmstate)
{
if(vmstate.trace)
{
//*vmstate.ostream << vmstate.indent() << "" << this->sig.name << "()\n";
//printStack(vmstate);
}
// Check the types of the arguments that we have received
/*for(size_t i=0; i<this->args.size(); ++i)
{
ValueRef arg_val = vmstate.argument_stack[vmstate.func_args_start.back() + i];
if(vmstate.trace)
{
*vmstate.ostream << "Arg " << i << ": " << arg_val->toString() << std::endl;
}
}*/
if(this->built_in_func_impl.nonNull())
return this->built_in_func_impl->invoke(vmstate);
// Execute body of function
ValueRef ret = body->exec(vmstate);
if(this->declared_return_type.nonNull() && (*body->type() != *this->declared_return_type))
{
// This may happen since type checking may not have been done yet.
throw ExceptionWithPosition("Returned object has invalid type.", errorContext(this));
}
return ret;
}
void FunctionDefinition::traverse(TraversalPayload& payload, std::vector<ASTNode*>& stack)
{
// Don't traverse function defn from top level directly, wait until it is traversed as the child of the enclosing function
if(is_anon_func && stack.empty() && (payload.operation != TraversalPayload::UpdateUpRefs))
return;
if(this->isGenericFunction() && (payload.operation != TraversalPayload::CustomVisit))
return;
/*if(payload.operation == TraversalPayload::ConstantFolding)
{
checkFoldExpression(body, payload);
}*/
//if(payload.operation == TraversalPayload::TypeCheck)
//{
// if(this->isGenericFunction())
// return; // Don't type check this. Concrete versions of this func will be type checked individually.
// if(this->body.nonNull())
// {
// if(this->declared_return_type.nonNull())
// {
// // Check that the return type of the body expression is equal to the declared return type
// // of this function.
// if(*this->body->type() != *this->declared_return_type)
// throw BaseException("Type error for function '" + this->sig.toString() + "': Computed return type '" + this->body->type()->toString() +
// "' is not equal to the declared return type '" + this->declared_return_type->toString() + "'.", errorContext(*this));
// }
// else
// {
// // Else return type is NULL, so infer it
// //this->return_type = this->body->type();
// }
// }
//}
if(payload.operation == TraversalPayload::TypeCheck)
{
payload.captured_types.clear();
}
else if(payload.operation == TraversalPayload::CustomVisit)
{
if(payload.custom_visitor.nonNull())
payload.custom_visitor->visit(*this, payload);
}
else if(payload.operation == TraversalPayload::DeadCodeElimination_ComputeAlive)
{
if(stack.empty()) // If this is a top-level global func (not a lambda expression):
{
// Clear this data in preparation for the analysis.
payload.reachable_nodes.clear();
payload.nodes_to_process.clear();
payload.processed_nodes.clear();
}
}
else if(payload.operation == TraversalPayload::CountArgumentRefs)
{
for(size_t i = 0; i<this->args.size(); ++i)
this->args[i].ref_count = 0;
}
else if(payload.operation == TraversalPayload::UnbindVariables)
{
this->free_variables.clear();
}
//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(this->isGenericFunction())
// return; // Don't try and bind functions yet.
//}
//bool old_use_captured_vars = payload.capture_variables;
//if(payload.operation == TraversalPayload::BindVariables)
//{
// if(this->use_captured_vars) // if we are an anon function...
// payload.capture_variables = true; // Tell varables in function expression tree to capture
//}
payload.func_def_stack.push_back(this);
stack.push_back(this);
if(this->body.nonNull())
{
this->body->traverse(payload, stack);
}
//payload.capture_variables = old_use_captured_vars;
if(payload.operation == TraversalPayload::UpdateUpRefs)
{
}
else if(payload.operation == TraversalPayload::SubstituteVariables)
{
this->order_num = payload.new_order_num;
}
else if(payload.operation == TraversalPayload::TypeCheck)
{
if(this->body.nonNull())
{
if(this->declared_return_type.nonNull())
{
const TypeRef body_type = this->body->type();
if(body_type.isNull()) // Will happen if body is a function expression bound to a newly concrete function that has not been type-checked yet.
throw ExceptionWithPosition("Type error for function '" + this->sig.toString() + "': Computed return type [Unknown] is not equal to the declared return type '" + this->declared_return_type->toString() + "'.", errorContext(*this));
// Check that the return type of the body expression is equal to the declared return type
// of this function.
if(*this->body->type() != *this->declared_return_type)
throw ExceptionWithPosition("Type error for function '" + this->sig.toString() + "': Computed return type '" + this->body->type()->toString() +
"' is not equal to the declared return type '" + this->declared_return_type->toString() + "'.", errorContext(*this));
}
else
{
// Else return type is NULL, so infer it
//this->return_type = this->body->type();
}
}
// If this is an anon func, add any types that it captures to the current set for the top-level function we are in.
if(this->is_anon_func)
{
for(auto it = free_variables.begin(); it != free_variables.end(); ++it)
{
payload.captured_types.insert((*it)->type());
}
}
if(stack.size() == 1)
{
assert(stack[0] == this);
// If this is a top-level func.
this->captured_var_types = payload.captured_types;
//std::cout << "captured var types for function " + this->sig.toString() + ": " << std::endl;
//for(auto i=captured_var_types.begin(); i != captured_var_types.end(); ++i)
// std::cout << (*i)->toString() << std::endl;
}
}
if(payload.operation == TraversalPayload::BindVariables)
{
if(this->built_in_func_impl.nonNull())
this->built_in_func_impl->linkInCalledFunctions(payload);
// NOTE: wtf is this code doing?
//this->captured_vars = payload.captured_vars;
//this->declared_return_type =
/*if(this->declared_return_type.nonNull() && this->declared_return_type->getType() == Type::FunctionType)
{
Function* ftype = static_cast<Function*>(this->declared_return_type.getPointer());
}*/
/*
Detecting function arguments that aren't referenced
===================================================
Do a pass over function body.
At end of pass,
if all variables are bound:
any argument that is not referenced is not used.
*/
/*if(payload.all_variables_bound)
{
for(size_t i=0; i<args.size(); ++i)
{
args[i].referenced = args[i].ref_count > 0;
}
}*/
}
if(payload.operation == TraversalPayload::TypeCoercion)
{
if(this->declared_return_type.nonNull() &&
this->declared_return_type->getType() == Type::FloatType &&
this->body.nonNull() &&
this->body->nodeType() == ASTNode::IntLiteralType)
{
IntLiteral* body_lit = static_cast<IntLiteral*>(this->body.getPointer());
if(isIntExactlyRepresentableAsFloat(body_lit->value))
{
ASTNodeRef new_body(new FloatLiteral((float)body_lit->value, body_lit->srcLocation()));
this->body = new_body;
payload.tree_changed = true;
}
}
else if(this->declared_return_type.nonNull() &&
this->declared_return_type->getType() == Type::DoubleType &&
this->body.nonNull() &&
this->body->nodeType() == ASTNode::IntLiteralType)
{
IntLiteral* body_lit = static_cast<IntLiteral*>(this->body.getPointer());
if(isIntExactlyRepresentableAsDouble(body_lit->value))
{
ASTNodeRef new_body(new DoubleLiteral((double)body_lit->value, body_lit->srcLocation()));
this->body = new_body;
payload.tree_changed = true;
}
}
}
else if(payload.operation == TraversalPayload::ComputeCanConstantFold)
{
const bool body_is_literal = checkFoldExpression(body, payload, stack);
this->can_maybe_constant_fold = body_is_literal;
}
else if(payload.operation == TraversalPayload::DeadFunctionElimination)
{
if(this->is_anon_func)
{
payload.reachable_nodes.insert(this);
}
if(this->built_in_func_impl.nonNull())
this->built_in_func_impl->deadFunctionEliminationTraverse(payload);
}
else if(payload.operation == TraversalPayload::DeadCodeElimination_ComputeAlive)
{
if(!this->is_anon_func) // if this is a top-level func:
{
while(!payload.nodes_to_process.empty())
{
ASTNode* n = payload.nodes_to_process.back();
payload.nodes_to_process.pop_back();
if(payload.processed_nodes.find(n) == payload.processed_nodes.end()) // If not already processed:
{
payload.processed_nodes.insert(n); // Mark node as processed.
//std::cout << "Processing node " << n << std::endl;
n->traverse(payload, stack); // stack will be wrong, but it shouldn't matter.
}
}
}
}
else if(payload.operation == TraversalPayload::AddAnonFuncsToLinker)
{
if(this->is_anon_func)
payload.linker->anon_functions_to_codegen.push_back(this);
}
stack.pop_back();
payload.func_def_stack.pop_back();
}
void FunctionDefinition::updateChild(const ASTNode* old_val, ASTNodeRef& new_val)
{
assert(body.ptr() == old_val);
this->body = new_val;
}
void FunctionDefinition::print(int depth, std::ostream& s) const
{
printMargin(depth, s);
s << "FunctionDef (" + toHexString((uint64)this) + "): " << this->sig.toString() << " " <<
(this->returnType().nonNull() ? this->returnType()->toString() : "[Unknown ret type]");
if(this->declared_return_type.nonNull())
s << " (Declared ret type: " + this->declared_return_type->toString() << ")";
s << "\n";
if(this->built_in_func_impl.nonNull())
{
printMargin(depth+1, s);
s << "Built in Implementation.\n";
}
else if(body.nonNull())
{
body->print(depth+1, s);
}
else
{
printMargin(depth+1, s);
s << "Null body.\n";
}
}
std::string FunctionDefinition::sourceString(int depth) const
{
std::string s;
if(is_anon_func)
{
s += "\\";
}
else
{
s += "def " + sig.name;
}
if(!generic_type_param_names.empty())
{
s += "<";
s += StringUtils::join(generic_type_param_names, ", ");
s += ">";
}
s += "(";
for(unsigned int i=0; i<args.size(); ++i)
{
s += args[i].type->toString() + " " + args[i].name;
if(i + 1 < args.size())
s += ", ";
}
s += ") ";
// Write function attributes, if present
if(this->noinline)
s += "!noinline ";
if(this->opencl_noinline)
s += "!opencl_noinline ";
if(this->declared_return_type.nonNull())
s += this->declared_return_type->toString() + " ";
s += ": ";
if(body.isNull())
{
if(built_in_func_impl.nonNull())
return s + " [Built-in]";
else if(external_function.nonNull())
return s + " [External]";
else
return s + " [NULL BODY]";
}
else
return s + body->sourceString(depth + 1);
}
// Depending on the argument type, will return something like
// const SomeStruct* const arg_name
// or
// const int arg_name
std::string FunctionDefinition::openCLCArgumentCode(EmitOpenCLCodeParams& params, const TypeVRef& arg_type, const std::string& arg_name)
{
if(arg_type->OpenCLPassByPointer())
return "const " + arg_type->address_space + " " + arg_type->OpenCLCType(params) + "* const " + mapOpenCLCVarName(params.opencl_c_keywords, arg_name);
else
return "const " + arg_type->OpenCLCType(params) + " " + mapOpenCLCVarName(params.opencl_c_keywords, arg_name);
}
std::string FunctionDefinition::emitOpenCLC(EmitOpenCLCodeParams& params) const
{
assert(returnType().nonNull());
// Emit forwards declaration to file scope code:
std::string opencl_sig = this->returnType()->OpenCLCType(params) + " ";
opencl_sig += sig.typeMangledName() + "(";
for(unsigned int i=0; i<args.size(); ++i)
{
opencl_sig += openCLCArgumentCode(params, args[i].type, args[i].name);
if(i + 1 < args.size())
opencl_sig += ", ";
}
if(is_anon_func)
{
if(args.size() >= 1) opencl_sig += ", ";
opencl_sig += openCLCArgumentCode(params, getCapturedVariablesStructType(), "cap_var_struct");
}
opencl_sig += ")";
params.file_scope_code += opencl_sig + ";\n";
// Emit function definition
std::string s = opencl_sig + "\n{\n";
// Emit body expression
params.blocks.push_back("");
const std::string body_expr = body->emitOpenCLC(params);
StringUtils::appendTabbed(s, params.blocks.back(), (int)params.blocks.size());
params.blocks.pop_back();
// If the body expression is just an argument, and it is pass by pointer, then it will need to be dereferenced.
if((body->nodeType() == ASTNode::VariableASTNodeType) && (body.downcastToPtr<Variable>()->binding_type == Variable::BindingType_Argument) && body->type()->OpenCLPassByPointer())
s += "\treturn *" + body_expr + ";\n";// Deref
else
s += "\treturn " + body_expr + ";\n";
s += "}\n";
return s;
}
llvm::Value* FunctionDefinition::emitLLVMCode(EmitLLVMCodeParams& params, llvm::Value* ret_space_ptr) const
{
// This will be called for lambda expressions.
// We want to return a function closure, which is allocated on the heap (usually) and contains a function pointer to the anonymous function,
// a structure containing the captured variables, etc..
params.stats->num_closure_allocations++;
TypeRef this_function_type = this->type();
assert(this_function_type.isType<Function>());
llvm::Type* func_ptr_type = LLVMTypeUtils::pointerType(this_function_type.downcastToPtr<Function>()->functionLLVMType(*params.module));
/////////////////////// Get closure destructor type ///////////////
llvm::Type* destructor_arg_types[1] = { LLVMTypeUtils::getPtrToBaseCapturedVarStructType(*params.module) };
llvm::FunctionType* destructor_type = llvm::FunctionType::get(
llvm::Type::getVoidTy(params.module->getContext()), // return type
destructor_arg_types,
false // varargs
);
/////////////////////// Get full captured var struct type ///////////////
const StructureTypeRef captured_var_struct_type = this->getCapturedVariablesStructType();
llvm::Type* cap_var_type_ = captured_var_struct_type->LLVMType(*params.module);
assert(cap_var_type_->isStructTy());
llvm::StructType* cap_var_type = static_cast<llvm::StructType*>(cap_var_type_);
///////////////// Create full closure type //////////////////////////////
// NOTE: the number and type of captured variables depends on the call site, so isn't actually reflected in the function type.
llvm::Type* closure_field_types[] = {
llvm::Type::getInt64Ty(*params.context), // Int 64 reference count
llvm::Type::getInt64Ty(*params.context), // flags
func_ptr_type,
LLVMTypeUtils::pointerType(destructor_type),
cap_var_type
};
llvm::StructType* closure_type = llvm::StructType::create(
*params.context,
#if TARGET_LLVM_VERSION >= 150
closure_field_types,
#else
llvm::makeArrayRef(closure_field_types),
#endif
this->sig.typeMangledName() + "_closure"
);
//////////////// Compute size of complete closure type /////////////////////////
const llvm::StructLayout* layout = params.target_data->getStructLayout(closure_type);
const uint64_t struct_size_B = layout->getSizeInBytes();
const bool alloc_on_heap = mayEscapeCurrentlyBuildingFunction(params, this->type());
llvm::Value* closure_pointer;
uint64 initial_flags;
if(alloc_on_heap)
{
params.stats->num_heap_allocation_calls++;
// Get pointer to allocateClosureFunc() function.
llvm::Function* alloc_closure_func = params.common_functions.allocateClosureFunc->getOrInsertFunction(params.module);
llvm::Value* alloc_closure_func_args[] = { llvm::ConstantInt::get(*params.context, llvm::APInt(64, struct_size_B, true)) };
// Call our allocateClosureFunc function
llvm::CallInst* alloc_closure_func_call = params.builder->CreateCall(alloc_closure_func, alloc_closure_func_args, "base_closure_ptr");
addMetaDataCommentToInstruction(params, alloc_closure_func_call, "alloc closure for " + this->sig.typeMangledName());
llvm::Value* closure_void_pointer = alloc_closure_func_call;
// Cast the pointer returned from the alloc_closure_func, from dummy closure type to the actual closure type.
closure_pointer = params.builder->CreateBitCast(
closure_void_pointer,
LLVMTypeUtils::pointerType(*closure_type),
"closure_pointer"
);
initial_flags = 1; // flag = 1 = heap allocated
}
else
{
// Emit the alloca in the entry block for better code-gen.
// We will emit the alloca at the start of the block, so that it doesn't go after any terminator instructions already created which have to be at the end of the block.
llvm::IRBuilder<> entry_block_builder(¶ms.currently_building_func->getEntryBlock(), params.currently_building_func->getEntryBlock().getFirstInsertionPt());
llvm::Value* alloca_ptr = entry_block_builder.CreateAlloca(
closure_type, // byte
llvm::ConstantInt::get(*params.context, llvm::APInt(64, 1, true)), // array size
"closure"
);
closure_pointer = alloca_ptr;
initial_flags = 0; // flag = 0 = not heap allocated
}
// Capture variables at this point, by getting them off the arg and let stack.
//TEMP: this needs to be in sync with Function::LLVMType()
/*const bool simple_func_ptr = false;
if(simple_func_ptr)
{
llvm::Function* func = this->getOrInsertFunction(
params.module,
false // use_cap_var_struct_ptr: Since we're storing a func ptr, it will be passed the captured var struct on usage.
);
return func;
}*/
/////////////////// Create function pointer type /////////////////////
// Build vector of function args
/*vector<llvm::Type*> llvm_arg_types(this->args.size());
for(size_t i=0; i<this->args.size(); ++i)
llvm_arg_types[i] = this->args[i].type->LLVMType(*params.module);
// Add Pointer to captured var struct, if there are any captured vars
//TEMP since we are returning a closure, the functions will always be passed captured vars. if(use_captured_vars)
llvm_arg_types.push_back(LLVMTypeUtils::getPtrToBaseCapturedVarStructType(*params.module));
// Add hidden void* arg NOTE: should only do this when hidden_void_arg is true.
// llvm_arg_types.push_back(LLVMTypeUtils::voidPtrType(*params.context));
// Construct the function pointer type
llvm::Type* func_ptr_type = LLVMTypeUtils::pointerType(*llvm::FunctionType::get(
this->returnType()->LLVMType(*params.module), // result type
llvm_arg_types,
false // is var arg
));*/
// Set the reference count in the closure to 1
llvm::Value* closure_ref_count_ptr = LLVMUtils::createStructGEP(params.builder, closure_pointer, 0, closure_type, "closure_ref_count_ptr");
llvm::Value* one = llvm::ConstantInt::get(*params.context, llvm::APInt(64, 1, /*signed=*/true));
llvm::StoreInst* store_inst = params.builder->CreateStore(one, closure_ref_count_ptr);
addMetaDataCommentToInstruction(params, store_inst, "Set initial ref count to 1");
// Set the flags
llvm::Value* flags_ptr = LLVMUtils::createStructGEP(params.builder, closure_pointer, 1, closure_type, "closure_flags_ptr");
llvm::Value* flags_contant_val = llvm::ConstantInt::get(*params.context, llvm::APInt(64, initial_flags));
llvm::StoreInst* store_flags_inst = params.builder->CreateStore(flags_contant_val, flags_ptr);
addMetaDataCommentToInstruction(params, store_flags_inst, "set initial flags to " + toString(initial_flags));
// Store function pointer to the anon function in the closure structure
{
llvm::Function* func = this->getOrInsertFunction(
params.module,
true // use_cap_var_struct_ptr: Since we're storing a func ptr, it will be passed the captured var struct on usage.
);
llvm::Value* func_field_ptr = LLVMUtils::createStructGEP(params.builder, closure_pointer, Function::functionPtrIndex(), closure_type, "function_field_ptr"); // NOTE: func->getType() correct? or should be pointerType(xx)?
llvm::StoreInst* store_inst_ = params.builder->CreateStore(func, func_field_ptr); // Do the store.
addMetaDataCommentToInstruction(params, store_inst_, "Store function pointer in closure");
}
// Store captured vars in closure.
llvm::Value* captured_var_struct_ptr = LLVMUtils::createStructGEP(params.builder, closure_pointer, Function::capturedVarStructIndex(), closure_type, "captured_var_struct_ptr");
llvm::Type* base_captured_var_llvm_type = this->getCapturedVariablesStructType()->LLVMStructType(*params.module); //LLVMTypeUtils::getBaseCapturedVarStructType(*params.module);
const auto unique_free_vars = this->getUniqueFreeVarList();
params.stats->num_free_vars_stored += unique_free_vars.size();
size_t free_var_index = 0;
for(auto z = unique_free_vars.begin(); z != unique_free_vars.end(); ++z) // for each captured var
{
Variable* free_var = *z;
TypeVRef cap_var_type_win(free_var->type());
llvm::Value* val = NULL;
// If this free variable is free in more than one lambda, we will need to get the captured value from the captured-val struct of the outer lambda.
// We want the next-most tightly enclosing lambda as the current lambda.
const FunctionDefinition* free_in_looser_lambda = NULL;
bool found_this_lambda = false;
for(int q=(int)free_var->enclosing_lambdas.size()-1; q >= 0; --q) // From inner to outer lambda:
{
const FunctionDefinition* func = free_var->enclosing_lambdas[q];
if(func == this)
found_this_lambda = true;
else if(found_this_lambda)
{
if(func->free_variables.count(free_var) > 0)
{
free_in_looser_lambda = func;
break;
}
}
}
if(free_in_looser_lambda)
{
// This captured var is bound to a captured var itself.
// The target captured var is in the captured var struct for the function, which is passed as the last arg to the function body.
llvm::Value* base_current_func_captured_var_struct = LLVMUtils::getLastArg(params.currently_building_func);
// Now we need to downcast it to the correct type.
llvm::Type* actual_cap_var_struct_type = params.currently_building_func_def->getCapturedVariablesStructType()->LLVMType(*params.module);
llvm::Value* current_func_captured_var_struct = params.builder->CreateBitCast(base_current_func_captured_var_struct, LLVMTypeUtils::pointerType(actual_cap_var_struct_type), "actual_cap_var_struct_type");
const size_t free_index = free_in_looser_lambda->getFreeIndexForVar(free_var);
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, current_func_captured_var_struct, (unsigned int)free_index, actual_cap_var_struct_type);
val = LLVMUtils::createLoad(params.builder, field_ptr, cap_var_type_win, params.module);
}
else if(free_var->binding_type == Variable::BindingType_Argument)
{
// Load arg
val = LLVMUtils::getNthArg(
params.currently_building_func,
params.currently_building_func_def->getLLVMArgIndex(free_var->arg_index)
);
}
else if(free_var->binding_type == Variable::BindingType_Let)
{
// Load let:
LetASTNode* let_node = free_var->bound_let_node;
assert(params.let_values.find(let_node) != params.let_values.end());
val = params.let_values[let_node];
// NOTE: This code is duplicated from Variable. de-duplicate.
if(let_node->vars.size() > 1)
{
// Destructuring assignment, we just want to return the individual tuple element.
// Value should be a pointer to a tuple struct.
if(cap_var_type_win->passByValue())
{
llvm::Value* tuple_elem_ptr = LLVMUtils::createStructGEP(params.builder, val, free_var->let_var_index, cap_var_type_win->LLVMType(*params.module), "tuple_elem_ptr");
llvm::Value* tuple_elem = LLVMUtils::createLoad(params.builder, tuple_elem_ptr, cap_var_type_win, params.module);
val = tuple_elem;
}
else
{
llvm::Value* tuple_elem = LLVMUtils::createStructGEP(params.builder, val, free_var->let_var_index, cap_var_type_win->LLVMType(*params.module), "tuple_elem_ptr");
val = tuple_elem;
}
}
}
else
{
assert(0);
}
// store in captured var structure field
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, captured_var_struct_ptr, (unsigned int)free_var_index, base_captured_var_llvm_type, "captured_var_" + toString(free_var_index) + "_field_ptr");
if(cap_var_type_win->passByValue())
{
llvm::StoreInst* store_inst_ = params.builder->CreateStore(val, field_ptr);
addMetaDataCommentToInstruction(params, store_inst_, "Store captured var " + toString(free_var_index) + " in closure");
}
else
{
// For pass-by-pointer types (structures for example), val is just a pointer, and we need to load the structure and then store it in the closure.
LLVMUtils::createCollectionCopy(cap_var_type_win, /*dest ptr=*/field_ptr, /*src ptr=*/val, params);
}
// If the captured var is a ref-counted type, we need to increment its reference count, since the struct now holds a reference to it.
captured_var_struct_type->component_types[free_var_index]->emitIncrRefCount(params, val, "Capture var ref count increment");
free_var_index++;
}
// Emit a destructor function for this closure.
// Will be something like (C++ equiv):
// void anon_func_xx_captured_var_struct_destructor(base_captured_var_struct* s)
{
const std::string destructor_name = this->sig.typeMangledName() + toHexString((uint64)this) + "_captured_var_struct_destructor";
assert(params.module->getFunction(destructor_name) == NULL);
llvm::Function* destructor = LLVMUtils::getFunctionFromModule(
params.module,
destructor_name, // Name
destructor_type // Type
);
llvm::BasicBlock* block = llvm::BasicBlock::Create(params.module->getContext(), "entry", destructor);
llvm::IRBuilder<> builder(block);
// Get zeroth arg to func
llvm::Value* base_captured_var_struct = LLVMUtils::getNthArg(destructor, 0);
// Downcast to known actual captured var struct type.
// Bitcast the closure pointer down to the 'base' closure type.
llvm::Value* actual_captured_var_struct = builder.CreateBitCast(
base_captured_var_struct, // value
LLVMTypeUtils::pointerType(cap_var_type), // dest type
"actual_captured_var_struct"
);
// Emit a call to the destructor for this captured var struct, if it has one.
EmitLLVMCodeParams temp_params = params;
temp_params.builder = &builder;
captured_var_struct_type->emitDestructorCall(temp_params, actual_captured_var_struct, "captured var struct destructor call");
builder.CreateRetVoid(); // Finish the destructor function
// Store a pointer to the destructor in the closure.
llvm::Value* closure_destr_ptr_ptr = LLVMUtils::createStructGEP(params.builder,
closure_pointer,
Function::destructorPtrIndex(),
closure_type,
"destructor ptr"
);
llvm::StoreInst* store_inst_ = params.builder->CreateStore(destructor, closure_destr_ptr_ptr);
addMetaDataCommentToInstruction(params, store_inst_, "Store destructor in closure");
}
// Bitcast the full closure pointer down to the 'base' closure type.
llvm::Type* base_closure_type = this->type()->LLVMType(*params.module);
return params.builder->CreateBitCast(
closure_pointer,
base_closure_type,
"base_closure_ptr"
);
}
llvm::Function* FunctionDefinition::getOrInsertFunction(
llvm::Module* module
) const
{
return getOrInsertFunction(module, false);
}
static void setArgumentAttributes(llvm::LLVMContext* context, llvm::Function::arg_iterator it, unsigned int index, llvm::AttrBuilder& attr_builder)
{
it->addAttrs(attr_builder);
}
llvm::Function* FunctionDefinition::getOrInsertFunction(
llvm::Module* module,