forked from pyston/pyston_v1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compvars.cpp
2365 lines (1960 loc) · 97.9 KB
/
compvars.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
// Copyright (c) 2014-2015 Dropbox, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "codegen/compvars.h"
#include <cstdio>
#include <sstream>
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Support/raw_ostream.h"
#include "codegen/codegen.h"
#include "codegen/gcbuilder.h"
#include "codegen/irgen.h"
#include "codegen/irgen/util.h"
#include "codegen/patchpoints.h"
#include "core/options.h"
#include "core/types.h"
#include "runtime/float.h"
#include "runtime/int.h"
#include "runtime/objmodel.h"
#include "runtime/types.h"
namespace pyston {
static const std::string& iter_str = "__iter__";
static const std::string& hasnext_str = "__hasnext__";
CompilerType* CompilerType::getPystonIterType() {
if (hasattr(&iter_str) == Yes) {
CompilerType* iter_type = getattrType(&iter_str, true)->callType(ArgPassSpec(0), {}, NULL);
if (iter_type->hasattr(&hasnext_str) == Yes)
return iter_type;
// if iter_type->hasattr(&hasnext_str) == No we know this is going to be a BoxedIterWrapper
// we could optimize this case but it looks like this is very uncommon
}
return UNKNOWN;
}
CompilerType::Result CompilerType::hasattr(const std::string* attr) {
CompilerType* type = getattrType(attr, true);
if (type == UNKNOWN)
return Result::Maybe;
else if (type == UNDEF)
return Result::No;
return Result::Yes;
}
void ConcreteCompilerType::serializeToFrame(VAR* var, std::vector<llvm::Value*>& stackmap_args) {
#ifndef NDEBUG
if (llvmType() == g.i1) {
var->getValue()->dump();
ASSERT(llvmType() != g.i1, "due to an llvm limitation cannot add these to stackmaps yet");
}
#endif
stackmap_args.push_back(var->getValue());
}
std::string ValuedCompilerType<llvm::Value*>::debugName() {
std::string rtn;
llvm::raw_string_ostream os(rtn);
llvmType()->print(os);
return rtn;
}
struct RawInstanceMethod {
CompilerVariable* obj, *func;
RawInstanceMethod(CompilerVariable* obj, CompilerVariable* func) : obj(obj), func(func) {}
};
class InstanceMethodType : public ValuedCompilerType<RawInstanceMethod*> {
private:
static std::unordered_map<std::pair<CompilerType*, CompilerType*>, InstanceMethodType*> made;
CompilerType* obj_type, *function_type;
InstanceMethodType(CompilerType* obj_type, CompilerType* function_type)
: obj_type(obj_type), function_type(function_type) {}
void checkVar(VAR* var) {
#ifndef NDEBUG
RawInstanceMethod* val = var->getValue();
assert(val->obj->getType() == obj_type);
assert(val->func->getType() == function_type);
#endif
}
public:
void assertMatches(RawInstanceMethod* im) override {
assert(obj_type == im->obj->getType() && function_type == im->func->getType());
}
static InstanceMethodType* get(CompilerType* obj_type, CompilerType* function_type) {
InstanceMethodType* rtn = made[std::make_pair(obj_type, function_type)];
if (rtn == NULL)
rtn = new InstanceMethodType(obj_type, function_type);
return rtn;
}
static CompilerVariable* makeIM(CompilerVariable* obj, CompilerVariable* func) {
CompilerVariable* rtn = new ValuedCompilerVariable<RawInstanceMethod*>(
InstanceMethodType::get(obj->getType(), func->getType()), new RawInstanceMethod(obj, func), true);
obj->incvref();
func->incvref();
return rtn;
}
CompilerType* callType(ArgPassSpec argspec, const std::vector<CompilerType*>& arg_types,
const std::vector<const std::string*>* keyword_names) override {
std::vector<CompilerType*> new_args(arg_types);
new_args.insert(new_args.begin(), obj_type);
ArgPassSpec new_argspec(argspec.num_args + 1u, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs);
return function_type->callType(new_argspec, new_args, keyword_names);
}
std::string debugName() override {
return "instanceMethod(" + obj_type->debugName() + " ; " + function_type->debugName() + ")";
}
void drop(IREmitter& emitter, VAR* var) override {
checkVar(var);
RawInstanceMethod* val = var->getValue();
val->obj->decvref(emitter);
val->func->decvref(emitter);
delete val;
}
CompilerVariable* call(IREmitter& emitter, const OpInfo& info, ValuedCompilerVariable<RawInstanceMethod*>* var,
ArgPassSpec argspec, const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names) override {
std::vector<CompilerVariable*> new_args;
new_args.push_back(var->getValue()->obj);
new_args.insert(new_args.end(), args.begin(), args.end());
ArgPassSpec new_argspec(argspec.num_args + 1u, argspec.num_keywords, argspec.has_starargs, argspec.has_kwargs);
return var->getValue()->func->call(emitter, info, new_argspec, new_args, keyword_names);
}
bool canConvertTo(ConcreteCompilerType* other_type) override { return other_type == UNKNOWN; }
ConcreteCompilerType* getConcreteType() override { return typeFromClass(instancemethod_cls); }
ConcreteCompilerType* getBoxType() override { return getConcreteType(); }
ConcreteCompilerVariable* makeConverted(IREmitter& emitter, VAR* var, ConcreteCompilerType* other_type) override {
checkVar(var);
assert(other_type == UNKNOWN || other_type == typeFromClass(instancemethod_cls));
RawInstanceMethod* im = var->getValue();
assert(im->obj);
assert(im->func);
ConcreteCompilerVariable* obj = im->obj->makeConverted(emitter, UNKNOWN);
ConcreteCompilerVariable* func = im->func->makeConverted(emitter, UNKNOWN);
llvm::Value* boxed
= emitter.getBuilder()->CreateCall2(g.funcs.boxInstanceMethod, obj->getValue(), func->getValue());
obj->decvref(emitter);
func->decvref(emitter);
return new ConcreteCompilerVariable(other_type, boxed, true);
}
CompilerVariable* dup(VAR* var, DupCache& cache) override {
checkVar(var);
CompilerVariable* rtn = cache[var];
if (rtn == NULL) {
RawInstanceMethod* im = var->getValue();
RawInstanceMethod* new_im = new RawInstanceMethod(im->obj->dup(cache), im->func->dup(cache));
rtn = new VAR(this, new_im, var->isGrabbed());
while (rtn->getVrefs() < var->getVrefs())
rtn->incvref();
}
return rtn;
}
void serializeToFrame(VAR* var, std::vector<llvm::Value*>& stackmap_args) override {
var->getValue()->obj->serializeToFrame(stackmap_args);
var->getValue()->func->serializeToFrame(stackmap_args);
}
Box* deserializeFromFrame(const FrameVals& vals) override {
assert(vals.size() == numFrameArgs());
abort();
}
int numFrameArgs() override { return obj_type->numFrameArgs() + function_type->numFrameArgs(); }
};
std::unordered_map<std::pair<CompilerType*, CompilerType*>, InstanceMethodType*> InstanceMethodType::made;
ConcreteCompilerVariable* ConcreteCompilerType::makeConverted(IREmitter& emitter, ConcreteCompilerVariable* var,
ConcreteCompilerType* other_type) {
if (other_type == this) {
var->incvref();
return var;
}
printf("makeConverted not defined for %s\n", debugName().c_str());
abort();
}
CompilerVariable* ConcreteCompilerType::dup(ConcreteCompilerVariable* v, DupCache& cache) {
auto& rtn = cache[v];
if (rtn == NULL) {
rtn = new ConcreteCompilerVariable(this, v->getValue(), v->isGrabbed());
while (rtn->getVrefs() < v->getVrefs())
rtn->incvref();
}
return rtn;
}
class UnknownType : public ConcreteCompilerType {
public:
llvm::Type* llvmType() override { return g.llvm_value_type_ptr; }
std::string debugName() override { return "AnyBox"; }
void drop(IREmitter& emitter, VAR* var) override { emitter.getGC()->dropPointer(emitter, var->getValue()); }
void grab(IREmitter& emitter, VAR* var) override { emitter.getGC()->grabPointer(emitter, var->getValue()); }
bool isFitBy(BoxedClass* c) override { return true; }
CompilerVariable* getattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr, bool cls_only) override;
CompilerVariable* call(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var, ArgPassSpec argspec,
const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names) override;
CompilerVariable* callattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr, CallattrFlags flags, ArgPassSpec argspec,
const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names) override;
ConcreteCompilerVariable* nonzero(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) override;
ConcreteCompilerVariable* hasnext(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) override;
void setattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var, const std::string* attr,
CompilerVariable* v) override {
llvm::Constant* ptr = getStringConstantPtr(*attr + '\0');
ConcreteCompilerVariable* converted = v->makeConverted(emitter, UNKNOWN);
// g.funcs.setattr->dump();
// var->getValue()->dump(); llvm::errs() << '\n';
// ptr->dump(); llvm::errs() << '\n';
// converted->getValue()->dump(); llvm::errs() << '\n';
bool do_patchpoint = ENABLE_ICSETATTRS && !info.isInterpreted();
if (do_patchpoint) {
ICSetupInfo* pp = createSetattrIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm_args.push_back(ptr);
llvm_args.push_back(converted->getValue());
emitter.createIC(pp, (void*)pyston::setattr, llvm_args, info.unw_info);
} else {
emitter.createCall3(info.unw_info, g.funcs.setattr, var->getValue(), ptr, converted->getValue());
}
converted->decvref(emitter);
}
void delattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr) override {
llvm::Constant* ptr = getStringConstantPtr(*attr + '\0');
// TODO
// bool do_patchpoint = ENABLE_ICDELATTRS && !info.isInterpreted();
bool do_patchpoint = false;
if (do_patchpoint) {
ICSetupInfo* pp = createDelattrIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm_args.push_back(ptr);
emitter.createIC(pp, (void*)pyston::delattr, llvm_args, info.unw_info);
} else {
emitter.createCall2(info.unw_info, g.funcs.delattr, var->getValue(), ptr);
}
}
llvm::Value* makeClassCheck(IREmitter& emitter, ConcreteCompilerVariable* var, BoxedClass* cls) override {
assert(var->getValue()->getType() == g.llvm_value_type_ptr);
static_assert(offsetof(Box, cls) % sizeof(void*) == 0, "");
llvm::Value* cls_ptr
= emitter.getBuilder()->CreateConstInBoundsGEP2_32(var->getValue(), 0, offsetof(Box, cls) / sizeof(void*));
llvm::Value* cls_value = emitter.getBuilder()->CreateLoad(cls_ptr);
assert(cls_value->getType() == g.llvm_class_type_ptr);
llvm::Value* rtn = emitter.getBuilder()->CreateICmpEQ(cls_value, embedConstantPtr(cls, g.llvm_class_type_ptr));
return rtn;
}
CompilerType* getattrType(const std::string* attr, bool cls_only) override { return UNKNOWN; }
CompilerType* callType(ArgPassSpec argspec, const std::vector<CompilerType*>& arg_types,
const std::vector<const std::string*>* keyword_names) override {
return UNKNOWN;
}
BoxedClass* guaranteedClass() override { return NULL; }
ConcreteCompilerType* getBoxType() override { return this; }
ConcreteCompilerVariable* makeConverted(IREmitter& emitter, ConcreteCompilerVariable* var,
ConcreteCompilerType* other_type) override {
if (other_type == this) {
var->incvref();
return var;
}
fprintf(stderr, "Can't convert unknown to %s...\n", other_type->debugName().c_str());
abort();
}
ConcreteCompilerVariable* len(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) override {
bool do_patchpoint = ENABLE_ICGENERICS && !info.isInterpreted();
llvm::Value* rtn;
if (do_patchpoint) {
ICSetupInfo* pp = createGenericIC(info.getTypeRecorder(), true, 256);
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
rtn = emitter.createIC(pp, (void*)pyston::unboxedLen, llvm_args, info.unw_info);
} else {
rtn = emitter.createCall(info.unw_info, g.funcs.unboxedLen, var->getValue());
}
assert(rtn->getType() == g.i64);
return new ConcreteCompilerVariable(INT, rtn, true);
}
CompilerVariable* getitem(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
CompilerVariable* slice) override {
ConcreteCompilerVariable* converted_slice = slice->makeConverted(emitter, slice->getBoxType());
bool do_patchpoint = ENABLE_ICGETITEMS && !info.isInterpreted();
llvm::Value* rtn;
if (do_patchpoint) {
ICSetupInfo* pp = createGetitemIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm_args.push_back(converted_slice->getValue());
llvm::Value* uncasted = emitter.createIC(pp, (void*)pyston::getitem, llvm_args, info.unw_info);
rtn = emitter.getBuilder()->CreateIntToPtr(uncasted, g.llvm_value_type_ptr);
} else {
rtn = emitter.createCall2(info.unw_info, g.funcs.getitem, var->getValue(), converted_slice->getValue());
}
converted_slice->decvref(emitter);
return new ConcreteCompilerVariable(UNKNOWN, rtn, true);
}
CompilerVariable* getPystonIter(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) override {
CallattrFlags flags = {.cls_only = true, .null_on_nonexistent = true };
CompilerVariable* iter_call = var->callattr(emitter, info, &iter_str, flags, ArgPassSpec(0), {}, 0);
ConcreteCompilerVariable* converted_iter_call = iter_call->makeConverted(emitter, iter_call->getBoxType());
// If the type analysis could determine the iter type is a valid pyston iter (has 'hasnext') we are finished.
CompilerType* iter_type = var->getType()->getPystonIterType();
if (iter_type != UNKNOWN) {
iter_call->decvref(emitter);
return converted_iter_call;
}
// We don't know the type so we have to check at runtime if __iter__ is implemented
llvm::Value* cmp = emitter.getBuilder()->CreateICmpNE(converted_iter_call->getValue(),
embedConstantPtr(0, g.llvm_value_type_ptr));
llvm::BasicBlock* bb_has_iter = emitter.createBasicBlock("has_iter");
bb_has_iter->moveAfter(emitter.currentBasicBlock());
llvm::BasicBlock* bb_no_iter = emitter.createBasicBlock("no_iter");
bb_no_iter->moveAfter(bb_has_iter);
llvm::BasicBlock* bb_join = emitter.createBasicBlock("join_after_getiter");
emitter.getBuilder()->CreateCondBr(cmp, bb_has_iter, bb_no_iter);
// var has __iter__()
emitter.setCurrentBasicBlock(bb_has_iter);
ICSetupInfo* pp = createGenericIC(info.getTypeRecorder(), true, 128);
llvm::Value* uncasted = emitter.createIC(pp, (void*)pyston::createBoxedIterWrapperIfNeeded,
{ converted_iter_call->getValue() }, info.unw_info);
llvm::Value* value_has_iter = emitter.getBuilder()->CreateIntToPtr(uncasted, g.llvm_value_type_ptr);
llvm::BasicBlock* value_has_iter_bb = emitter.currentBasicBlock();
emitter.getBuilder()->CreateBr(bb_join);
// var has no __iter__()
// TODO: we could create a patchpoint if this turns out to be hot
emitter.setCurrentBasicBlock(bb_no_iter);
llvm::Value* value_no_iter = emitter.createCall(info.unw_info, g.funcs.getiterHelper, var->getValue());
llvm::BasicBlock* value_no_iter_bb = emitter.currentBasicBlock();
emitter.getBuilder()->CreateBr(bb_join);
// join
emitter.setCurrentBasicBlock(bb_join);
auto phi = emitter.getBuilder()->CreatePHI(g.llvm_value_type_ptr, 2, "iter");
phi->addIncoming(value_has_iter, value_has_iter_bb);
phi->addIncoming(value_no_iter, value_no_iter_bb);
converted_iter_call->decvref(emitter);
iter_call->decvref(emitter);
return new ConcreteCompilerVariable(UNKNOWN, phi, true);
}
CompilerVariable* binexp(IREmitter& emitter, const OpInfo& info, VAR* var, CompilerVariable* rhs,
AST_TYPE::AST_TYPE op_type, BinExpType exp_type) override {
ConcreteCompilerVariable* converted_rhs = rhs->makeConverted(emitter, rhs->getBoxType());
llvm::Value* rtn;
bool do_patchpoint = ENABLE_ICBINEXPS && !info.isInterpreted();
llvm::Value* rt_func;
void* rt_func_addr;
if (exp_type == BinOp) {
rt_func = g.funcs.binop;
rt_func_addr = (void*)binop;
} else if (exp_type == AugBinOp) {
rt_func = g.funcs.augbinop;
rt_func_addr = (void*)augbinop;
} else {
rt_func = g.funcs.compare;
rt_func_addr = (void*)compare;
}
if (do_patchpoint) {
ICSetupInfo* pp = createBinexpIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm_args.push_back(converted_rhs->getValue());
llvm_args.push_back(getConstantInt(op_type, g.i32));
llvm::Value* uncasted = emitter.createIC(pp, rt_func_addr, llvm_args, info.unw_info);
rtn = emitter.getBuilder()->CreateIntToPtr(uncasted, g.llvm_value_type_ptr);
} else {
rtn = emitter.createCall3(info.unw_info, rt_func, var->getValue(), converted_rhs->getValue(),
getConstantInt(op_type, g.i32));
}
converted_rhs->decvref(emitter);
if (op_type == AST_TYPE::In || op_type == AST_TYPE::NotIn || op_type == AST_TYPE::Is
|| op_type == AST_TYPE::IsNot) {
llvm::Value* unboxed = emitter.getBuilder()->CreateCall(g.funcs.unboxBool, rtn);
return boolFromI1(emitter, unboxed);
}
return new ConcreteCompilerVariable(UNKNOWN, rtn, true);
}
Box* deserializeFromFrame(const FrameVals& vals) override {
assert(vals.size() == 1);
return reinterpret_cast<Box*>(vals[0]);
}
std::vector<CompilerVariable*> unpack(IREmitter& emitter, const OpInfo& info, VAR* var, int num_into) override {
llvm::Value* unpacked = emitter.createCall2(info.unw_info, g.funcs.unpackIntoArray, var->getValue(),
getConstantInt(num_into, g.i64));
assert(unpacked->getType() == g.llvm_value_type_ptr->getPointerTo());
std::vector<CompilerVariable*> rtn;
for (int i = 0; i < num_into; i++) {
llvm::Value* ptr = emitter.getBuilder()->CreateConstGEP1_32(unpacked, i);
llvm::Value* val = emitter.getBuilder()->CreateLoad(ptr);
assert(val->getType() == g.llvm_value_type_ptr);
rtn.push_back(new ConcreteCompilerVariable(UNKNOWN, val, true));
}
return rtn;
}
};
ConcreteCompilerType* UNKNOWN = new UnknownType();
CompilerVariable* UnknownType::getattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr, bool cls_only) {
llvm::Constant* ptr = getStringConstantPtr(*attr + '\0');
llvm::Value* rtn_val = NULL;
llvm::Value* llvm_func;
void* raw_func;
if (cls_only) {
llvm_func = g.funcs.getclsattr;
raw_func = (void*)pyston::getclsattr;
} else {
llvm_func = g.funcs.getattr;
raw_func = (void*)pyston::getattr;
}
bool do_patchpoint = ENABLE_ICGETATTRS && !info.isInterpreted();
if (do_patchpoint) {
ICSetupInfo* pp = createGetattrIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm_args.push_back(ptr);
llvm::Value* uncasted = emitter.createIC(pp, raw_func, llvm_args, info.unw_info);
rtn_val = emitter.getBuilder()->CreateIntToPtr(uncasted, g.llvm_value_type_ptr);
} else {
rtn_val = emitter.createCall2(info.unw_info, llvm_func, var->getValue(), ptr);
}
return new ConcreteCompilerVariable(UNKNOWN, rtn_val, true);
}
static ConcreteCompilerVariable* _call(IREmitter& emitter, const OpInfo& info, llvm::Value* func, void* func_addr,
const std::vector<llvm::Value*>& other_args, ArgPassSpec argspec,
const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names,
ConcreteCompilerType* rtn_type) {
bool pass_keyword_names = (keyword_names != nullptr);
assert(pass_keyword_names == (argspec.num_keywords > 0));
std::vector<BoxedClass*> guaranteed_classes;
std::vector<ConcreteCompilerVariable*> converted_args;
for (int i = 0; i < args.size(); i++) {
assert(args[i]);
converted_args.push_back(args[i]->makeConverted(emitter, args[i]->getBoxType()));
guaranteed_classes.push_back(converted_args.back()->guaranteedClass());
}
std::vector<llvm::Value*> llvm_args;
llvm_args.insert(llvm_args.end(), other_args.begin(), other_args.end());
if (args.size() >= 1) {
llvm_args.push_back(converted_args[0]->getValue());
} else if (pass_keyword_names) {
llvm_args.push_back(embedConstantPtr(NULL, g.llvm_value_type_ptr));
}
if (args.size() >= 2) {
llvm_args.push_back(converted_args[1]->getValue());
} else if (pass_keyword_names) {
llvm_args.push_back(embedConstantPtr(NULL, g.llvm_value_type_ptr));
}
if (args.size() >= 3) {
llvm_args.push_back(converted_args[2]->getValue());
} else if (pass_keyword_names) {
llvm_args.push_back(embedConstantPtr(NULL, g.llvm_value_type_ptr));
}
llvm::Value* mallocsave = NULL;
if (args.size() >= 4) {
llvm::Value* arg_array;
if (info.isInterpreted()) {
llvm::Value* n_bytes = getConstantInt((args.size() - 3) * sizeof(Box*), g.i64);
mallocsave = emitter.getBuilder()->CreateCall(g.funcs.malloc, n_bytes);
arg_array = emitter.getBuilder()->CreateBitCast(mallocsave, g.llvm_value_type_ptr->getPointerTo());
} else {
llvm::Value* n_varargs = getConstantInt(args.size() - 3, g.i64);
// Don't use the IRBuilder since we want to specifically put this in the entry block so it only gets called
// once.
// TODO we could take this further and use the same alloca for all function calls?
llvm::Instruction* insertion_point = emitter.currentFunction()->func->getEntryBlock().getFirstInsertionPt();
arg_array = new llvm::AllocaInst(g.llvm_value_type_ptr, n_varargs, "arg_scratch", insertion_point);
}
for (int i = 3; i < args.size(); i++) {
llvm::Value* ptr = emitter.getBuilder()->CreateConstGEP1_32(arg_array, i - 3);
emitter.getBuilder()->CreateStore(converted_args[i]->getValue(), ptr);
}
llvm_args.push_back(arg_array);
if (pass_keyword_names)
llvm_args.push_back(embedConstantPtr(keyword_names, g.vector_ptr));
} else if (pass_keyword_names) {
llvm_args.push_back(embedConstantPtr(NULL, g.llvm_value_type_ptr->getPointerTo()));
llvm_args.push_back(embedConstantPtr(keyword_names, g.vector_ptr));
}
// f->dump();
// for (int i = 0; i < llvm_args.size(); i++) {
// llvm_args[i]->dump();
// llvm::errs() << '\n';
//}
llvm::Value* rtn;
// func->dump();
// for (auto a : llvm_args)
// a->dump();
bool do_patchpoint = ENABLE_ICCALLSITES && !info.isInterpreted()
&& (func_addr == runtimeCall || func_addr == pyston::callattr);
if (do_patchpoint) {
assert(func_addr);
ICSetupInfo* pp = createCallsiteIC(info.getTypeRecorder(), args.size());
llvm::Value* uncasted = emitter.createIC(pp, func_addr, llvm_args, info.unw_info);
assert(llvm::cast<llvm::FunctionType>(llvm::cast<llvm::PointerType>(func->getType())->getElementType())
->getReturnType() == g.llvm_value_type_ptr);
rtn = emitter.getBuilder()->CreateIntToPtr(uncasted, g.llvm_value_type_ptr);
} else {
// printf("\n");
// func->dump();
// printf("\n");
// for (auto a : llvm_args) {
// a->dump();
//}
// printf("%ld %ld\n", llvm_args.size(), args.size());
// printf("\n");
rtn = emitter.createCall(info.unw_info, func, llvm_args);
}
if (mallocsave) {
llvm::Value* l_free = embedConstantPtr(
(void*)free, llvm::FunctionType::get(g.void_, g.i8->getPointerTo(), false)->getPointerTo());
emitter.getBuilder()->CreateCall(l_free, mallocsave);
}
for (int i = 0; i < args.size(); i++) {
converted_args[i]->decvref(emitter);
}
assert(rtn->getType() == rtn_type->llvmType());
return new ConcreteCompilerVariable(rtn_type, rtn, true);
}
CompilerVariable* UnknownType::call(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
ArgPassSpec argspec, const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names) {
bool pass_keywords = (argspec.num_keywords != 0);
int npassed_args = argspec.totalPassed();
llvm::Value* func;
if (pass_keywords)
func = g.funcs.runtimeCall;
else if (npassed_args == 0)
func = g.funcs.runtimeCall0;
else if (npassed_args == 1)
func = g.funcs.runtimeCall1;
else if (npassed_args == 2)
func = g.funcs.runtimeCall2;
else if (npassed_args == 3)
func = g.funcs.runtimeCall3;
else
func = g.funcs.runtimeCallN;
std::vector<llvm::Value*> other_args;
other_args.push_back(var->getValue());
llvm::Value* llvm_argspec = llvm::ConstantInt::get(g.i32, argspec.asInt(), false);
other_args.push_back(llvm_argspec);
return _call(emitter, info, func, (void*)runtimeCall, other_args, argspec, args, keyword_names, UNKNOWN);
}
CompilerVariable* UnknownType::callattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr, CallattrFlags flags, ArgPassSpec argspec,
const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names) {
bool pass_keywords = (argspec.num_keywords != 0);
int npassed_args = argspec.totalPassed();
llvm::Value* func;
if (pass_keywords)
func = g.funcs.callattr;
else if (npassed_args == 0)
func = g.funcs.callattr0;
else if (npassed_args == 1)
func = g.funcs.callattr1;
else if (npassed_args == 2)
func = g.funcs.callattr2;
else if (npassed_args == 3)
func = g.funcs.callattr3;
else
func = g.funcs.callattrN;
union {
CallattrFlags flags;
char value;
} flags_to_int;
static_assert(sizeof(CallattrFlags) == sizeof(char), "");
flags_to_int.flags = flags;
std::vector<llvm::Value*> other_args;
other_args.push_back(var->getValue());
other_args.push_back(embedConstantPtr(attr, g.llvm_str_type_ptr));
other_args.push_back(getConstantInt(flags_to_int.value, g.i8));
llvm::Value* llvm_argspec = llvm::ConstantInt::get(g.i32, argspec.asInt(), false);
other_args.push_back(llvm_argspec);
return _call(emitter, info, func, (void*)pyston::callattr, other_args, argspec, args, keyword_names, UNKNOWN);
}
ConcreteCompilerVariable* UnknownType::nonzero(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) {
bool do_patchpoint = ENABLE_ICNONZEROS && !info.isInterpreted();
llvm::Value* rtn_val;
if (do_patchpoint) {
ICSetupInfo* pp = createNonzeroIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm::Value* uncasted = emitter.createIC(pp, (void*)pyston::nonzero, llvm_args, info.unw_info);
rtn_val = emitter.getBuilder()->CreateTrunc(uncasted, g.i1);
} else {
rtn_val = emitter.createCall(info.unw_info, g.funcs.nonzero, var->getValue());
}
return boolFromI1(emitter, rtn_val);
}
ConcreteCompilerVariable* UnknownType::hasnext(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) {
bool do_patchpoint = ENABLE_ICS && !info.isInterpreted();
do_patchpoint = false; // we are currently using runtime ics for this
llvm::Value* rtn_val;
if (do_patchpoint) {
ICSetupInfo* pp = createHasnextIC(info.getTypeRecorder());
std::vector<llvm::Value*> llvm_args;
llvm_args.push_back(var->getValue());
llvm::Value* uncasted = emitter.createIC(pp, (void*)pyston::hasnext, llvm_args, info.unw_info);
rtn_val = emitter.getBuilder()->CreateTrunc(uncasted, g.i1);
} else {
rtn_val = emitter.createCall(info.unw_info, g.funcs.hasnext, var->getValue());
}
return boolFromI1(emitter, rtn_val);
}
CompilerVariable* makeFunction(IREmitter& emitter, CLFunction* f, CompilerVariable* closure, bool isGenerator,
const std::vector<ConcreteCompilerVariable*>& defaults) {
// Unlike the CLFunction*, which can be shared between recompilations, the Box* around it
// should be created anew every time the functiondef is encountered
llvm::Value* closure_v;
ConcreteCompilerVariable* convertedClosure = NULL;
if (closure) {
convertedClosure = closure->makeConverted(emitter, closure->getConcreteType());
closure_v = convertedClosure->getValue();
} else {
closure_v = embedConstantPtr(nullptr, g.llvm_closure_type_ptr);
}
llvm::Value* scratch;
if (defaults.size()) {
scratch = emitter.getScratch(defaults.size() * sizeof(Box*));
scratch = emitter.getBuilder()->CreateBitCast(scratch, g.llvm_value_type_ptr_ptr);
int i = 0;
for (auto d : defaults) {
llvm::Value* v = d->getValue();
llvm::Value* p = emitter.getBuilder()->CreateConstGEP1_32(scratch, i);
emitter.getBuilder()->CreateStore(v, p);
i++;
}
} else {
scratch = embedConstantPtr(nullptr, g.llvm_value_type_ptr_ptr);
}
llvm::Value* isGenerator_v = llvm::ConstantInt::get(g.i1, isGenerator, false);
// We know this function call can't throw, so it's safe to use emitter.getBuilder()->CreateCall() rather than
// emitter.createCall().
llvm::Value* boxed = emitter.getBuilder()->CreateCall(
g.funcs.boxCLFunction,
std::vector<llvm::Value*>{ embedConstantPtr(f, g.llvm_clfunction_type_ptr), closure_v, isGenerator_v, scratch,
getConstantInt(defaults.size(), g.i64) });
if (convertedClosure)
convertedClosure->decvref(emitter);
return new ConcreteCompilerVariable(typeFromClass(function_cls), boxed, true);
}
class AbstractFunctionType : public CompilerType {
public:
struct Sig {
std::vector<ConcreteCompilerType*> arg_types;
CompilerType* rtn_type;
int ndefaults;
};
private:
std::vector<Sig*> sigs;
AbstractFunctionType(const std::vector<Sig*>& sigs) : sigs(sigs) {}
public:
std::string debugName() override { return "<AbstractFunctionType>"; }
ConcreteCompilerType* getConcreteType() override { return UNKNOWN; }
ConcreteCompilerType* getBoxType() override { return UNKNOWN; }
bool canConvertTo(ConcreteCompilerType* other_type) override { return other_type == UNKNOWN; }
CompilerType* getattrType(const std::string* attr, bool cls_only) override { return UNDEF; }
CompilerType* callType(ArgPassSpec argspec, const std::vector<CompilerType*>& arg_types,
const std::vector<const std::string*>* keyword_names) override {
RELEASE_ASSERT(!argspec.has_starargs, "");
RELEASE_ASSERT(!argspec.has_kwargs, "");
RELEASE_ASSERT(argspec.num_keywords == 0, "");
for (int i = 0; i < sigs.size(); i++) {
Sig* sig = sigs[i];
if (arg_types.size() < sig->arg_types.size() - sig->ndefaults || arg_types.size() > sig->arg_types.size())
continue;
bool works = true;
for (int j = 0; j < arg_types.size(); j++) {
if (!arg_types[j]->canConvertTo(sig->arg_types[j])) {
works = false;
break;
}
}
if (!works)
continue;
return sig->rtn_type;
}
return UNDEF;
}
BoxedClass* guaranteedClass() override { return NULL; }
static CompilerType* fromRT(BoxedFunction* rtfunc, bool stripfirst) {
std::vector<Sig*> sigs;
CLFunction* clf = rtfunc->f;
for (int i = 0; i < clf->versions.size(); i++) {
CompiledFunction* cf = clf->versions[i];
FunctionSpecialization* fspec = cf->spec;
Sig* type_sig = new Sig();
type_sig->rtn_type = fspec->rtn_type;
type_sig->ndefaults = clf->num_defaults;
if (stripfirst) {
assert(fspec->arg_types.size() >= 1);
type_sig->arg_types.insert(type_sig->arg_types.end(), fspec->arg_types.begin() + 1,
fspec->arg_types.end());
} else {
type_sig->arg_types.insert(type_sig->arg_types.end(), fspec->arg_types.begin(), fspec->arg_types.end());
}
sigs.push_back(type_sig);
}
return get(sigs);
}
static CompilerType* get(const std::vector<Sig*>& sigs) { return new AbstractFunctionType(sigs); }
Box* deserializeFromFrame(const FrameVals& vals) override {
assert(vals.size() == numFrameArgs());
abort();
}
int numFrameArgs() override { abort(); }
};
class IntType : public ConcreteCompilerType {
public:
IntType() {}
llvm::Type* llvmType() override { return g.i64; }
bool isFitBy(BoxedClass* c) override { return false; }
void drop(IREmitter& emitter, ConcreteCompilerVariable* var) override {
// pass
}
void grab(IREmitter& emitter, ConcreteCompilerVariable* var) override {
// pass
}
CompilerType* getattrType(const std::string* attr, bool cls_only) override {
/*
static std::vector<AbstractFunctionType::Sig*> sigs;
if (sigs.size() == 0) {
AbstractFunctionType::Sig* int_sig = new AbstractFunctionType::Sig();
int_sig->rtn_type = INT;
int_sig->arg_types.push_back(INT);
sigs.push_back(int_sig);
AbstractFunctionType::Sig* unknown_sig = new AbstractFunctionType::Sig();
unknown_sig->rtn_type = UNKNOWN;
unknown_sig->arg_types.push_back(UNKNOWN);
sigs.push_back(unknown_sig);
}
if (*attr == "__add__" || *attr == "__sub__" || *attr == "__mod__" || *attr == "__mul__"
|| *attr == "__lshift__" || *attr == "__rshift__" || *attr == "__div__" || *attr == "__pow__"
|| *attr == "__floordiv__" || *attr == "__and__" || *attr == "__or__" || *attr == "__xor__") {
return AbstractFunctionType::get(sigs);
}
if (*attr == "__iadd__" || *attr == "__isub__" || *attr == "__imod__" || *attr == "__imul__"
|| *attr == "__ilshift__" || *attr == "__irshift__" || *attr == "__idiv__" || *attr == "__ipow__"
|| *attr == "__ifloordiv__" || *attr == "__iand__" || *attr == "__ior__" || *attr == "__ixor__") {
return AbstractFunctionType::get(sigs);
}
*/
static std::vector<AbstractFunctionType::Sig*> sigs;
if (sigs.size() == 0) {
AbstractFunctionType::Sig* int__float_sig = new AbstractFunctionType::Sig();
int__float_sig->rtn_type = FLOAT;
int__float_sig->arg_types.push_back(FLOAT);
sigs.push_back(int__float_sig);
AbstractFunctionType::Sig* unknown_sig = new AbstractFunctionType::Sig();
unknown_sig->rtn_type = UNKNOWN;
unknown_sig->arg_types.push_back(UNKNOWN);
sigs.push_back(unknown_sig);
}
// we can handle those operations when the rhs is a float
if (*attr == "__add__" || *attr == "__sub__" || *attr == "__mul__" || *attr == "__div__" || *attr == "__pow__"
|| *attr == "__floordiv__" || *attr == "__mod__" || *attr == "__pow__") {
return AbstractFunctionType::get(sigs);
}
return BOXED_INT->getattrType(attr, cls_only);
}
CompilerVariable* callattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr, CallattrFlags flags, ArgPassSpec argspec,
const std::vector<CompilerVariable*>& args,
const std::vector<const std::string*>* keyword_names) override {
ConcreteCompilerVariable* converted = var->makeConverted(emitter, BOXED_INT);
CompilerVariable* rtn = converted->callattr(emitter, info, attr, flags, argspec, args, keyword_names);
converted->decvref(emitter);
return rtn;
}
CompilerVariable* getattr(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var,
const std::string* attr, bool cls_only) override {
ConcreteCompilerVariable* converted = var->makeConverted(emitter, BOXED_INT);
CompilerVariable* rtn = converted->getattr(emitter, info, attr, cls_only);
converted->decvref(emitter);
return rtn;
}
void setattr(IREmitter& emitter, const OpInfo& info, VAR* var, const std::string* attr,
CompilerVariable* v) override {
llvm::CallSite call = emitter.createCall2(info.unw_info, g.funcs.raiseAttributeErrorStr,
getStringConstantPtr("int\0"), getStringConstantPtr(*attr + '\0'));
call.setDoesNotReturn();
}
void delattr(IREmitter& emitter, const OpInfo& info, VAR* var, const std::string* attr) override {
llvm::CallSite call = emitter.createCall2(info.unw_info, g.funcs.raiseAttributeErrorStr,
getStringConstantPtr("int\0"), getStringConstantPtr(*attr + '\0'));
call.setDoesNotReturn();
}
ConcreteCompilerVariable* makeConverted(IREmitter& emitter, ConcreteCompilerVariable* var,
ConcreteCompilerType* other_type) override {
if (other_type == this) {
var->incvref();
return var;
} else if (other_type == UNKNOWN || other_type == BOXED_INT) {
llvm::Value* boxed = emitter.getBuilder()->CreateCall(g.funcs.boxInt, var->getValue());
return new ConcreteCompilerVariable(other_type, boxed, true);
} else {
printf("Don't know how to convert i64 to %s\n", other_type->debugName().c_str());
abort();
}
}
CompilerVariable* getitem(IREmitter& emitter, const OpInfo& info, VAR* var, CompilerVariable* slice) override {
ConcreteCompilerVariable* converted = var->makeConverted(emitter, BOXED_INT);
CompilerVariable* rtn = converted->getitem(emitter, info, slice);
converted->decvref(emitter);
return rtn;
}
ConcreteCompilerVariable* len(IREmitter& emitter, const OpInfo& info, VAR* var) override {
llvm::CallSite call
= emitter.createCall(info.unw_info, g.funcs.raiseNotIterableError, getStringConstantPtr("int"));
call.setDoesNotReturn();
return new ConcreteCompilerVariable(INT, llvm::UndefValue::get(g.i64), true);
}
ConcreteCompilerVariable* nonzero(IREmitter& emitter, const OpInfo& info, ConcreteCompilerVariable* var) override {
llvm::Value* cmp = emitter.getBuilder()->CreateICmpNE(var->getValue(), llvm::ConstantInt::get(g.i64, 0, false));
return boolFromI1(emitter, cmp);
}
CompilerVariable* binexp(IREmitter& emitter, const OpInfo& info, VAR* var, CompilerVariable* rhs,
AST_TYPE::AST_TYPE op_type, BinExpType exp_type) override {
bool can_lower = (rhs->getType() == INT && exp_type == Compare);
if (!can_lower) {
// if the rhs is a float convert the lhs to a float and do the operation on it.
if (rhs->getType() == FLOAT) {
if (op_type == AST_TYPE::IsNot || op_type == AST_TYPE::Is)
return makeBool(op_type == AST_TYPE::IsNot);
ConcreteCompilerVariable* converted_left = var->makeConverted(emitter, INT);
llvm::Value* conv = emitter.getBuilder()->CreateSIToFP(converted_left->getValue(), g.double_);
converted_left->decvref(emitter);
converted_left = new ConcreteCompilerVariable(FLOAT, conv, true);
return converted_left->binexp(emitter, info, rhs, op_type, exp_type);