-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBuiltInFunctionImpl.cpp
More file actions
5018 lines (3840 loc) · 173 KB
/
BuiltInFunctionImpl.cpp
File metadata and controls
5018 lines (3840 loc) · 173 KB
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
#include "BuiltInFunctionImpl.h"
#include "VMState.h"
#include "VirtualMachine.h"
#include "Value.h"
#include "wnt_Type.h"
#include "wnt_ASTNode.h"
#include "wnt_FunctionDefinition.h"
#include "wnt_FunctionExpression.h"
#include "wnt_RefCounting.h"
#include <vector>
#include "LLVMUtils.h"
#include "LLVMTypeUtils.h"
#include "utils/PlatformUtils.h"
#include "utils/StringUtils.h"
#include "utils/TaskManager.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/IR/Attributes.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>
#if TARGET_LLVM_VERSION >= 110
#include <llvm/IR/IntrinsicsX86.h> // New for ~11.0
#endif
#ifdef _MSC_VER
#pragma warning(pop) // Re-enable warnings
#endif
using std::vector;
namespace Winter
{
//----------------------------------------------------------------------------------------------
class CreateLoopBodyCallBack
{
public:
virtual ~CreateLoopBodyCallBack(){}
virtual llvm::Value* emitLoopBody(llvm::IRBuilder<>& Builder, llvm::Module* module, /*llvm::Value* loop_value_var, */llvm::Value* loop_iter_val) = 0;
};
/*
Make a for loop.
PreheaderBB
--------------
jump to condition_BB
condition_BB
------------
cond = compute condition
cond branch(cond, loop_body_BB, after_BB)
loop_body_BB
-------------
do loop body
increment loop index var
jump to condition BB
after_BB
---------
*/
static void makeForLoop(llvm::IRBuilder<>& builder, llvm::Module* module, llvm::Value* begin_index, llvm::Value* end_index, CreateLoopBodyCallBack* create_loop_body_callback)
{
// Make the new basic block for the loop header, inserting after current block.
llvm::Function* current_func = builder.GetInsertBlock()->getParent();
llvm::BasicBlock* preheader_BB = builder.GetInsertBlock();
llvm::BasicBlock* condition_BB = llvm::BasicBlock::Create(module->getContext(), "condition", current_func);
llvm::BasicBlock* loop_body_BB = llvm::BasicBlock::Create(module->getContext(), "loop_body", current_func);
llvm::BasicBlock* after_BB = llvm::BasicBlock::Create(module->getContext(), "after_loop", current_func);
builder.SetInsertPoint(preheader_BB);
// Insert an explicit fall through from the current block to the condition_BB.
builder.CreateBr(condition_BB);
//============================= condition_BB ================================
builder.SetInsertPoint(condition_BB);
// Create loop index (i) variable phi node
llvm::PHINode* loop_index_var = builder.CreatePHI(llvm::Type::getInt64Ty(module->getContext()), 2, "loop_index_var");
loop_index_var->addIncoming(begin_index, preheader_BB);
// Compute the end condition.
llvm::Value* end_cond = builder.CreateICmpNE(end_index, loop_index_var, "loopcond");
// Insert the conditional branch
builder.CreateCondBr(end_cond, loop_body_BB, after_BB);
//============================= loop_body_BB ================================
builder.SetInsertPoint(loop_body_BB);
// TODO: deal with result?
create_loop_body_callback->emitLoopBody(builder, module, loop_index_var);
llvm::Value* one = llvm::ConstantInt::get(module->getContext(), llvm::APInt(64, 1));
llvm::Value* next_var = builder.CreateAdd(loop_index_var, one, "next_var");
// Add a new entry to the PHI node for the backedge.
loop_index_var->addIncoming(next_var, loop_body_BB);
// Do jump back to condition basic block
builder.CreateBr(condition_BB);
//============================= after_BB ================================
builder.SetInsertPoint(after_BB);
}
#if 0
static llvm::Value* makeForLoop(llvm::IRBuilder<>& builder, llvm::Module* module, llvm::Value* begin_index, llvm::Value* end_index, llvm::Type* loop_value_type, /*llvm::Value* initial_value, */
CreateLoopBodyCallBack* create_loop_body_callback)
{
// Make the new basic block for the loop header, inserting after current
// block.
llvm::Function* TheFunction = Builder.GetInsertBlock()->getParent();
llvm::BasicBlock* PreheaderBB = Builder.GetInsertBlock();
llvm::BasicBlock* LoopBB = llvm::BasicBlock::Create(module->getContext(), "loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
Builder.CreateBr(LoopBB);
// Start insertion in LoopBB.
Builder.SetInsertPoint(LoopBB);
// Create loop index (i) variable phi node
llvm::PHINode* loop_index_var = Builder.CreatePHI(llvm::Type::getInt64Ty(module->getContext()), 2, "loop_index_var");
//llvm::Value* initial_loop_index_value = llvm::ConstantInt::get(*params.context, llvm::APInt(64, 0)); // Initial induction loop index value: Zero
loop_index_var->addIncoming(begin_index, PreheaderBB);
// Create loop body/value variable phi node
//llvm::PHINode* loop_value_var = Builder.CreatePHI(loop_value_type, 2, "loop_value_var");
//loop_value_var->addIncoming(initial_value, PreheaderBB);
// Emit the body of the loop.
llvm::Value* updated_value = create_loop_body_callback->emitLoopBody(Builder, module, /*loop_value_var, */loop_index_var);
// Create increment of loop index
llvm::Value* step_val = llvm::ConstantInt::get(module->getContext(), llvm::APInt(64, 1));
llvm::Value* next_var = Builder.CreateAdd(loop_index_var, step_val, "next_var");
// Compute the end condition.
llvm::Value* end_value = end_index; // llvm::ConstantInt::get(*params.context, llvm::APInt(32, num_iterations));//TEMP HACK
llvm::Value* end_cond = Builder.CreateICmpNE(
end_value,
next_var,
"loopcond"
);
// Create the "after loop" block and insert it.
llvm::BasicBlock* LoopEndBB = Builder.GetInsertBlock();
llvm::BasicBlock* AfterBB = llvm::BasicBlock::Create(module->getContext(), "afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
Builder.CreateCondBr(end_cond, LoopBB, AfterBB);
// Any new code will be inserted in AfterBB.
Builder.SetInsertPoint(AfterBB);
// Add a new entry to the PHI node for the backedge.
loop_index_var->addIncoming(next_var, LoopEndBB);
//loop_value_var->addIncoming(updated_value, LoopEndBB);
return updated_value;
}
#endif
//----------------------------------------------------------------------------------------------
Constructor::Constructor(VRef<StructureType>& struct_type_)
: BuiltInFunctionImpl(BuiltInType_Constructor),
struct_type(struct_type_)
{
}
ValueRef Constructor::invoke(VMState& vmstate)
{
vector<ValueRef> field_values(this->struct_type->component_names.size());
const size_t func_args_start = vmstate.func_args_start.back();
for(unsigned int i=0; i<this->struct_type->component_types.size(); ++i)
field_values[i] = vmstate.argument_stack[func_args_start + i];
return new StructureValue(field_values);
}
llvm::Value* Constructor::emitLLVMCode(EmitLLVMCodeParams& params) const
{
if(this->struct_type->passByValue())
{
// Structs are not passed by value
assert(0);
llvm::Value* s = llvm::UndefValue::get(this->struct_type->LLVMType(*params.module));
for(unsigned int i=0; i<this->struct_type->component_types.size(); ++i)
{
llvm::Value* arg_value = LLVMUtils::getNthArg(params.currently_building_func, i);
s = params.builder->CreateInsertValue(
s,
arg_value,
i
);
}
return s;
}
else
{
// Pointer to structure memory will be in 0th argument.
llvm::Value* struct_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
// For each field in the structure
for(unsigned int i=0; i<this->struct_type->component_types.size(); ++i)
{
// Get the pointer to the structure field.
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, struct_ptr, i, this->struct_type->LLVMType(*params.module));
llvm::Value* arg_value_or_ptr = LLVMUtils::getNthArg(params.currently_building_func, i + 1);
if(this->struct_type->component_types[i]->passByValue())
{
params.builder->CreateStore(arg_value_or_ptr, field_ptr);
}
else
{
LLVMUtils::createCollectionCopy(
this->struct_type->component_types[i],
field_ptr, // dest ptr
arg_value_or_ptr, // src ptr
params
);
}
// If the field is a ref-counted type, we need to increment its reference count, since the newly constructed struct now holds a reference to it.
// (and to compensate for the decrement of the argument in the function application code)
this->struct_type->component_types[i]->emitIncrRefCount(params, arg_value_or_ptr, "Constructor::emitLLVMCode() for type " + this->struct_type->toString());
}
return NULL;
}
}
size_t Constructor::getTimeBound(GetTimeBoundParams& params) const
{
return struct_type->component_types.size(); // Copy time
}
GetSpaceBoundResults Constructor::getSpaceBound(GetSpaceBoundParams& params) const
{
// TEMP HACK work out properly
return GetSpaceBoundResults(0, this->struct_type->memSize());
}
//------------------------------------------------------------------------------------
ValueRef GetField::invoke(VMState& vmstate)
{
const size_t func_args_start = vmstate.func_args_start.back();
// Top param on arg stack should be a structure
const StructureValue* s = checkedCast<const StructureValue>(vmstate.argument_stack[func_args_start].getPointer());
assert(this->index < s->fields.size());
return s->fields[this->index];
}
llvm::Value* GetField::emitLLVMCode(EmitLLVMCodeParams& params) const
{
if(this->struct_type->passByValue())
{
return params.builder->CreateExtractValue(
LLVMUtils::getNthArg(params.currently_building_func, 0),
this->index,
this->struct_type->component_names[this->index] // name
);
}
else
{
const TypeVRef field_type = this->struct_type->component_types[this->index];
const std::string field_name = this->struct_type->component_names[this->index];
if(field_type->passByValue())
{
// Pointer to structure will be in 0th argument.
llvm::Value* struct_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, struct_ptr, this->index, this->struct_type->LLVMType(*params.module), field_name + " ptr");
llvm::Value* loaded_val = LLVMUtils::createLoad(params,
field_ptr,
field_type,
field_name // name
);
// TEMP NEW: increment ref count if this is a string
//if(field_type->getType() == Type::StringType)
// RefCounting::emitIncrementStringRefCount(params, loaded_val);
return loaded_val;
}
else
{
// Pointer to memory for return value will be 0th argument.
llvm::Value* return_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
// Pointer to structure will be in 1st argument.
llvm::Value* struct_ptr = LLVMUtils::getNthArg(params.currently_building_func, 1);
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, struct_ptr, this->index, this->struct_type->LLVMType(*params.module), field_name + " ptr");
LLVMUtils::createCollectionCopy(
field_type,
return_ptr, // dest ptr
field_ptr, // src ptr
params
);
return NULL;
}
}
}
size_t GetField::getTimeBound(GetTimeBoundParams& params) const
{
return 1;
}
GetSpaceBoundResults GetField::getSpaceBound(GetSpaceBoundParams& params) const
{
const TypeVRef field_type = this->struct_type->component_types[this->index];
// TEMP HACK TODO: work out properly
return GetSpaceBoundResults(0, field_type->memSize());
}
//------------------------------------------------------------------------------------
UpdateElementBuiltInFunc::UpdateElementBuiltInFunc(const TypeVRef& collection_type_)
: BuiltInFunctionImpl(BuiltInType_UpdateElementBuiltInFunc),
collection_type(collection_type_)
{}
// def update(CollectionType c, int index, T newval) CollectionType
ValueRef UpdateElementBuiltInFunc::invoke(VMState& vmstate)
{
const size_t func_args_start = vmstate.func_args_start.back();
//const Value* collection = vmstate.argument_stack[func_args_start].getPointer();
const IntValue* inv_val = checkedCast<const IntValue>(vmstate.argument_stack[func_args_start + 1].getPointer());
const int64 index = inv_val->value;
const ValueRef newval = vmstate.argument_stack[func_args_start + 2];
if(collection_type->getType() == Type::ArrayTypeType)
{
const ArrayValue* array_val = checkedCast<const ArrayValue>(vmstate.argument_stack[func_args_start]);
if(index < 0 || index >= (int64)array_val->e.size())
throw BaseException("Index out of bounds");
ArrayValue* new_collection = new ArrayValue();
new_collection->e.resize(array_val->e.size());
for(unsigned int i=0; i<array_val->e.size(); ++i)
new_collection->e[i] = array_val->e[i];
new_collection->e[index] = newval;
return new_collection;
}
else
{
// TODO: handle other types.
throw BaseException("UpdateElementBuiltInFunc::invoke: invalid type");
}
}
// def update(CollectionType c, int index, T newval) CollectionType
llvm::Value* UpdateElementBuiltInFunc::emitLLVMCode(EmitLLVMCodeParams& params) const
{
if(collection_type->getType() == Type::ArrayTypeType)
{
// Pointer to memory for return value will be 0th argument.
llvm::Value* return_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
// Pointer to structure will be in 1st argument.
llvm::Value* struct_ptr = LLVMUtils::getNthArg(params.currently_building_func, 1);
// Index will be in 2nd argument.
llvm::Value* index = LLVMUtils::getNthArg(params.currently_building_func, 2);
// New val will be in 3rd argument. TEMP: assuming pass by value.
llvm::Value* newval = LLVMUtils::getNthArg(params.currently_building_func, 3);
// Copy old collection to new collection
// llvm::Value* collection_val = params.builder->CreateLoad(struct_ptr, "collection val");
// params.builder->CreateStore(collection_val, return_ptr);
llvm::Value* size = llvm::ConstantInt::get(*params.context, llvm::APInt(32, sizeof(int) * collection_type.downcast<ArrayType>()->num_elems, true)); // TEMP HACK
LLVMUtils::createMemCpy(params.builder, return_ptr, struct_ptr, size, 4);
// Update element with new val
llvm::Value* indices[] = {
llvm::ConstantInt::get(*params.context, llvm::APInt(32, 0)), // get the zero-th array
index // get the indexed element in the array
};
llvm::Value* new_elem_ptr = LLVMUtils::createInBoundsGEP(*params.builder, return_ptr, collection_type.downcastToPtr<ArrayType>()->LLVMType(*params.module), indices);//params.builder->CreateInBoundsGEP(return_ptr, indices, "new elem ptr");
params.builder->CreateStore(newval, new_elem_ptr);
}
return NULL;
}
size_t UpdateElementBuiltInFunc::getTimeBound(GetTimeBoundParams& params) const
{
throw BaseException("UpdateElementBuiltInFunc::getTimeBound: unimplemented");
}
GetSpaceBoundResults UpdateElementBuiltInFunc::getSpaceBound(GetSpaceBoundParams& params) const
{
throw BaseException("UpdateElementBuiltInFunc::getTimeBound: unimplemented");
}
//------------------------------------------------------------------------------------
ValueRef GetTupleElementBuiltInFunc::invoke(VMState& vmstate)
{
const size_t func_args_start = vmstate.func_args_start.back();
// Top param on arg stack should be a tuple
const TupleValue* s = checkedCast<const TupleValue>(vmstate.argument_stack[func_args_start].getPointer());
if(index >= s->e.size())
throw BaseException("Index out of bounds");
return s->e[this->index];
}
llvm::Value* GetTupleElementBuiltInFunc::emitLLVMCode(EmitLLVMCodeParams& params) const
{
if(this->tuple_type->passByValue())
{
assert(0);
//return params.builder->CreateExtractValue(
// LLVMUtils::getNthArg(params.currently_building_func, 0),
// this->index,
// this->tuple_type->component_names[this->index] // name
//);
return NULL;
}
else
{
const TypeVRef field_type = this->tuple_type->component_types[this->index];
const std::string field_name = "field " + ::toString(this->index);
if(field_type->passByValue())
{
// Pointer to structure will be in 0th argument.
llvm::Value* struct_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, struct_ptr, this->index, this->tuple_type->LLVMType(*params.module), field_name + " ptr");
//llvm::Value* loaded_val = params.builder->CreateLoad(
// field_ptr,
// field_name // name
//);
llvm::Value* loaded_val = LLVMUtils::createLoad(params.builder, field_ptr, field_type, params.module, field_name);
// TEMP NEW: increment ref count if this is a string
//if(field_type->getType() == Type::StringType)
// RefCounting::emitIncrementStringRefCount(params, loaded_val);
return loaded_val;
}
else
{
// Pointer to memory for return value will be 0th argument.
llvm::Value* return_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
// Pointer to structure will be in 1st argument.
llvm::Value* struct_ptr = LLVMUtils::getNthArg(params.currently_building_func, 1);
llvm::Value* field_ptr = LLVMUtils::createStructGEP(params.builder, struct_ptr, this->index, this->tuple_type->LLVMType(*params.module), field_name + " ptr");
LLVMUtils::createCollectionCopy(
field_type,
return_ptr, // dest ptr
field_ptr, // src ptr
params
);
return NULL;
}
}
}
size_t GetTupleElementBuiltInFunc::getTimeBound(GetTimeBoundParams& params) const
{
return 1;
}
GetSpaceBoundResults GetTupleElementBuiltInFunc::getSpaceBound(GetSpaceBoundParams& params) const
{
const TypeVRef field_type = this->tuple_type->component_types[this->index];
// TEMP HACK TODO: work out properly
return GetSpaceBoundResults(0, field_type->memSize());
}
//------------------------------------------------------------------------------------
ValueRef GetVectorElement::invoke(VMState& vmstate)
{
const size_t func_args_start = vmstate.func_args_start.back();
const VectorValue* vec = checkedCast<const VectorValue>(vmstate.argument_stack[func_args_start].getPointer());
if(this->index >= vec->e.size())
throw BaseException("Index out of bounds");
return vec->e[this->index];
}
llvm::Value* GetVectorElement::emitLLVMCode(EmitLLVMCodeParams& params) const
{
llvm::Value* vec_value = NULL;
if(true) // TEMP shouldPassByValue(*this->type()))
{
vec_value = LLVMUtils::getNthArg(
params.currently_building_func,
0
);
}
else
{
vec_value = LLVMUtils::createLoad(params.builder,
LLVMUtils::getNthArg(params.currently_building_func, 0),
vector_type->elem_type,//false, // true,// TEMP: volatile = true to pick up returned vector);
params.module,
"argument" // name
);
}
return params.builder->CreateExtractElement(
vec_value, // vec
llvm::ConstantInt::get(*params.context, llvm::APInt(32, this->index))
);
}
size_t GetVectorElement::getTimeBound(GetTimeBoundParams& params) const
{
return 1;
}
GetSpaceBoundResults GetVectorElement::getSpaceBound(GetSpaceBoundParams& params) const
{
return GetSpaceBoundResults(0, 0);
}
//------------------------------------------------------------------------------------
void ArrayMapBuiltInFunc::specialiseForFunctionArg(FunctionDefinition* f)
{
specialised_f = f;
}
ValueRef ArrayMapBuiltInFunc::invoke(VMState& vmstate)
{
const size_t func_args_start = vmstate.func_args_start.back();
const FunctionValue* f = checkedCast<const FunctionValue>(vmstate.argument_stack[func_args_start].getPointer());
const ArrayValue* from = checkedCast<const ArrayValue>(vmstate.argument_stack[func_args_start + 1].getPointer());
ArrayValueRef retval = new ArrayValue();
retval->e.resize(from->e.size());
for(unsigned int i=0; i<from->e.size(); ++i)
{
// Set up arg stack
vmstate.func_args_start.push_back((unsigned int)vmstate.argument_stack.size());
vmstate.argument_stack.push_back(from->e[i]); // Push value arg
retval->e[i] = f->func_def->invoke(vmstate);
vmstate.argument_stack.pop_back(); // Pop Value arg
vmstate.func_args_start.pop_back();
}
return retval;
}
class ArrayMapBuiltInFunc_CreateLoopBodyCallBack : public CreateLoopBodyCallBack
{
public:
virtual llvm::Value* emitLoopBody(llvm::IRBuilder<>& builder, llvm::Module* module, /*llvm::Value* loop_value_var, */llvm::Value* i)
{
// Load element from input array
llvm::Value* indices[] = {
llvm::ConstantInt::get(module->getContext(), llvm::APInt(64, 0)), // get the zero-th array
i // get the indexed element in the array
};
llvm::Value* elem_ptr = LLVMUtils::createInBoundsGEP(builder, input_array, array_llvm_type, indices);
llvm::Value* elem = LLVMUtils::createLoad(&builder, elem_ptr, elem_llvm_type);
llvm::Value* args[] = { elem, captured_var_struct_ptr };
// Call function on element
llvm::Value* mapped_elem = LLVMUtils::createCallWithValue(&builder, function, function_llvm_type, args, "map function call");
// Get pointer to output element
llvm::Value* out_elem_ptr = LLVMUtils::createInBoundsGEP(builder, return_ptr, array_llvm_type, indices);
return builder.CreateStore(mapped_elem, out_elem_ptr); // Store the element in the output array
}
llvm::Type* array_llvm_type;
llvm::Type* elem_llvm_type;
llvm::Type* function_llvm_type;
llvm::Value* return_ptr;
llvm::Value* function;
llvm::Value* captured_var_struct_ptr;
llvm::Value* input_array;
};
static void setArgumentAttributes(llvm::LLVMContext* context, llvm::Function::arg_iterator it, unsigned int index, llvm::AttrBuilder& attr_builder)
{
it->addAttrs(attr_builder);
}
// This function computes the map on a slice of the array given by [begin, end).
// typedef void (WINTER_JIT_CALLING_CONV * ARRAY_WORK_FUNCTION) (void* output, void* input, void* map_function, size_t begin, size_t end); // Winter code
llvm::Value* ArrayMapBuiltInFunc::insertWorkFunction(EmitLLVMCodeParams& params) const
{
llvm::Type* int64_type = llvm::IntegerType::get(*params.context, 64);
llvm::SmallVector<llvm::Type*, 8> arg_types(2, LLVMTypeUtils::pointerType(this->from_type->LLVMType(*params.module))); // output, input
arg_types.push_back(this->func_type->LLVMType(*params.module)); // map_function
arg_types.push_back(int64_type); // size_t begin
arg_types.push_back(int64_type); // size_t end
llvm::FunctionType* functype = llvm::FunctionType::get(
llvm::Type::getVoidTy(params.module->getContext()), // return type
arg_types,
false // varargs
);
llvm::Function* llvm_func = LLVMUtils::getFunctionFromModule(params.module, "work_function", functype);
llvm::BasicBlock* block = llvm::BasicBlock::Create(params.module->getContext(), "entry", llvm_func);
llvm::IRBuilder<> builder(block);
ArrayMapBuiltInFunc_CreateLoopBodyCallBack callback;
callback.array_llvm_type = this->from_type->LLVMType(*params.module);
callback.elem_llvm_type = this->from_type->elem_type->LLVMType(*params.module);
callback.function_llvm_type = this->func_type->functionLLVMType(*params.module);
callback.return_ptr = LLVMUtils::getNthArg(llvm_func, 0);
// If we have a specialised function to use, insert a call to it directly, else used the function pointer passed in as an argument.
if(this->specialised_f)
callback.function = this->specialised_f->getOrInsertFunction(params.module, false);
else
callback.function = LLVMUtils::getNthArg(llvm_func, 2);
callback.input_array = LLVMUtils::getNthArg(llvm_func, 1);
//llvm_func->addAttribute(1, llvm::Attribute::getWithAlignment(*params.context, 3));
// Set some attributes
llvm::Function::arg_iterator AI = llvm_func->arg_begin();
{
#if TARGET_LLVM_VERSION >= 150
llvm::AttrBuilder attr_builder(*params.context);
#else
llvm::AttrBuilder attr_builder;
#endif
attr_builder.addAlignmentAttr(32);
attr_builder.addAttribute(llvm::Attribute::NoAlias);
setArgumentAttributes(params.context, AI, /*index=*/1, attr_builder);
}
AI++;
{
#if TARGET_LLVM_VERSION >= 150
llvm::AttrBuilder attr_builder(*params.context);
#else
llvm::AttrBuilder attr_builder;
#endif
attr_builder.addAlignmentAttr(32);
attr_builder.addAttribute(llvm::Attribute::NoAlias);
setArgumentAttributes(params.context, AI, /*index=*/2, attr_builder);
}
makeForLoop(
builder,
params.module,
llvm::ConstantInt::get(*params.context, llvm::APInt(64, 0)), // TEMP BEGIN=0 LLVMUtils::getNthArg(llvm_func, 3), // begin index
LLVMUtils::getNthArg(llvm_func, 4), // end index
//from_type->elem_type->LLVMType(*params.module), // Loop value type
&callback
);
builder.CreateRetVoid();
return llvm_func;
}
llvm::Value* ArrayMapBuiltInFunc::emitLLVMCode(EmitLLVMCodeParams& params) const
{
// Pointer to result array
llvm::Value* return_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0);
// Closure ptr
/*llvm::Value* closure_ptr = LLVMUtils::getNthArg(params.currently_building_func, 1);
// Get function ptr from closure ptr
vector<llvm::Value*> indices(2);
indices[0] = llvm::ConstantInt::get(*params.context, llvm::APInt(32, 0)); // get the zero-th closure
indices[1] = llvm::ConstantInt::get(*params.context, llvm::APInt(32, 1)); // get the 1st field (function ptr)
llvm::Value* function_ptr = params.builder->CreateGEP(
closure_ptr,
indices
);
llvm::Value* function = params.builder->CreateLoad(function_ptr);*/
llvm::Type* func_llvm_type = func_type->functionLLVMType(*params.module);
llvm::Type* func_ptr_llvm_type = LLVMTypeUtils::pointerType(func_llvm_type);
llvm::Value* closure_ptr = LLVMUtils::getNthArg(params.currently_building_func, 1);
llvm::Type* closure_type = func_type->closureLLVMStructType(*params.module);
llvm::Value* function_ptr_ptr = LLVMUtils::createStructGEP(params.builder, closure_ptr, Function::functionPtrIndex(), closure_type);
llvm::Value* function_ptr = LLVMUtils::createLoad(params.builder, function_ptr_ptr, func_ptr_llvm_type);
llvm::Value* captured_var_struct_ptr = LLVMUtils::createStructGEP(params.builder, closure_ptr, Function::capturedVarStructIndex(), closure_type);
//llvm::Value* function_ptr = params.builder->CreateLoad(
// closure_ptr,
// vector<uint32_t>(1, 1) // 1st field (function ptr)
//);
// Input array
llvm::Value* input_array = LLVMUtils::getNthArg(params.currently_building_func, 2);
//llvm::Value* initial_value = return_ptr;
const bool do_multithreaded_map = false;
if(do_multithreaded_map)
{
llvm::Value* work_function = insertWorkFunction(params);
// Want to call back into function
//
// void execArrayMap(void* output, void* input, size_t array_size, void* map_function, ARRAY_WORK_FUNCTION work_function)
//
// from host code
llvm::Type* voidptr = LLVMTypeUtils::voidPtrType(*params.context);
llvm::SmallVector<llvm::Type*, 8> arg_types(2, LLVMTypeUtils::voidPtrType(*params.context)); // void* output, void* input
const TypeVRef int64_type = new Int(64);
arg_types.push_back(int64_type->LLVMType(*params.module)); // array_size
arg_types.push_back(LLVMTypeUtils::voidPtrType(*params.context)); // map_function
arg_types.push_back(LLVMTypeUtils::voidPtrType(*params.context)); // work_function
llvm::FunctionType* functype = llvm::FunctionType::get(
llvm::Type::getVoidTy(*params.context), // return type
arg_types,
false // varargs
);
llvm::Function* llvm_func = LLVMUtils::getFunctionFromModule(params.module, "execArrayMap", functype);
llvm::SmallVector<llvm::Value*, 8> args;
args.push_back(params.builder->CreatePointerCast(return_ptr, voidptr)); // output
args.push_back(params.builder->CreatePointerCast(input_array, voidptr)); // input
args.push_back(llvm::ConstantInt::get(*params.context, llvm::APInt(64, this->from_type->num_elems))); // array_size
args.push_back(params.builder->CreatePointerCast(function_ptr, voidptr)); // map_function
//TODO: captured_var_struct_ptr stuff
args.push_back(params.builder->CreatePointerCast(work_function, voidptr)); // work_function
params.builder->CreateCall(llvm_func, args);
return return_ptr;
}
else
{
ArrayMapBuiltInFunc_CreateLoopBodyCallBack callback;
callback.array_llvm_type = this->from_type->LLVMType(*params.module);
callback.elem_llvm_type = this->from_type->elem_type->LLVMType(*params.module);
callback.function_llvm_type = this->func_type->functionLLVMType(*params.module);
callback.return_ptr = return_ptr;
callback.function = function_ptr;
callback.captured_var_struct_ptr = captured_var_struct_ptr;
callback.input_array = input_array;
makeForLoop(
*params.builder,
params.module,
llvm::ConstantInt::get(*params.context, llvm::APInt(64, 0)), // begin index
llvm::ConstantInt::get(*params.context, llvm::APInt(64, from_type->num_elems)), // end index
//from_type->elem_type->LLVMType(*params.module), // Loop value type
&callback
);
return return_ptr;
}
}
size_t ArrayMapBuiltInFunc::getTimeBound(GetTimeBoundParams& params) const
{
if(specialised_f)
return specialised_f->getTimeBound(params) * from_type->num_elems;
else
throw BaseException("Unable to bound time of array map function.");
}
GetSpaceBoundResults ArrayMapBuiltInFunc::getSpaceBound(GetSpaceBoundParams& params) const
{
// TODO
throw BaseException("TODO: Unable to bound space of array map function.");
}
//------------------------------------------------------------------------------------
ArrayFoldBuiltInFunc::ArrayFoldBuiltInFunc(const VRef<Function>& func_type_, const VRef<ArrayType>& array_type_, const TypeVRef& state_type_)
: BuiltInFunctionImpl(BuiltInType_ArrayFoldBuiltInFunc),
func_type(func_type_), array_type(array_type_), state_type(state_type_), specialised_f(NULL)
{}
void ArrayFoldBuiltInFunc::specialiseForFunctionArg(FunctionDefinition* f)
{
specialised_f = f;
}
ValueRef ArrayFoldBuiltInFunc::invoke(VMState& vmstate)
{
// fold(function<State, T, State> f, array<T> array, State initial_state) State
const FunctionValue* f = checkedCast<const FunctionValue>(vmstate.argument_stack[vmstate.func_args_start.back()].getPointer());
const ArrayValue* arr = checkedCast<const ArrayValue>(vmstate.argument_stack[vmstate.func_args_start.back() + 1].getPointer());
const ValueRef initial_val = vmstate.argument_stack[vmstate.func_args_start.back() + 2];
assert(f && arr && initial_val.nonNull());
ValueRef running_val = initial_val;
for(unsigned int i=0; i<arr->e.size(); ++i)
{
// Set up arg stack
vmstate.func_args_start.push_back((unsigned int)vmstate.argument_stack.size());
vmstate.argument_stack.push_back(running_val); // Push value arg
vmstate.argument_stack.push_back(arr->e[i]); // Push value arg
ValueRef new_running_val = f->func_def->invoke(vmstate);
vmstate.argument_stack.pop_back(); // Pop Value arg
vmstate.argument_stack.pop_back(); // Pop Value arg
vmstate.func_args_start.pop_back();
running_val = new_running_val;
}
return running_val;
}
// fold(function<State, T, State> f, array<T> array, State initial_state) State
llvm::Value* ArrayFoldBuiltInFunc::emitLLVMCode(EmitLLVMCodeParams& params) const
{
// Get argument pointers/values
llvm::Value* return_ptr = NULL;
llvm::Value* closure_ptr;
llvm::Value* array_arg;
llvm::Value* initial_state_ptr_or_value;
if(state_type->passByValue())
{
closure_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0); // Pointer to function
array_arg = LLVMUtils::getNthArg(params.currently_building_func, 1);
initial_state_ptr_or_value = LLVMUtils::getNthArg(params.currently_building_func, 2); // Pointer to, or value of initial state
}
else
{
return_ptr = LLVMUtils::getNthArg(params.currently_building_func, 0); // Pointer to result structure
closure_ptr = LLVMUtils::getNthArg(params.currently_building_func, 1); // Pointer to function
array_arg = LLVMUtils::getNthArg(params.currently_building_func, 2);
initial_state_ptr_or_value = LLVMUtils::getNthArg(params.currently_building_func, 3); // Pointer to, or value of initial state
}
llvm::Type* func_closure_llvm_type = func_type->LLVMStructType(*params.module);
llvm::Type* func_llvm_type = func_type->functionLLVMType(*params.module);
llvm::Type* func_ptr_llvm_type = LLVMTypeUtils::pointerType(func_llvm_type);
llvm::Value* function_ptr_ptr = LLVMUtils::createStructGEP(params.builder, closure_ptr, Function::functionPtrIndex(), func_closure_llvm_type);
llvm::Value* function_ptr = LLVMUtils::createLoad(params.builder, function_ptr_ptr, func_ptr_llvm_type);
//LLVMTypeUtils::getBaseCapturedVarStructType(*params.module)->dump();
llvm::Value* captured_var_struct_ptr = LLVMUtils::createStructGEP(params.builder, closure_ptr, Function::capturedVarStructIndex(), func_closure_llvm_type);
llvm::Type* array_llvm_type = array_type->LLVMType(*params.module);
llvm::Type* elem_llvm_type = array_type->elem_type->LLVMType(*params.module);
// 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());
//=======================================Begin specialisation ====================================================
// TODO: check args to update as well to make sure it is bound to correct update etc..
// Also check first arg of update is bound to first arg to specialised_f.
if(specialised_f && specialised_f->body->nodeType() == ASTNode::FunctionExpressionType && specialised_f->body.downcast<FunctionExpression>()->static_function_name == "update")
{