/
fcc.d
2196 lines (2066 loc) · 76 KB
/
fcc.d
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
module fcc; // feep's crazed compiler
// fcc is licensed under the terms of the GNU General Public License v3 or GPLv3.
import tools.log, tools.compat, tools.smart_import;
alias ast.types.Type Type;
import classgraph;
static import std.gc;
mixin(expandImport(`ast.[
aggregate, aggregate_parse, returns, ifstmt, loops, assign,
structure, variable, fun, unary, arrays, index, slice,
nestfun, structfuns, type_info, aliasing, oop, dg,
newexpr, guard, withstmt, templ, globvars, context,
concat, stringex, c_bind, eval, iterator, iterator_ext, properties,
tuples, tuple_access, literal_string, literals, funcall, vector, externs,
intr, conditionals, opers, conditional_opt, cond, casting,
pointer, nulls, sa_index_opt, intrinsic, mode, repl,
propcall, properties_parse, main, alignment, modules_parse,
platform, math, longmath, base, mixins, int_literal, static_arrays,
enums, import_parse, pragmas, trivial, fp, expr_statement,
typeset, dependency, prefixfun, forex, dominf,
macros, tenth, vardecl_expr, vardecl_parse, property, condprop],
casts, llvmtype, cache`));
alias ast.tuples.resolveTup resolveTup;
alias ast.c_bind.readback readback;
// placed here to resolve circular dependency issues
import ast.parse, ast.namespace, ast.scopes;
// from ast.types
pragma(set_attribute, ast_types_resolveType, externally_visible);
extern(C) IType ast_types_resolveType(IType t, bool carefully = false, bool hard = false) {
if (!hard && t is resolvecache) return t; // shortcut for repeated call
while (t) {
// avoid poking LateTypes if not needed.
if (carefully) if (auto lt = fastcast!(LateType)(t)) return lt;
if (auto tp = t.proxyType()) {
t = tp;
continue;
}
if (hard) {
if (auto ta = fastcast!(TypeAlias)(t)) {
assert(ta.strictFrom || ta.strictTo);
t = ta.base;
continue;
}
if (auto poi = fastcast!(Pointer)(t)) {
auto br = resolveTypeHard(poi.target, carefully);
if (br !is poi.target) {
t = fastalloc!(Pointer)(br);
continue;
}
}
}
break;
}
resolvecache = hard?null:t;
return t;
}
// from ast.modules_parse
mixin DefaultParser!(gotNamed, "tree.expr.named", "25");
const ProgbarLength = 60;
string output;
bool sigmode;
string my_prefix() {
version(Windows) { return path_prefix; }
else return path_prefix ~ platform_prefix;
}
string[] linkerArgs;
string[] processCArgs(string[] ar) {
string[] res;
while (ar.length) {
auto arg = ar.take();
if (arg == "-pthread") continue; // silently ignore;
if (auto define = arg.startsWith("-D").strip()) {
synchronized(defines_sync) defines ~= define.strip();
continue;
}
if (auto rest = arg.startsWith("-l").strip()) {
if (!rest.length) rest = ar.take();
linkerArgs ~= "-l"~rest;
continue;
}
if (auto rest = arg.startsWith("-L").strip()) {
if (!rest.length) rest = ar.take();
linkerArgs ~= "-L"~rest;
continue;
}
if (auto rest = arg.startsWith("-Wl")) {
rest.accept(",");
rest = rest.strip();
if (!rest.length) rest = ar.take();
linkerArgs ~= rest;
continue;
}
if (auto rest = arg.startsWith("-I")) {
rest = rest.strip();
if (!rest.length) rest = ar.take();
include_path = rest ~ include_path;
continue;
}
res ~= arg;
}
return res;
}
string[Tree] ids;
pragma(set_attribute, mangletree, externally_visible);
extern(C) string mangletree(Tree tr) {
if (auto ea = fastcast!(ExprAlias)(tr))
return "ea_"~mangletree(ea.base);
if (auto rce = fastcast!(RCE)(tr))
return "rce_"~rce.to.mangle()~"_"~mangletree(rce.from);
if (auto ie = fastcast!(IntExpr)(tr))
return qformat("ie_", ie.num);
if (auto se = fastcast!(StringExpr)(tr))
return qformat("se_", cleanup(se.str));
synchronized {
if (auto p = tr in ids) return *p;
auto res = qformat("uniquetree_", ids.length);
ids[tr] = res;
return res;
}
logln("tr: ", fastcast!(Object)(tr).classinfo.name, " ", tr);
asm { int 3; }
}
pragma(set_attribute, is_unsafe_fast, externally_visible);
extern(C)
bool is_unsafe_fast() { return current_emitting_function().unsafe_fast; }
static this() {
setupSlice();
setupIndex();
setupIterIndex();
setupConditionalOpt();
bool isStringLiteral(Expr ex) { return !!fastcast!(StringExpr) (collapse(ex)); }
pragmas["fast"] = delegate Object(Expr ex) {
if (ex) throw new Exception("pragma 'fast' does not take arguments");
auto fun = namespace().get!(Function);
if (!fun) throw new Exception("pragma 'fast' must be inside a function");
fun.optimize = true;
releaseMode = true; // it'll be restored at the end of the function - no harm
fun.unsafe_fast = true;
return Single!(NoOp);
};
pragmas["noreturn"] = delegate Object(Expr ex) {
if (!gotImplicitCast(ex, &isStringLiteral))
throw new Exception("pragma 'noreturn' expects name of function");
string str = (fastcast!(StringExpr) (collapse(ex))).str;
auto obj = namespace().lookup(str);
if (!obj) throw new Exception("pragma 'noreturn' cannot find '"~str~"'");
if (auto os = fastcast!(OverloadSet) (obj)) {
foreach (fun; os.funs) fun.noreturn = true;
} else {
auto fun = fastcast!(Function)(obj);
if (!fun) throw new Exception("pragma 'noreturn' expects function, not "~obj.classinfo.name);
fun.noreturn = true;
}
return Single!(NoOp);
};
// Link with this library
pragmas["lib"] = delegate Object(Expr ex) {
if (!gotImplicitCast(ex, &isStringLiteral))
throw new Exception("Lib name expected. ");
string str = (fastcast!(StringExpr) (collapse(ex))).str;
string newarg = "-l" ~ str;
// only add once .. becomes relevant in incremental mode
foreach (arg; extra_linker_args) if (arg == newarg) {
newarg = null;
break;
}
if (newarg) extra_linker_args = newarg ~ extra_linker_args;
return Single!(NoOp);
};
pragmas["pkg-config"] = delegate Object(Expr ex) {
if (!gotImplicitCast(ex, &isStringLiteral))
throw new Exception("pkg-config packet identifier expected. ");
auto pkgname = fastcast!(StringExpr) (collapse(ex)).str;
auto lines = readback("sh -c 'pkg-config --cflags --libs "~pkgname~" 2>&1 || echo pkg-config FAILED'").strip().split("\n");
if (lines[$-1] == "pkg-config FAILED") {
throw new Exception("While evaluating pkg-config pragma for "~pkgname~": "~lines[$-2]);
}
foreach (line; lines)
processCArgs (line.split(" "));
return Single!(NoOp);
};
pragmas["config"] = delegate Object(Expr ex) {
if (!gotImplicitCast(ex, &isStringLiteral))
throw new Exception("pragma(config,...) config script identifier expected. ");
auto configname = fastcast!(StringExpr) (collapse(ex)).str;
auto lines = readback("sh -c '"~configname~"-config --cflags --libs 2>&1 || echo config FAILED'").strip().split("\n");
if (lines[$-1] == "config FAILED") {
throw new Exception("While evaluating config pragma for "~configname~"-config: "~lines[$-2]);
}
foreach (line; lines)
processCArgs (line.split(" "));
return Single!(NoOp);
};
pragmas["binary"] = delegate Object(Expr ex) {
if (!gotImplicitCast(ex, &isStringLiteral))
throw new Exception("Binary name expected. ");
output = (fastcast!(StringExpr) (collapse(ex))).str;
if (isWindoze()) output ~= ".exe";
return Single!(NoOp);
};
pragmas["linker"] = delegate Object(Expr ex) {
if (!gotImplicitCast(ex, (Expr ex) {
return !!fastcast!(StringExpr) (collapse(ex));
}))
throw new Exception("Linker argument expected. ");
string str = (fastcast!(StringExpr) (collapse(ex))).str;
string newarg = "-Wl,"~str;
// only add once .. becomes relevant in incremental mode
foreach (arg; extra_linker_args) if (arg == newarg) {
newarg = null;
break;
}
if (newarg) extra_linker_args = newarg ~ extra_linker_args;
return Single!(NoOp);
};
// from ast.fun
pragmas["internalfn"] = delegate Object(Expr ex) {
opt(ex);
auto se = fastcast!(StringExpr) (ex);
if (!se) fail(qformat("Expected string expression for pragma(internalfn, ...), not ", ex));
auto obj = namespace().lookup(se.str, false);
if (!obj) fail(qformat("Function not found for pragma(internalfn, ...): '", se.str, "' at ", namespace()));
auto fun = fastcast!(Function)(obj);
if (!fun) fail(qformat("Parameter not a function for pragma(internalfn, ...): ", obj));
fun.internalfn = true;
return Single!(NoOp);
};
}
static this() {
New(namespace, { return cast(Namespace) null; });
New(peeky_lookup, { return new bool; });
New(current_module, { return cast(IModule) null; });
// placed here because it needs some circular importage
foldopt ~= delegate Itr(Itr it) {
auto mae = fastcast!(MemberAccess_Expr) (it);
if (!mae || mae.stm.name != "ptr") return null;
auto rce = fastcast!(RCE) (mae.base);
if (!rce) return null;
if (!(rce.to in isArrayStructType)) return null;
auto se = fastcast!(StringExpr) (rce.from);
if (se) return fastcast!(Itr) (se.getPointer());
auto ar = fastcast!(ArrayMaker) (rce.from);
if (ar) return fastcast!(Itr) (ar.ptr);
return null;
};
}
alias ast.parse.startsWith startsWith;
// from ast.namespace
pragma(set_attribute, C_showsAnySignOfHaving, externally_visible);
extern(C) bool C_showsAnySignOfHaving(Expr ex, string thing) {
if (fastcast!(MyPlaceholderExpr) (ex)) return false; // nuh-uh.
auto it = ex.valueType();
if (Single!(Void) == it) return false;
if (auto ns = fastcast!(Namespace) (it)) {
if (ns.lookup(thing)) return true;
}
RelNamespace rns;
if (auto srns = fastcast!(SemiRelNamespace) (it)) rns = srns.resolve();
if (!rns) rns = fastcast!(RelNamespace) (it);
if (rns && rns.lookupRel(thing, ex)) return true;
return false;
}
pragma(set_attribute, _mns_stackframe, externally_visible);
extern(C) Stuple!(IType, string)[] _mns_stackframe(Namespace sup, typeof(Namespace.field) field) {
Stuple!(IType, string)[] res;
if (sup) res = sup.get!(ScopeLike).stackframe();
// variables added to a MiniNamespace are probably taken
// from elsewhere and are **NOT** part of the stackframe!
/*foreach (obj; field)
if (auto var = fastcast!(Variable) (obj._1))
res ~= stuple(var.type, var.name);*/
return res;
}
// text, "is binop safe"
alias Stuple!(string, bool) pptype;
pptype prettyprint_rec(Iterable itr) {
opt(itr);
pptype format_bin(string op, pptype s1, pptype s2) {
string res;
if (s1._1) res ~= s1._0;
else res ~= "("~s1._0~")";
res ~= " " ~ op ~ " ";
if (s2._1) res ~= s2._0;
else res ~= "("~s2._0~")";
return stuple(res, false);
}
string parenwrap(pptype pair) {
if (!pair._1) return qformat("(", pair._0, ")");
return pair._0;
}
if (auto co = fastcast!(Compare)(itr)) {
string op;
if (co.not) op ~= "!";
if (co.smaller) op~= "<";
if (co.equal) op ~= "=";
if (co.greater) op ~= ">";
if (co.equal && !co.smaller && !co.greater && !co.not) op ~= "=";
return format_bin(op, prettyprint_rec(co.e1), prettyprint_rec(co.e2));
}
if (auto ao = fastcast!(AndOp)(itr)) {
return format_bin("&&", prettyprint_rec(ao.c1), prettyprint_rec(ao.c2));
}
if (auto ao = fastcast!(OrOp)(itr)) {
return format_bin("||", prettyprint_rec(ao.c1), prettyprint_rec(ao.c2));
}
if (auto va = fastcast!(Variable)(itr)) {
return stuple(va.name, true);
}
if (auto ie = fastcast!(IntExpr)(itr)) {
return stuple(qformat(ie.num), true);
}
if (auto ew = fastcast!(ExprWrap)(itr)) {
return prettyprint_rec(ew.ex);
}
if (auto rce = fastcast!(RCE)(itr)) {
auto res = prettyprint_rec(rce.from);
auto ex = rce.from;
if (gotImplicitCast(ex, rce.to, (IType it) { return test(it == rce.to); }))
return res; // implicit cast
res._0 = fastcast!(Object)(rce.to).toString()~":"~res._0;
return res;
}
if (auto ea = fastcast!(ExprAlias)(itr)) {
return stuple(ea.name, true);
}
if (auto sae = fastcast!(StatementAndExpr)(itr)) {
return stuple(qformat("{", sae.first, sae.second, "}"), false);
}
if (auto de = fastcast!(DerefExpr)(itr)) {
return stuple(qformat("*", parenwrap(prettyprint_rec(de.src))), true);
}
if (auto re = fastcast!(RefExpr)(itr)) {
return stuple(qformat("&", parenwrap(prettyprint_rec(re.src))), true);
}
if (auto mae = fastcast!(MemberAccess_Expr)(itr)) {
auto base = mae.base;
loopstart:
// (*foo).bar == foo.bar
if (auto de = fastcast!(DerefExpr)(base)) {
base = de.src;
goto loopstart;
}
return stuple(qformat(parenwrap(prettyprint_rec(base)), ".", mae.stm.name), true);
}
return stuple(qformat("TODO ", fastcast!(Object)(itr).classinfo.name, " ", itr), false);
}
// see ast.base
pragma(set_attribute, prettyprint, externally_visible);
extern(C) string prettyprint(Iterable itr) {
return prettyprint_rec(itr)._0;
}
// from ast.vardecl
pragma(set_attribute, freeVar, externally_visible);
extern(C) Statement freeVar(Expr var) {
auto vt = resolveType(var.valueType());
if (fastcast!(Array) (vt) || fastcast!(ExtArray) (vt) || showsAnySignOfHaving(var, "free")) {
return iparse!(Statement, "scope_guard", "tree.stmt")
(`var.free;`, "var", var);
} else if (fastcast!(Delegate) (vt)) {
return iparse!(Statement, "scope_guard", "tree.stmt")
(`dupvfree var.data;`, "var", var);
} else {
return iparse!(Statement, "scope_guard", "tree.stmt")
(`mem.free var;`, "var", var);
}
}
// from ast.fun
static this() {
// Assumption: SysInt is size_t.
Expr fpeq(bool neg, Expr ex1, Expr ex2) {
auto fp1 = fastcast!(FunctionPointer) (ex1.valueType()), fp2 = fastcast!(FunctionPointer) (ex2.valueType());
if (!fp1 || !fp2) return null;
return fastalloc!(Compare)(reinterpret_cast(Single!(SysInt), ex1), neg, false, true, false, reinterpret_cast(Single!(SysInt), ex2));
}
Expr ptreq(bool neg, Expr ex1, Expr ex2) {
auto p1 = fastcast!(Pointer) (resolveType(ex1.valueType())), p2 = fastcast!(Pointer) (resolveType(ex2.valueType()));
if (!p1 || !p2) return null;
// assert(p1.target == p2.target, Format("Cannot compare ", p1, " and ", p2));
return fastalloc!(Compare)(reinterpret_cast(Single!(SysInt), ex1), neg, false, true, false, reinterpret_cast(Single!(SysInt), ex2));
}
defineOp("==", false /apply/ &fpeq);
defineOp("==", false /apply/ &ptreq);
defineOp("!=", true /apply/ &fpeq);
defineOp("!=", true /apply/ &ptreq);
setupPropCall();
}
pragma(set_attribute, rt_print, externally_visible);
extern(C) void rt_print(LLVMFile lf, string s) {
auto printf = sysmod.lookup("printf");
buildFunCall(printf, mkString(s~"\n"), "printf").emitLLVM(lf);
}
// from ast.math
import ast.modules, ast.prefixfun;
void ast_math_constr() {
/*funcall_folds ~= delegate Expr(FunCall fc) {
bool isFabsMath;
auto mod = fastcast!(Module) (fc.fun.sup);
if (fc.fun.name != "fabsf"[] || !fc.fun.extern_c) return null;
auto arg = collapse(fc.getParams()[0]);
return fastalloc!(FAbsFExpr)(arg);
};*/
Expr substfun(int arity, bool delegate(Function, Module) dg, Expr delegate(Expr[]) dgex, FunCall fc) {
if (fc.getParams().length != arity) return null;
auto mod = fastcast!(Module)(fc.fun.sup);
if (!mod) return null;
if (!dg(fc.fun, mod)) return null;
// auto res = dgex(collapse(fc.getParams()[0]));
auto pars = fc.getParams();
foreach (ref par; pars) par = collapse(par);
auto res = dgex(pars);
// logln("subst with ", res);
return res;
}
// NO
// fastfloor is fast
// floorf is slow >.<
/*if (!isWindoze()) {
funcall_folds ~= &substfun /fix/ stuple(1, (Function fun, Module mod) {
return fun.name == "fastfloor" && mod is sysmod;
}, delegate Expr(Expr[] args) {
return fastalloc!(FPAsInt)(lookupOp("+",
fastalloc!(IntrinsicExpr)("llvm.floor.f32"[], args, Single!(Float)),
fastalloc!(FloatExpr)(0.25)));
});
}*/
funcall_folds ~= &substfun /fix/ stuple(2, (Function fun, Module mod) {
return (fun.name == "fminf" || fun.name == "[wrap]fminf") && fun.extern_c;
}, delegate Expr(Expr[] args) { return new MinFloat(args[0], args[1]); });
funcall_folds ~= &substfun /fix/ stuple(2, (Function fun, Module mod) {
return (fun.name == "fmaxf" || fun.name == "[wrap]fmaxf") && fun.extern_c;
}, delegate Expr(Expr[] args) { return new MaxFloat(args[0], args[1]); });
funcall_folds ~= &substfun /fix/ stuple(2, (Function fun, Module mod) {
return (fun.name == "fmin" || fun.name == "[wrap]fmin") && fun.extern_c;
}, delegate Expr(Expr[] args) { return new MinDouble(args[0], args[1]); });
funcall_folds ~= &substfun /fix/ stuple(2, (Function fun, Module mod) {
return (fun.name == "fmax" || fun.name == "[wrap]fmax") && fun.extern_c;
}, delegate Expr(Expr[] args) { return new MaxDouble(args[0], args[1]); });
void addCIntrin(int arity, string funname, IType ret, string intrin, bool argsSameTypeAsReturn = true) {
funcall_folds ~= &substfun /fix/ stuple(arity, stuple(funname) /apply/ (string funname, Function fun, Module mod) {
return (fun.name == funname || fun.name == qformat("[wrap]", funname)) && fun.extern_c;
}, stuple(intrin, ret, argsSameTypeAsReturn) /apply/ delegate Expr(string intrin, IType ret, bool argsSameTypeAsReturn, Expr[] args) {
if (argsSameTypeAsReturn) foreach (ref arg; args) {
if (!gotImplicitCast(arg, ret, (IType it) { return test(ret == it); }))
throw new Exception("invalid argument for intrinsic");
}
return fastalloc!(IntrinsicExpr)(intrin, args, ret);
});
}
addCIntrin(1, "sqrtf" , Single!(Float), "llvm.sqrt.f32");
addCIntrin(1, "sqrt" , Single!(Double), "llvm.sqrt.f64");
// do in software, intrinsic is slow
// addCIntrin(1, "sinf" , Single!(Float), "llvm.sin.f32");
// addCIntrin(1, "sin" , Single!(Double), "llvm.sin.f64");
// addCIntrin(1, "cosf" , Single!(Float), "llvm.cos.f32");
// addCIntrin(1, "cos" , Single!(Double), "llvm.cos.f64");
// not supported on it
if (llvmver() > 31) {
if (!isWindoze()) {
addCIntrin(1, "floorf", Single!(Float), "llvm.floor.f32");
}
addCIntrin(1, "fabsf" , Single!(Float), "llvm.fabs.f32");
addCIntrin(1, "fabs" , Single!(Double), "llvm.fabs.f64");
}
if (llvmver() >= 37) {
// addCIntrin(2, "fminf" , Single!(Float), "llvm.minnum.f32");
// addCIntrin(2, "fmin" , Single!(Double), "llvm.minnum.f64");
// addCIntrin(2, "fmaxf" , Single!(Float), "llvm.maxnum.f32");
// addCIntrin(2, "fmax" , Single!(Double), "llvm.maxnum.f64");
addCIntrin(2, "copysignf", Single!(Float), "llvm.copysign.f32");
addCIntrin(2, "copysign", Single!(Double), "llvm.copysign.f64");
}
addCIntrin(1, "exp" , Single!(Float), "llvm.exp.f32");
addCIntrin(1, "log" , Single!(Float), "llvm.log.f32");
addCIntrin(2, "powf" , Single!(Float), "llvm.pow.f32");
addCIntrin(4, "prefetch", Single!(Void), "llvm.prefetch", false);
bool isInt(IType it) { return test(Single!(SysInt) == it); }
bool isSizeT(IType it) { return test(Single!(SizeT) == it); }
bool isFloat(IType it) { return test(Single!(Float) == it); }
bool isDouble(IType it) { return test(Single!(Double) == it); }
bool isLong(IType it) { return test(Single!(Long) == it); }
bool isPointer(IType it) { return test(fastcast!(Pointer)~ it); }
bool isBool(IType it) { if (!sysmod) return false; return exactlyEquals(it, fastcast!(IType)(sysmod.lookup("bool"))); }
Expr handleIntMath(string op, Expr ex1, Expr ex2) {
bool b1 = isBool(ex1.valueType()), b2 = isBool(ex2.valueType());
Expr i1 = ex1, i2 = ex2, u1, u2;
if (!gotImplicitCast(i1, Single!(SysInt), &isInt )) i1 = null;
if (!gotImplicitCast(i2, Single!(SysInt), &isInt )) i2 = null;
// delay as far as possible
void initU1() { if (u1) return; u1 = ex1; if (!gotImplicitCast(u1, Single!(SizeT), &isSizeT)) u1 = null; }
void initU2() { if (u2) return; u2 = ex2; if (!gotImplicitCast(u2, Single!(SizeT), &isSizeT)) u2 = null; }
// if (!i1 && !u1 || !i2 && !u2) return null;
if (!i1) { initU1; if (!u1) return null; }
if (!i2) { initU2; if (!u2) return null; }
// if (!(i1 && i2 || u1 && u2)) return null; // cannot mix
if (!(i1 && i2)) {
initU1;
initU2;
if (!(u1 && u2)) return null;
}
Expr res;
bool ntcache, ntcached;
bool nontrivial() {
if (ntcached) return ntcache;
auto ie1 = fastcast!(IntExpr) (collapse(ex1));
if (!ie1) { ntcache = ntcached = true; return true; }
auto ie2 = fastcast!(IntExpr) (collapse(ex2));
if (!ie2) { ntcache = ntcached = true; return true; }
ntcached = true; ntcache = false; return false;
}
if (!res) {
if (i1 && i2)
res = fastalloc!(AsmIntBinopExpr)(i1, i2, op, false);
else
res = fastalloc!(AsmIntBinopExpr)(u1, u2, op, true);
/*if (qformat(res).find("+ 0) + 0) + 0) + 0) + 0) + 0) + 0)") != -1) {
logln("?? ", res);
fail;*/
}
if (b1 && b2) res = reinterpret_cast(fastcast!(IType) (sysmod.lookup("bool")), res);
return res;
}
Expr handleSizeTUnary(string op, Expr ex) {
if (!gotImplicitCast(ex, Single!(SizeT), &isSizeT))
return null;
return fastalloc!(AsmIntUnaryExpr)(ex, op);
}
Expr handleLongUnary(string op, Expr ex) {
if (!gotImplicitCast(ex, Single!(Long), &isLong))
return null;
return fastalloc!(AsmLongUnaryExpr)(ex, op);
}
Expr handleNeg(Expr ex) {
return lookupOp("-", mkInt(0), ex);
}
Expr handlePointerMath(string op, Expr ex1, Expr ex2) {
Pointer e1pt;
if (auto p = fastcast!(Pointer) (resolveTup(ex2.valueType()))) {
if (op == "-") {
// return null; // wut
// pointer - pointer is defined! (if they have the same types)
auto p2 = fastcast!(Pointer)(resolveTup(ex1.valueType()));
if (p != p2) return null;
} else {
swap(ex1, ex2);
e1pt = p;
}
}
if (!e1pt) e1pt = fastcast!(Pointer) (resolveTup(ex1.valueType()));
if (!e1pt) return null;
auto e2pt = fastcast!(Pointer) (resolveTup(ex2.valueType()));
if (e2pt) {
return handleIntMath("/",
handleIntMath("-",
reinterpret_cast(Single!(SysInt), ex1),
reinterpret_cast(Single!(SysInt), ex2)
),
llvmval(e1pt.target.llvmSize())
);
}
if (fastcast!(Float) (ex2.valueType())) {
logln(ex1, " ", op, " ", ex2, "; WTF?! ");
logln("is ", ex1.valueType(), " and ", ex2.valueType());
// fail();
throw new Exception("Invalid pointer op");
}
Expr ex2index = ex2; // ex2 without the * size step
if (auto ie = fastcast!(IntExpr) (ex2)) { // shortcut
ex2 = llvmval(llmul(qformat(ie.num), e1pt.target.llvmSize()));
} else {
ex2 = handleIntMath("*", ex2, llvmval(e1pt.target.llvmSize()));
}
if (!ex2) return null;
if (op == "+") return fastalloc!(RefExpr)(fastalloc!(PointerIndexAccess)(ex1, ex2index));
return reinterpret_cast(ex1.valueType(), handleIntMath(op, reinterpret_cast(Single!(SizeT), ex1), reinterpret_cast(Single!(SizeT), ex2)));
}
Expr handleFloatMath(string op, Expr ex1, Expr ex2) {
if (Single!(Double) == ex1.valueType()) {
ex1 = collapse(ex1);
if (!fastcast!(DoubleExpr) (ex1))
return null;
}
if (Single!(Double) == ex2.valueType()) {
ex2 = collapse(ex2);
if (!fastcast!(DoubleExpr) (ex2))
return null;
}
if (fastcast!(DoubleExpr) (ex1) && fastcast!(DoubleExpr) (ex2)) return null;
if (!gotImplicitCast(ex1, Single!(Float), &isFloat) || !gotImplicitCast(ex2, Single!(Float), &isFloat))
return null;
return fastalloc!(AsmFloatBinopExpr)(ex1, ex2, op);
}
Expr handleDoubleMath(string op, Expr ex1, Expr ex2) {
if (Single!(Double) != resolveTup(ex1.valueType())
&& Single!(Double) != resolveTup(ex2.valueType()))
return null;
if (!gotImplicitCast(ex1, Single!(Double), &isDouble) || !gotImplicitCast(ex2, Single!(Double), &isDouble))
return null;
return fastalloc!(AsmDoubleBinopExpr)(ex1, ex2, op);
}
Expr handleLongMath(string op, Expr ex1, Expr ex2) {
/*if (Single!(Long) != resolveTup(ex1.valueType())
&& Single!(Long) != resolveTup(ex2.valueType()))
return null;*/
if (!gotImplicitCast(ex1, Single!(Long), &isLong) || !gotImplicitCast(ex2, Single!(Long), &isLong))
return null;
return mkLongExpr(ex1, ex2, op);
}
void defineOps(Expr delegate(string op, Expr, Expr) dg, bool reduced = false) {
string[] ops;
if (reduced) ops = ["+", "-"]; // pointer math
else ops = ["+", "-", "&", "|", "*", "/", "%", "<<", ">>", ">>>", "xor"];
foreach (op; ops)
defineOp(op, op /apply/ dg);
}
defineOp("¬", "¬" /apply/ &handleSizeTUnary);
defineOp("¬", "¬" /apply/ &handleLongUnary);
defineOp("-", &handleNeg);
defineOps(&handleIntMath);
defineOps(&handleFloatMath);
defineOps(&handleDoubleMath);
defineOps(&handlePointerMath, true);
defineOps(&handleLongMath);
defineOp("^", delegate Expr(Expr ex1, Expr ex2) {
if (gotImplicitCast(ex2, Single!(SysInt), &isInt)) {
if (auto ie = fastcast!(IntExpr)(collapse(ex2))) {
if (ie.num == 0) return fastalloc!(IntExpr)(1);
return tmpize_maybe(ex1, (Expr ex1) { // a^3 should only evaluate a once!
auto res = ex1;
for (int i = 1; i < ie.num; ++i) {
res = lookupOp("*", res, ex1);
}
return res;
});
}
}
return null;
});
}
pragma(set_attribute, printThing, externally_visible);
extern(C) void printThing(LLVMFile lf, string s, Expr ex) {
(buildFunCall(sysmod.lookup("printf"), mkTupleExpr(mkString(s), ex), "mew")).emitLLVM(lf);
}
pragma(set_attribute, fcc_wte_collapse, externally_visible);
extern(C) Expr fcc_wte_collapse(WithTempExpr wte) {
int llc, llrefc;
void countUses(ref Iterable it) {
if (it is wte.val) llc ++;
else if (it is wte.lltemp) llrefc ++;
else it.iterate(&countUses);
}
{ Iterable it = wte.superthing; countUses(it); }
if (llc != 1 || llrefc > 0) {
// logln("bad form ", wte.superthing);
return wte;
}
void replace(ref Iterable it) {
if (it is wte.val) it = wte.thing;
else it.iterate(&replace);
}
Expr res = wte.superthing.dup;
{ Iterable it = res; replace(it); res = fastcast!(Expr)(it); }
// logln("success: ", wte, " to ", res);
return res;
}
pragma(set_attribute, fcc_assignment_collapse, externally_visible);
extern(C) Tree fcc_assignment_collapse(Tree tr) {
auto as = fastcast!(Assignment)(tr);
if (!as) return tr;
// decompose struct assign into {member assigns} for better llvm compat
auto value = as.value, target = as.target;
IType vvt; string llt; Structure st;
void regenInfo() {
vvt = resolveType(value.valueType());
llt = typeToLLVM(vvt);
st = fastcast!(Structure)(vvt);
}
regenInfo();
if (!st) {
if (!llt.endsWith("}")) return tr;
if (!!fastcast!(Array)(vvt) || fastcast!(ExtArray)(vvt)) {
value = arrayToStruct(value);
target = arrayToStruct(target);
regenInfo();
} else if (fastcast!(Delegate)(vvt)) {
value = dgAsStruct(value);
target = fastcast!(LValue)(dgAsStruct(target));
regenInfo();
}
}
if (auto st = fastcast!(Structure)(vvt)) {
if (!_is_cheap(value, CheapMode.Flatten)) {
// logln("not cheap 1: ", value);
return tr;
}
if (!_is_cheap(target, CheapMode.Flatten)) {
// logln("not cheap 2: ", target);
return tr;
}
auto from = splitStruct(value), to = splitStruct(target);
if (from.length != to.length) fail;
auto ags = fastalloc!(AggrStatement)();
foreach (i, sfrom; from) {
auto sto = to[i];
ags.stmts ~= mkAssignment(sto, sfrom);
}
return ags;
} else {
// if (llt.endsWith("}")) logln("not struct: ", resolveType(value.valueType()), " but ", llt);
}
return tr;
}
// from ast.fun
import ast.casting;
Object gotFunRefExpr(ref string text, ParseCb cont, ParseCb rest) {
if (text.startsWith("&")) return null;
Object obj;
if (!rest(text, "tree.expr _tree.expr.bin"[], &obj)) return null;
if (auto fun = fastcast!(Function) (obj)) {
return fastalloc!(FunRefExpr)(fun);
}
if (auto os = fastcast!(OverloadSet) (obj)) {
Function matched;
foreach (fun; os.funs) {
if (fastcast!(PrefixFunction) (fun)) continue;
if (matched) { text.setError("Cannot take address of overload set"); return null; }
matched = fun;
}
if (matched) return fastalloc!(FunRefExpr)(matched);
}
return null;
}
mixin DefaultParser!(gotFunRefExpr, "tree.expr.fun_ref"[], "2101"[], "&"[]);
// from ast.structure
static this() {
Expr handleStructOp(string op, string opname, Expr lhs, Expr rhs) {
if (!showsAnySignOfHaving(lhs, opname)) return null;
auto v1 = lhs.valueType(), v2 = rhs.valueType();
auto rns = fastcast!(RelNamespace)(resolveType(v1));
if (!rns) fail;
auto opfun = rns.lookupRel(opname, lhs);
// first, try extended pointer form since it's more efficient
// that is. instead of "lhs.op rhs", try "{lhs.op(&rhs, &auto res); return res;}"
// or "{lhs.op(rhs, &auto res); return res;}"
IType checkFunForPointerOpCall(Function fun, out bool argIsPointerToo) {
auto args = fun.getParams(false);
if (args.length == 2) {
auto rhs2 = rhs;
IType ptrtype;
if (auto rhsptr = fastcast!(Pointer)(resolveType(args[0].type))) {
// logln("yep it's a pointer, see if we can get ", rhs2.valueType(), " into ", rhsptr.target);
if (gotImplicitCast(rhs2, rhsptr.target, (IType it) { return test(it == rhsptr.target); })) {
argIsPointerToo = true;
ptrtype = args[1].type;
}
} else {
// logln("nope not a pointer, see if we can get ", rhs2.valueType(), " into ", args[0].type);
if (gotImplicitCast(rhs2, args[0].type, (IType it) { return test(it == args[0].type); })) {
argIsPointerToo = false;
ptrtype = args[1].type;
}
}
if (ptrtype) {
auto ptr = fastcast!(Pointer)(ptrtype);
if (ptr) return ptr.target;
}
}
return null;
}
Expr tryPointerCall(Function f) {
bool argIsPointerToo;
if (auto restype = checkFunForPointerOpCall(f, argIsPointerToo)) {
// reserve a result of type restype
return tmpize(rhs, (Expr rhs, LLVMRef res) {
// logln("detect pointer op call, ", argIsPointerToo, " for ", f);
if (!argIsPointerToo) {
res.type = restype;
auto call = buildFunCall(f, mkTupleExpr(rhs, fastalloc!(RefExpr)(res)), "direct arg op overload pointer res call");
if (!call) fail;
return mkStatementAndExpr(fastalloc!(ExprStatement)(call), res);
} else {
Expr doWith(LValue rhs, LValue res) {
auto call = buildFunCall(f, mkTupleExpr(fastalloc!(RefExpr)(rhs), fastalloc!(RefExpr)(res)), "pointer arg op overload pointer res call");
if (!call) {
logln("couldn't call ", f.getParams(false), " with a ", mkTupleExpr(fastalloc!(RefExpr)(rhs), fastalloc!(RefExpr)(res)).valueType());
fail;
}
return mkStatementAndExpr(fastalloc!(ExprStatement)(call), res);
}
res.type = mkTuple(restype, rhs.valueType()); // need to copy both so we can take a pointer
auto tup_0 = fastcast!(LValue)(mkTupleIndexAccess(res, 0));
auto tup_1 = fastcast!(LValue)(mkTupleIndexAccess(res, 1));
if (!tup_0 || !tup_1) fail;
auto as = mkAssignment(tup_1, rhs);
auto ex = doWith(tup_1, tup_0);
return mkStatementAndExpr(as, ex);
}
});
}
return null;
}
if (auto fun = fastcast!(Function)(opfun)) {
if (auto res = tryPointerCall(fun)) return res;
} else if (auto os = fastcast!(OverloadSet)(opfun)) {
foreach (osfun; os.funs)
if (auto res = tryPointerCall(osfun)) return res;
}
if (auto call = buildFunCall(opfun, rhs, "struct operator overload call")) return call; // straightforward
/*if (auto res = iparse!(Expr, "operator_overload", "tree.expr _tree.expr.bin")
(`lhs.`~opname~` rhs`, "lhs", lhs, "rhs", rhs)) {
return res;
}*/
// throw new Exception(qformat("op ", opname, " = ", opfun, " did not match ", rhs.valueType(), " ", v2));
return null;
}
void defineStructOp(string op, string opname) {
defineOp(op, stuple(op, opname) /apply/ &handleStructOp);
}
defineStructOp("+", "opAdd");
defineStructOp("-", "opSub");
defineStructOp("*", "opMul");
defineStructOp("/", "opDiv");
defineStructOp("%", "opMod");
defineStructOp("&", "opAnd");
defineStructOp("|", "opOr");
}
Object gotAsType(ref string text, ParseCb cont, ParseCb rest) {
string ident;
auto t2 = text;
if (t2.accept("(") && t2.gotIdentifier(ident) && t2.accept(")")) {
text = t2;
} else {
if (!text.gotIdentifier(ident)) text.failparse("Identifier expected for as_type");
}
auto ta = fastalloc!(TypeAlias)(cast(IType) null, ident);
{
auto as_type_ns = fastalloc!(MiniNamespace)("as_type_ident_override");
as_type_ns.sup = namespace();
as_type_ns.internalMode = true;
as_type_ns.add(ta);
namespace.set(as_type_ns);
scope(exit) namespace.set(as_type_ns.sup);
if (!rest(text, "type", &ta.base))
text.failparse("Type expected");
}
return ta;
}
mixin DefaultParser!(gotAsType, "type.as_type", "8", "as_type");
// from ast.casting
import llvmfile, ast.vardecl;
alias ast.types.typeToLLVM typeToLLVM;
pragma(set_attribute, _reinterpret_cast_expr, externally_visible);
extern(C) void _reinterpret_cast_expr(RCE rce, LLVMFile lf) {
string v = save(lf, rce.from);
string from = typeToLLVM(rce.from.valueType()), to = typeToLLVM(rce.to);
// logln("rce ", rce, " (", rce.from.valueType(), ", ", rce.to, "): ", from, " -> ", to);
llcast(lf, from, to, v, rce.from.valueType().llvmSize());
}
pragma(set_attribute, llcast, externally_visible);
extern(C) void llcast(LLVMFile lf, string from, string to, string v, string fromsize = null) {
if (from != to) {
checkcasttypes(from, to);
if (from.endsWith("}") || from.endsWith("]") || from.endsWith(">") || to.endsWith("}") || to.endsWith("]")) {
if ((from.endsWith("}") || from.endsWith(">"))&& (to.endsWith("}") || to.endsWith(">"))) {
bool fromIsStruct = !!from.endsWith("}"), toIsStruct = !!to.endsWith("}");
string[] a, b;
if (fromIsStruct) llvmtype.structDecompose(from, (string s) { a ~= s; });
else a = getVecTypes(from);
if ( toIsStruct) llvmtype.structDecompose( to, (string s) { b ~= s; });
else b = getVecTypes( to);
if (a.length == b.length) {
bool samelayout = true;
foreach (i, t1; a) {
auto t2 = b[i];
// if types are not (the same or both pointers)
if (!(t1 == t2 || t1.endsWith("*") && t2.endsWith("*"))) {
samelayout = false;
break;
}
}
if (samelayout) {
// logln("use elaborate conversion for ", from, " -> ", to);
// extract, cast and recombine
string res = "undef";
foreach (i, t1; a) {
auto t2 = b[i];
string val;
if (fromIsStruct) val = extractvalue(lf, t1, from, v, i);
else val = save(lf, "extractelement ", from, " ", v, ", i32 ", i);
if (t1 != t2) {
llcast(lf, t1, t2, val);
val = lf.pop();
}
if (toIsStruct) res = save(lf, "insertvalue ", to, " ", res, ", ", t2, " ", val, ", ", i);
else res = save(lf, "insertelement ", to, " ", res, ", ", t2, " ", val, ", i32 ", i);
}
lf.push(res);
return;
}
}
}
if (llvmTypeIs16Aligned(from)) {
auto ap = alloca(lf, "1", from);
auto fs = bitcastptr(lf, from, to, ap);
splitstore(lf, from, v, from, ap, false);
// put(lf, "store ", from, " ", v, ", ", from, "* ", ap);
ll_load(lf, to, fs);
v = lf.pop();
} else {
auto ap = alloca(lf, "1", to);
auto fs = bitcastptr(lf, to, from, ap);
splitstore(lf, from, v, from, fs, false);
// put(lf, "store ", from, " ", v, ", ", from, "* ", fs);
ll_load(lf, to, ap);
v = lf.pop();
}
} else if (from.endsWith("*") && to == "i32") {
v = save(lf, "ptrtoint ", from, " ", v, " to i32");
} else if (from == "i32" && to.endsWith("*")) {
v = save(lf, "inttoptr i32 ", v, " to ", to);
} else {
v = save(lf, "bitcast ", from, " ", v, " to ", to);
}
}
push(lf, v);
}
pragma(set_attribute, _exactly_equals, externally_visible);
extern(C) bool _exactly_equals(IType a, IType b) {
auto pa = fastcast!(Pointer)~ a, pb = fastcast!(Pointer)~ b;
if (pa && pb) return _exactly_equals(pa.target, pb.target);
if (!pa && pb || pa && !pb) return false;
IType resolveMyType(IType it) {
if (fastcast!(TypeAlias) (it)) return it;
if (auto tp = it.proxyType())
return resolveMyType(tp);
return it;
}
auto
ta = fastcast!(ast.tuples.Tuple)(resolveMyType(a)),
tb = fastcast!(ast.tuples.Tuple)(resolveMyType(b));
if ( ta && tb) return ta is tb;
if (!ta && tb) return false;
if ( ta && !tb) return false;
auto
ca = fastcast!(TypeAlias) (resolveMyType(a)),
cb = fastcast!(TypeAlias) (resolveMyType(b));
if (!ca && !cb) return test(a == b);
if ( ca && !cb) return false;
if (!ca && cb) return false;
if ( ca && cb) return (ca.name == cb.name) && _exactly_equals(ca.base, cb.base);
}