forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzer.js
1781 lines (1692 loc) · 73.3 KB
/
analyzer.js
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
//"use strict";
// Analyze intertype data. Calculates things that are necessary in order
// to do the final conversion into JavaScript later, for example,
// properties of variables, loop structures of functions, etc.
var VAR_NATIVE = 'native';
var VAR_NATIVIZED = 'nativized';
var VAR_EMULATED = 'emulated';
var ENTRY_IDENT = toNiceIdent('%0');
function recomputeLines(func) {
func.lines = func.labels.map(function(label) { return label.lines }).reduce(concatenator, []);
}
// Handy sets
var BRANCH_INVOKE = set('branch', 'invoke');
var LABEL_ENDERS = set('branch', 'return', 'switch');
var SIDE_EFFECT_CAUSERS = set('call', 'invoke', 'atomic');
var UNUNFOLDABLE = set('value', 'structvalue', 'type', 'phiparam');
var SHADOW_FLIP = { i64: 'double', double: 'i64' }; //, i32: 'float', float: 'i32' };
// Analyzer
function analyzer(data, sidePass) {
//B.start('analyzer');
var mainPass = !sidePass;
var item = { items: data };
var data = item;
var newTypes = {};
// Gather
// Single-liners
['globalVariable', 'functionStub', 'unparsedFunction', 'unparsedGlobals', 'unparsedTypes', 'alias'].forEach(function(intertype) {
var temp = splitter(item.items, function(item) { return item.intertype == intertype });
item.items = temp.leftIn;
item[intertype + 's'] = temp.splitOut;
});
var temp = splitter(item.items, function(item) { return item.intertype == 'type' });
item.items = temp.leftIn;
temp.splitOut.forEach(function(type) {
//dprint('types', 'adding defined type: ' + type.name_);
Types.types[type.name_] = type;
newTypes[type.name_] = 1;
if (QUANTUM_SIZE === 1) {
Types.fatTypes[type.name_] = copy(type);
}
});
// Functions & labels
item.functions = [];
var currLabelFinished = false; // Sometimes LLVM puts a branch in the middle of a label. We need to ignore all lines after that.
item.items.sort(function(a, b) { return a.lineNum - b.lineNum });
for (var i = 0; i < item.items.length; i++) {
var subItem = item.items[i];
assert(subItem.lineNum);
if (subItem.intertype == 'function') {
item.functions.push(subItem);
subItem.endLineNum = null;
subItem.lines = []; // We will fill in the function lines after the legalizer, since it can modify them
subItem.labels = [];
subItem.forceEmulated = false;
// no explicit 'entry' label in clang on LLVM 2.8 - most of the time, but not all the time! - so we add one if necessary
if (item.items[i+1].intertype !== 'label') {
item.items.splice(i+1, 0, {
intertype: 'label',
ident: ENTRY_IDENT,
lineNum: subItem.lineNum + '.5'
});
}
} else if (subItem.intertype == 'functionEnd') {
item.functions.slice(-1)[0].endLineNum = subItem.lineNum;
} else if (subItem.intertype == 'label') {
item.functions.slice(-1)[0].labels.push(subItem);
subItem.lines = [];
currLabelFinished = false;
} else if (item.functions.length > 0 && item.functions.slice(-1)[0].endLineNum === null) {
// Internal line
if (!currLabelFinished) {
item.functions.slice(-1)[0].labels.slice(-1)[0].lines.push(subItem); // If this line fails, perhaps missing a label?
if (subItem.intertype in LABEL_ENDERS) {
currLabelFinished = true;
}
} else {
print('// WARNING: content after a branch in a label, line: ' + subItem.lineNum);
}
} else {
throw 'ERROR: what is this? ' + dump(subItem);
}
}
delete item.items;
// CastAway - try to remove bitcasts of double<-->i64, which LLVM sometimes generates unnecessarily
// (load a double, convert to i64, use as i64).
// We optimize this by checking if there are such bitcasts. If so we create a shadow
// variable that is of the other type, and use that in the relevant places. (As SSA, this is valid, and
// variable elimination later will remove the double load if it is no longer needed.)
//
// Note that aside from being an optimization, this is needed for correctness in some cases: If code
// assumes it can bitcast a double to an i64 and back and forth without loss, that may be violated
// due to NaN canonicalization.
function castAway() {
if (USE_TYPED_ARRAYS != 2) return;
item.functions.forEach(function(func) {
var has = false;
func.labels.forEach(function(label) {
var lines = label.lines;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.intertype == 'bitcast' && line.type in SHADOW_FLIP) {
has = true;
}
}
});
if (!has) return;
// there are integer<->floating-point bitcasts, create shadows for everything
var shadowed = {};
func.labels.forEach(function(label) {
var lines = label.lines;
var i = 0;
while (i < lines.length) {
var lines = label.lines;
var line = lines[i];
if (line.intertype == 'load' && line.type in SHADOW_FLIP) {
if (line.pointer.intertype != 'value') { i++; continue } // TODO
shadowed[line.assignTo] = 1;
var shadow = line.assignTo + '$$SHADOW';
var flip = SHADOW_FLIP[line.type];
lines.splice(i + 1, 0, { // if necessary this element will be legalized in the next phase
tokens: null,
indent: 2,
lineNum: line.lineNum + 0.5,
assignTo: shadow,
intertype: 'load',
pointerType: flip + '*',
type: flip,
valueType: flip,
pointer: {
intertype: 'value',
ident: line.pointer.ident,
type: flip + '*'
},
align: line.align,
ident: line.ident
});
// note: no need to update func.lines, it is generated in a later pass
i++;
}
i++;
}
});
// use shadows where possible
func.labels.forEach(function(label) {
var lines = label.lines;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.intertype == 'bitcast' && line.type in SHADOW_FLIP && line.ident in shadowed) {
var shadow = line.ident + '$$SHADOW';
line.params[0].ident = shadow;
line.params[0].type = line.type;
line.type2 = line.type;
}
}
});
});
}
// Legalize LLVM unrealistic types into realistic types.
//
// With full LLVM optimizations, it can generate types like i888 which do not exist in
// any actual hardware implementation, but are useful during optimization. LLVM then
// legalizes these types into real ones during code generation. Sadly, there is no LLVM
// IR pass to legalize them, which would have been useful and nice from a design perspective.
// The LLVM community is also not interested in receiving patches to implement that
// functionality, since it would duplicate existing code from the code generation
// component. Therefore, we implement legalization here in Emscripten.
//
// Currently we just legalize completely unrealistic types into bundles of i32s, and just
// the most common instructions that can be involved with such types: load, store, shifts,
// trunc and zext.
function legalizer() {
// Legalization
if (USE_TYPED_ARRAYS == 2) {
function getLegalVars(base, bits, allowLegal) {
bits = bits || 32; // things like pointers are all i32, but show up as 0 bits from getBits
if (allowLegal && bits <= 32) return [{ intertype: 'value', ident: base + ('i' + bits in Compiletime.INT_TYPES ? '' : '$0'), bits: bits, type: 'i' + bits }];
if (isNumber(base)) return getLegalLiterals(base, bits);
if (base[0] == '{') {
warnOnce('seeing source of illegal data ' + base + ', likely an inline struct - assuming zeroinit');
return getLegalLiterals('0', bits);
}
var ret = new Array(Math.ceil(bits/32));
var i = 0;
if (base == 'zeroinitializer' || base == 'undef') base = 0;
while (bits > 0) {
ret[i] = { intertype: 'value', ident: base ? base + '$' + i : '0', bits: Math.min(32, bits), type: 'i' + Math.min(32, bits) };
bits -= 32;
i++;
}
return ret;
}
function getLegalLiterals(text, bits) {
var parsed = parseArbitraryInt(text, bits);
var ret = new Array(Math.ceil(bits/32));
var i = 0;
while (bits > 0) {
ret[i] = { intertype: 'value', ident: (parsed[i]|0).toString(), bits: Math.min(32, bits), type: 'i' + Math.min(32, bits) }; // resign all values
bits -= 32;
i++;
}
return ret;
}
function getLegalStructuralParts(value) {
return value.params.slice(0);
}
function getLegalParams(params, bits) {
return params.map(function(param) {
var value = param.value || param;
if (isNumber(value.ident)) {
return getLegalLiterals(value.ident, bits);
} else if (value.intertype == 'structvalue') {
return getLegalStructuralParts(value).map(function(part) {
part.bits = part.type.substr(1); // can be some nested IR, like LLVM calls
return part;
});
} else {
return getLegalVars(value.ident, bits);
}
});
}
// Uses the right factor to multiply line numbers by so that they fit in between
// the line[i] and the line after it
function interpLines(lines, i, toAdd) {
var prev = i >= 0 ? lines[i].lineNum : -1;
var next = (i < lines.length-1) ? lines[i+1].lineNum : (lines[i].lineNum + 0.5);
var factor = (next - prev)/(4*toAdd.length+3);
for (var k = 0; k < toAdd.length; k++) {
toAdd[k].lineNum = prev + ((k+1)*factor);
assert(k == 0 || toAdd[k].lineNum > toAdd[k-1].lineNum);
}
}
function removeAndAdd(lines, i, toAdd) {
var item = lines[i];
interpLines(lines, i, toAdd);
Array.prototype.splice.apply(lines, [i, 1].concat(toAdd));
if (i > 0) assert(lines[i].lineNum > lines[i-1].lineNum);
if (i + toAdd.length < lines.length) assert(lines[i + toAdd.length - 1].lineNum < lines[i + toAdd.length].lineNum);
return toAdd.length;
}
function legalizeFunctionParameters(params) {
var i = 0;
while (i < params.length) {
var param = params[i];
if (param.intertype == 'value' && isIllegalType(param.type)) {
var toAdd = getLegalVars(param.ident, getBits(param.type)).map(function(element) {
return {
intertype: 'value',
type: 'i' + element.bits,
ident: element.ident,
byval: 0
};
});
Array.prototype.splice.apply(params, [i, 1].concat(toAdd));
i += toAdd.length;
continue;
} else if (param.intertype == 'structvalue') {
// 'flatten' out the struct into scalars
var toAdd = param.params;
toAdd.forEach(function(param) {
param.byval = 0;
});
Array.prototype.splice.apply(params, [i, 1].concat(toAdd));
continue; // do not increment i; proceed to process the new params
}
i++;
}
}
function fixUnfolded(item) {
// Unfolded items may need some correction to work properly in the global scope
if (item.intertype in MATHOPS) {
item.op = item.intertype;
item.intertype = 'mathop';
}
}
data.functions.forEach(function(func) {
// Legalize function params
legalizeFunctionParameters(func.params);
// Legalize lines in labels
var tempId = 0;
func.labels.forEach(function(label) {
if (dcheck('legalizer')) dprint('zz legalizing: \n' + dump(label.lines));
var i = 0, bits;
while (i < label.lines.length) {
var item = label.lines[i];
var value = item;
// Check if we need to legalize here, and do some trivial legalization along the way
var isIllegal = false;
walkInterdata(item, function(item) {
if (item.intertype == 'getelementptr' || (item.intertype == 'call' && item.ident in LLVM.INTRINSICS_32)) {
// Turn i64 args into i32
for (var i = 0; i < item.params.length; i++) {
if (item.params[i].type == 'i64') item.params[i].type = 'i32';
}
} else if (item.intertype == 'inttoptr') {
var input = item.params[0];
if (input.type == 'i64') input.type = 'i32'; // inttoptr can only care about 32 bits anyhow since pointers are 32-bit
}
if (isIllegalType(item.valueType) || isIllegalType(item.type)) {
isIllegal = true;
} else if ((item.intertype == 'load' || item.intertype == 'store') && isStructType(item.valueType)) {
isIllegal = true; // storing an entire structure is illegal
} else if (item.intertype == 'mathop' && item.op == 'trunc' && isIllegalType(item.params[1].ident)) { // trunc stores target value in second ident
isIllegal = true;
}
});
if (!isIllegal) {
//if (dcheck('legalizer')) dprint('no need to legalize \n' + dump(item));
i++;
continue;
}
// Unfold this line. If we unfolded, we need to return and process the lines we just
// generated - they may need legalization too
var unfolded = [];
walkAndModifyInterdata(item, function(subItem) {
// Unfold all non-value interitems that we can, and also unfold all numbers (doing the latter
// makes it easier later since we can then assume illegal expressions are always variables
// accessible through ident$x, and not constants we need to parse then and there)
if (subItem != item && (!(subItem.intertype in UNUNFOLDABLE) ||
(subItem.intertype == 'value' && isNumber(subItem.ident) && isIllegalType(subItem.type)))) {
if (item.intertype == 'phi') {
assert(subItem.intertype == 'value' || subItem.intertype == 'structvalue' || subItem.intertype in PARSABLE_LLVM_FUNCTIONS, 'We can only unfold some expressions in phis');
// we must handle this in the phi itself, if we unfold normally it will not be pushed back with the phi
} else {
var tempIdent = '$$etemp$' + (tempId++);
subItem.assignTo = tempIdent;
unfolded.unshift(subItem);
fixUnfolded(subItem);
return { intertype: 'value', ident: tempIdent, type: subItem.type };
}
} else if (subItem.intertype == 'switch' && isIllegalType(subItem.type)) {
subItem.switchLabels.forEach(function(switchLabel) {
if (switchLabel.value[0] != '$') {
var tempIdent = '$$etemp$' + (tempId++);
unfolded.unshift({
assignTo: tempIdent,
intertype: 'value',
ident: switchLabel.value,
type: subItem.type
});
switchLabel.value = tempIdent;
}
});
}
});
if (unfolded.length > 0) {
interpLines(label.lines, i-1, unfolded);
Array.prototype.splice.apply(label.lines, [i, 0].concat(unfolded));
continue; // remain at this index, to unfold newly generated lines
}
// This is an illegal-containing line, and it is unfolded. Legalize it now
dprint('legalizer', 'Legalizing ' + item.intertype + ' at line ' + item.lineNum);
var finalizer = null;
switch (item.intertype) {
case 'store': {
var toAdd = [];
bits = getBits(item.valueType);
var elements = getLegalParams([item.value], bits)[0];
var j = 0;
elements.forEach(function(element) {
var tempVar = '$st$' + (tempId++) + '$' + j;
toAdd.push({
intertype: 'getelementptr',
assignTo: tempVar,
ident: item.pointer.ident,
type: '[0 x i32]*',
params: [
{ intertype: 'value', ident: item.pointer.ident, type: '[0 x i32]*' }, // technically a bitcase is needed in llvm, but not for us
{ intertype: 'value', ident: '0', type: 'i32' },
{ intertype: 'value', ident: j.toString(), type: 'i32' }
],
});
var actualSizeType = 'i' + element.bits; // The last one may be smaller than 32 bits
toAdd.push({
intertype: 'store',
valueType: actualSizeType,
value: { intertype: 'value', ident: element.ident, type: actualSizeType },
pointer: { intertype: 'value', ident: tempVar, type: actualSizeType + '*' },
ident: tempVar,
pointerType: actualSizeType + '*',
align: item.align,
});
j++;
});
Types.needAnalysis['[0 x i32]'] = 0;
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
// call, return: Return the first 32 bits, the rest are in temp
case 'call': {
var toAdd = [value];
// legalize parameters
legalizeFunctionParameters(value.params);
// legalize return value, if any
var returnType = getReturnType(item.type);
if (value.assignTo && isIllegalType(returnType)) {
bits = getBits(returnType);
var elements = getLegalVars(item.assignTo, bits);
// legalize return value
value.assignTo = elements[0].ident;
for (var j = 1; j < elements.length; j++) {
var element = elements[j];
toAdd.push({
intertype: 'value',
assignTo: element.ident,
type: 'i' + element.bits,
ident: 'tempRet' + (j - 1)
});
assert(j<10); // TODO: dynamically create more than 10 tempRet-s
}
}
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'landingpad': {
// not much to legalize
i++;
continue;
}
case 'return': {
bits = getBits(item.type);
var elements = getLegalVars(item.value.ident, bits);
item.value.ident = '(';
for (var j = 1; j < elements.length; j++) {
item.value.ident += 'tempRet' + (j-1) + '=' + elements[j].ident + ',';
}
item.value.ident += elements[0].ident + ')';
i++;
continue;
}
case 'invoke': {
legalizeFunctionParameters(value.params);
// We can't add lines after this, since invoke already modifies control flow. So we handle the return in invoke
i++;
continue;
}
case 'value': {
bits = getBits(value.type);
var elements = getLegalVars(item.assignTo, bits);
var values = getLegalLiterals(item.ident, bits);
var j = 0;
var toAdd = elements.map(function(element) {
return {
intertype: 'value',
assignTo: element.ident,
type: 'i' + bits,
ident: values[j++].ident
};
});
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'structvalue': {
bits = getBits(value.type);
var elements = getLegalVars(item.assignTo, bits);
var toAdd = [];
for (var j = 0; j < item.params.length; j++) {
toAdd[j] = {
intertype: 'value',
assignTo: elements[j].ident,
type: 'i32',
ident: item.params[j].ident
};
}
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'load': {
bits = getBits(value.valueType);
var elements = getLegalVars(item.assignTo, bits);
var j = 0;
var toAdd = [];
elements.forEach(function(element) {
var tempVar = '$ld$' + (tempId++) + '$' + j;
toAdd.push({
intertype: 'getelementptr',
assignTo: tempVar,
ident: value.pointer.ident,
type: '[0 x i32]*',
params: [
{ intertype: 'value', ident: value.pointer.ident, type: '[0 x i32]*' }, // technically bitcast is needed in llvm, but not for us
{ intertype: 'value', ident: '0', type: 'i32' },
{ intertype: 'value', ident: j.toString(), type: 'i32' }
]
});
var newItem = {
intertype: 'load',
assignTo: element.ident,
pointerType: 'i32*',
valueType: 'i32',
type: 'i32',
pointer: { intertype: 'value', ident: tempVar, type: 'i32*' },
ident: tempVar,
align: value.align
};
var newItem2 = null;
// The last one may be smaller than 32 bits
if (element.bits < 32) {
newItem.assignTo += '$preadd$';
newItem2 = {
intertype: 'mathop',
op: 'and',
assignTo: element.ident,
type: 'i32',
params: [{
intertype: 'value',
type: 'i32',
ident: newItem.assignTo
}, {
intertype: 'value',
type: 'i32',
ident: (0xffffffff >>> (32 - element.bits)).toString()
}],
};
}
toAdd.push(newItem);
if (newItem2) toAdd.push(newItem2);
j++;
});
Types.needAnalysis['[0 x i32]'] = 0;
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'phi': {
bits = getBits(value.type);
var toAdd = [];
var elements = getLegalVars(item.assignTo, bits);
var j = 0;
var values = getLegalParams(value.params, bits);
elements.forEach(function(element) {
var k = 0;
toAdd.push({
intertype: 'phi',
assignTo: element.ident,
type: 'i' + element.bits,
params: value.params.map(function(param) {
return {
intertype: 'phiparam',
label: param.label,
value: values[k++][j]
};
})
});
j++;
});
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'switch': {
i++;
continue; // special case, handled in makeComparison
}
case 'va_arg': {
assert(value.type == 'i64');
assert(value.value.type == 'i32*', value.value.type);
i += removeAndAdd(label.lines, i, range(2).map(function(x) {
return {
intertype: 'va_arg',
assignTo: value.assignTo + '$' + x,
type: 'i32',
value: {
intertype: 'value',
ident: value.value.ident, // We read twice from the same i32* var, incrementing // + '$' + x,
type: 'i32*'
}
};
}));
continue;
}
case 'extractvalue': { // XXX we assume 32-bit alignment in extractvalue/insertvalue,
// but in theory they can run on packed structs too (see use getStructuralTypePartBits)
// potentially legalize the actual extracted value too if it is >32 bits, not just the extraction in general
var index = item.indexes[0][0].text;
var parts = getStructureTypeParts(item.type);
var indexedType = parts[index];
var targetBits = getBits(indexedType);
var sourceBits = getBits(item.type);
var elements = getLegalVars(item.assignTo, targetBits, true); // possibly illegal
var sourceElements = getLegalVars(item.ident, sourceBits); // definitely illegal
var toAdd = [];
var sourceIndex = 0;
for (var partIndex = 0; partIndex < parts.length; partIndex++) {
if (partIndex == index) {
for (var j = 0; j < elements.length; j++) {
toAdd.push({
intertype: 'value',
assignTo: elements[j].ident,
type: 'i' + elements[j].bits,
ident: sourceElements[sourceIndex+j].ident
});
}
break;
}
sourceIndex += getStructuralTypePartBits(parts[partIndex])/32;
}
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'insertvalue': {
var index = item.indexes[0][0].text; // the modified index
var parts = getStructureTypeParts(item.type);
var indexedType = parts[index];
var indexBits = getBits(indexedType);
var bits = getBits(item.type); // source and target
bits = getBits(value.type);
var toAdd = [];
var elements = getLegalVars(item.assignTo, bits);
var sourceElements = getLegalVars(item.ident, bits);
var indexElements = getLegalVars(item.value.ident, indexBits, true); // possibly legal
var sourceIndex = 0;
for (var partIndex = 0; partIndex < parts.length; partIndex++) {
var currNum = getStructuralTypePartBits(parts[partIndex])/32;
for (var j = 0; j < currNum; j++) {
toAdd.push({
intertype: 'value',
assignTo: elements[sourceIndex+j].ident,
type: 'i' + elements[sourceIndex+j].bits,
ident: partIndex == index ? indexElements[j].ident : sourceElements[sourceIndex+j].ident
});
}
sourceIndex += currNum;
}
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
case 'bitcast': {
var inType = item.type2;
var outType = item.type;
if ((inType in Compiletime.INT_TYPES && outType in Compiletime.FLOAT_TYPES) ||
(inType in Compiletime.FLOAT_TYPES && outType in Compiletime.INT_TYPES)) {
i++;
continue; // special case, handled in processMathop
}
// fall through
}
case 'inttoptr': case 'ptrtoint': case 'zext': case 'sext': case 'trunc': case 'ashr': case 'lshr': case 'shl': case 'or': case 'and': case 'xor': {
value = {
op: item.intertype,
variant: item.variant,
type: item.type,
params: item.params
};
// fall through
}
case 'mathop': {
var toAdd = [];
var sourceBits = getBits(value.params[0].type);
// All mathops can be parametrized by how many shifts we do, and how big the source is
var shifts = 0;
var targetBits = sourceBits;
var processor = null;
var signed = false;
switch (value.op) {
case 'ashr': {
signed = true;
// fall through
}
case 'lshr': {
shifts = parseInt(value.params[1].ident);
break;
}
case 'shl': {
shifts = -parseInt(value.params[1].ident);
break;
}
case 'sext': {
signed = true;
// fall through
}
case 'trunc': case 'zext': case 'ptrtoint': {
targetBits = getBits(value.params[1] ? value.params[1].ident : value.type);
break;
}
case 'inttoptr': {
targetBits = 32;
break;
}
case 'bitcast': {
if (!sourceBits) {
// we can be asked to bitcast doubles or such to integers, handle that as best we can (if it's a double that
// was an x86_fp80, this code will likely break when called)
sourceBits = targetBits = Runtime.getNativeTypeSize(value.params[0].type);
warn('legalizing non-integer bitcast on ll #' + item.lineNum);
}
break;
}
case 'select': {
sourceBits = targetBits = getBits(value.params[1].type);
var params = getLegalParams(value.params.slice(1), sourceBits);
processor = function(result, j) {
return {
intertype: 'mathop',
op: 'select',
type: 'i' + params[0][j].bits,
params: [
value.params[0],
{ intertype: 'value', ident: params[0][j].ident, type: 'i' + params[0][j].bits },
{ intertype: 'value', ident: params[1][j].ident, type: 'i' + params[1][j].bits }
]
};
};
break;
}
case 'or': case 'and': case 'xor': case 'icmp': {
var otherElements = getLegalVars(value.params[1].ident, sourceBits);
processor = function(result, j) {
return {
intertype: 'mathop',
op: value.op,
variant: value.variant,
type: 'i' + otherElements[j].bits,
params: [
result,
{ intertype: 'value', ident: otherElements[j].ident, type: 'i' + otherElements[j].bits }
]
};
};
if (value.op == 'icmp') {
if (sourceBits == 64) { // handle the i64 case in processMathOp, where we handle full i64 math
i++;
continue;
}
finalizer = function() {
var ident = '';
for (var i = 0; i < targetElements.length; i++) {
if (i > 0) {
switch(value.variant) {
case 'eq': ident += '&'; break;
case 'ne': ident += '|'; break;
default: throw 'unhandleable illegal icmp: ' + value.variant;
}
}
ident += targetElements[i].ident;
}
return {
intertype: 'value',
ident: ident,
type: 'rawJS',
assignTo: item.assignTo
};
}
}
break;
}
case 'add': case 'sub': case 'sdiv': case 'udiv': case 'mul': case 'urem': case 'srem': {
if (sourceBits < 32) {
// when we add illegal types like i24, we must work on the singleton chunks
item.assignTo += '$0';
item.params[0].ident += '$0';
item.params[1].ident += '$0';
}
// fall through
}
case 'uitofp': case 'sitofp': case 'fptosi': case 'fptoui': {
// We cannot do these in parallel chunks of 32-bit operations. We will handle these in processMathop
i++;
continue;
}
default: throw 'Invalid mathop for legalization: ' + [value.op, item.lineNum, dump(item)];
}
// Do the legalization
var sourceElements = getLegalVars(value.params[0].ident, sourceBits, true);
if (!isNumber(shifts)) {
// We can't statically legalize this, do the operation at runtime TODO: optimize
assert(sourceBits == 64, 'TODO: handle nonconstant shifts on != 64 bits');
assert(PRECISE_I64_MATH, 'Must have precise i64 math for non-constant 64-bit shifts');
Types.preciseI64MathUsed = 1;
value.intertype = 'value';
value.ident = makeVarDef(value.assignTo) + '$0=' +
asmCoercion('_bitshift64' + value.op[0].toUpperCase() + value.op.substr(1) + '(' +
asmCoercion(sourceElements[0].ident, 'i32') + ',' +
asmCoercion(sourceElements[1].ident, 'i32') + ',' +
asmCoercion(value.params[1].ident + '$0', 'i32') + ')', 'i32'
) + ';' +
makeVarDef(value.assignTo) + '$1=tempRet0;';
value.vars = [[value.assignTo + '$0', 'i32'], [value.assignTo + '$1', 'i32']];
value.assignTo = null;
i++;
continue;
}
var targetElements = getLegalVars(item.assignTo, targetBits);
var sign = shifts >= 0 ? 1 : -1;
var shiftOp = shifts >= 0 ? 'shl' : 'lshr';
var shiftOpReverse = shifts >= 0 ? 'lshr' : 'shl';
var whole = (shifts/32)|0; // Remove fractional part either for positive or negative number.
var fraction = Math.abs(shifts % 32);
if (signed) {
var signedFill = {
intertype: 'mathop',
op: 'select',
variant: 's',
type: 'i32',
params: [{
intertype: 'mathop',
op: 'icmp',
variant: 'slt',
type: 'i32',
params: [
{ intertype: 'value', ident: sourceElements[sourceElements.length-1].ident, type: 'i' + Math.min(sourceBits, 32) },
{ intertype: 'value', ident: '0', type: 'i32' }
]
},
{ intertype: 'value', ident: '-1', type: 'i32' },
{ intertype: 'value', ident: '0', type: 'i32' },
]
};
}
for (var j = 0; j < targetElements.length; j++) {
var inBounds = j + whole >= 0 && j + whole < sourceElements.length;
var result;
if (inBounds || !signed) {
result = {
intertype: 'value',
ident: inBounds ? sourceElements[j + whole].ident : '0',
type: 'i' + Math.min(sourceBits, 32),
};
if (j == 0 && sourceBits < 32) {
// zext sign correction
var result2 = {
intertype: 'mathop',
op: isUnsignedOp(value.op) ? 'zext' : 'sext',
params: [result, {
intertype: 'type',
ident: 'i32',
type: 'i' + sourceBits
}],
type: 'i32'
};
result = result2;
}
} else {
// out of bounds and signed
result = copy(signedFill);
}
if (fraction != 0) {
var other;
var otherInBounds = j + sign + whole >= 0 && j + sign + whole < sourceElements.length;
if (otherInBounds || !signed) {
other = {
intertype: 'value',
ident: otherInBounds ? sourceElements[j + sign + whole].ident : '0',
type: 'i32',
};
} else {
other = copy(signedFill);
}
other = {
intertype: 'mathop',
op: shiftOp,
type: 'i32',
params: [
other,
{ intertype: 'value', ident: (32 - fraction).toString(), type: 'i32' }
]
};
result = {
intertype: 'mathop',
// shifting in 1s from the top is a special case
op: (signed && shifts >= 0 && j + sign + whole >= sourceElements.length) ? 'ashr' : shiftOpReverse,
type: 'i32',
params: [
result,
{ intertype: 'value', ident: fraction.toString(), type: 'i32' }
]
};
result = {
intertype: 'mathop',
op: 'or',
type: 'i32',
params: [
result,
other
]
}
}
if (targetElements[j].bits < 32 && shifts < 0) {
// truncate bits that fall off the end. This is not needed in most cases, can probably be optimized out
result = {
intertype: 'mathop',
op: 'and',
type: 'i32',
params: [
result,
{ intertype: 'value', ident: (Math.pow(2, targetElements[j].bits)-1).toString(), type: 'i32' }
]
}
}
if (processor) {
result = processor(result, j);
}
result.assignTo = targetElements[j].ident;
toAdd.push(result);
}
if (targetBits <= 32) {
// We are generating a normal legal type here
legalValue = { intertype: 'value', ident: targetElements[0].ident, type: 'i32' };
if (targetBits < 32) {
legalValue = {
intertype: 'mathop',
op: 'and',
type: 'i32',
params: [
legalValue,
{ intertype: 'value', ident: (Math.pow(2, targetBits)-1).toString(), type: 'i32' }
]
}
};
legalValue.assignTo = item.assignTo;
toAdd.push(legalValue);
} else if (finalizer) {
toAdd.push(finalizer());
}
i += removeAndAdd(label.lines, i, toAdd);
continue;
}
}
assert(0, 'Could not legalize illegal line: ' + [item.lineNum, dump(item)]);
}
if (dcheck('legalizer')) dprint('zz legalized: \n' + dump(label.lines));
});
});
}
// Add function lines to func.lines, after our modifications to the label lines
data.functions.forEach(function(func) {
func.labels.forEach(function(label) {
func.lines = func.lines.concat(label.lines);
});
});
}
function addTypeInternal(type) {
if (type.length == 1) return;
if (Types.types[type]) return;
if (['internal', 'hidden', 'inbounds', 'void'].indexOf(type) != -1) return;
if (Compiletime.isNumberType(type)) return;
dprint('types', 'Adding type: ' + type);
// 'blocks': [14 x %struct.X] etc. If this is a pointer, we need
// to look at the underlying type - it was not defined explicitly
// anywhere else.
var nonPointing = removeAllPointing(type);
if (Types.types[nonPointing]) return;
var check = /^\[(\d+)\ x\ (.*)\]$/.exec(nonPointing);
if (check) {
var num = parseInt(check[1]);
num = Math.max(num, 1); // [0 x something] is used not for allocations and such of course, but
// for indexing - for an |array of unknown length|, basically. So we
// define the 'type' as having a single field. TODO: Ensure as a sanity
// check that we never allocate with this (either as a child structure
// in the analyzer, or in calcSize in alloca).
var subType = check[2];
addTypeInternal(subType); // needed for anonymous structure definitions (see below)
var fields = [subType, subType]; // Two, so we get the flatFactor right. We care about the flatFactor, not the size here. see calculateStructAlignment
Types.types[nonPointing] = {
name_: nonPointing,
fields: fields,
lineNum: '?'
};
newTypes[nonPointing] = 1;
// Also add a |[0 x type]| type
var zerod = '[0 x ' + subType + ']';
if (!Types.types[zerod]) {
Types.types[zerod] = {
name_: zerod,
fields: fields,
lineNum: '?'
};
newTypes[zerod] = 1;
}
return;
}
// anonymous structure definition, for example |{ i32, i8*, void ()*, i32 }|
if (type[0] == '{' || type[0] == '<') {
type = nonPointing;
var packed = type[0] == '<';
var internal = type;
if (packed) {
if (type[1] !== '{') {
// vector type, <4 x float> etc.
var size = getVectorSize(type);
Types.types[type] = {
name_: type,