forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseTools.js
2716 lines (2521 loc) · 101 KB
/
parseTools.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";
// Various tools for parsing LLVM. Utilities of various sorts, that are
// specific to Emscripten (and hence not in utility.js).
// Does simple 'macro' substitution, using Django-like syntax,
// {{{ code }}} will be replaced with |eval(code)|.
// NOTE: Be careful with that ret check. If ret is |0|, |ret ? ret.toString() : ''| would result in ''!
function processMacros(text) {
return text.replace(/{{{([^}]|}(?!}))+}}}/g, function(str) {
str = str.substr(3, str.length-6);
var ret = eval(str);
return ret !== null ? ret.toString() : '';
});
}
// Simple #if/else/endif preprocessing for a file. Checks if the
// ident checked is true in our global.
// Also handles #include x.js (similar to C #include <file>)
function preprocess(text) {
var lines = text.split('\n');
var ret = '';
var showStack = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line[line.length-1] == '\r') {
line = line.substr(0, line.length-1); // Windows will have '\r' left over from splitting over '\r\n'
}
if (!line[0] || line[0] != '#') {
if (showStack.indexOf(false) == -1) {
ret += line + '\n';
}
} else {
if (line[1] == 'i') {
if (line[2] == 'f') { // if
var parts = line.split(' ');
var ident = parts[1];
var op = parts[2];
var value = parts[3];
if (op) {
if (op === '==') {
showStack.push(ident in this && this[ident] == value);
} else if (op === '!=') {
showStack.push(!(ident in this && this[ident] == value));
} else {
error('unsupported preprecessor op ' + op);
}
} else {
if (ident[0] === '!') {
showStack.push(!(this[ident.substr(1)] > 0));
} else {
showStack.push(ident in this && this[ident] > 0);
}
}
} else if (line[2] == 'n') { // include
var included = read(line.substr(line.indexOf(' ')+1));
ret += '\n' + preprocess(included) + '\n'
}
} else if (line[2] == 'l') { // else
showStack.push(!showStack.pop());
} else if (line[2] == 'n') { // endif
showStack.pop();
} else {
throw "Unclear preprocessor command: " + line;
}
}
}
assert(showStack.length == 0);
return ret;
}
function addPointing(type) { return type + '*' }
function removePointing(type, num) {
if (num === 0) return type;
assert(type.substr(type.length-(num ? num : 1)).replace(/\*/g, '') === ''); //, 'Error in removePointing with ' + [type, num, type.substr(type.length-(num ? num : 1))]);
return type.substr(0, type.length-(num ? num : 1));
}
function pointingLevels(type) {
if (!type) return 0;
var ret = 0;
var len1 = type.length - 1;
while (type[len1-ret] && type[len1-ret] === '*') {
ret++;
}
return ret;
}
function removeAllPointing(type) {
return removePointing(type, pointingLevels(type));
}
function toNiceIdent(ident) {
assert(ident);
if (parseFloat(ident) == ident) return ident;
if (ident == 'null') return '0'; // see parseNumerical
if (ident == 'undef') return '0';
return ident.replace('%', '$').replace(/["&\\ \.@:<>,\*\[\]\(\)-]/g, '_');
}
// Kind of a hack. In some cases we have strings that we do not want
// to |toNiceIdent|, as they are the output of previous processing. We
// should refactor everything into an object, with an explicit flag
// saying what has been |toNiceIdent|ed. Until then, this will detect
// simple idents that are in need of |toNiceIdent|ation. Or, we should
// ensure that processed strings never start with %,@, e.g. by always
// enclosing them in ().
function toNiceIdentCarefully(ident) {
if (ident[0] == '%' || ident[0] == '@') ident = toNiceIdent(ident);
return ident;
}
// Returns true if ident is a niceIdent (see toNiceIdent). If loose
// is true, then also allow () and spaces.
function isNiceIdent(ident, loose) {
if (loose) {
return /^\(?[$_]+[\w$_\d ]*\)?$/.test(ident);
} else {
return /^[$_]+[\w$_\d]*$/.test(ident);
}
}
function isJSVar(ident) {
if (ident[0] === '(') {
if (ident[ident.length-1] !== ')') return false;
ident = ident.substr(1, ident.length-2);
}
return /^[$_]?[\w$_\d]* *$/.test(ident);
}
function isLocalVar(ident) {
return ident[0] === '$';
}
// Simple variables or numbers, or things already quoted, do not need to be quoted
function needsQuoting(ident) {
if (/^[-+]?[$_]?[\w$_\d]*$/.test(ident)) return false; // number or variable
if (ident[0] === '(' && ident[ident.length-1] === ')' && ident.indexOf('(', 1) < 0) return false; // already fully quoted
return true;
}
function isStructPointerType(type) {
// This test is necessary for clang - in llvm-gcc, we
// could check for %struct. The downside is that %1 can
// be either a variable or a structure, and we guess it is
// a struct, which can lead to |call i32 %5()| having
// |%5()| as a function call (like |i32 (i8*)| etc.). So
// we must check later on, in call(), where we have more
// context, to differentiate such cases.
// A similar thing happens in isStructType()
return !Compiletime.isNumberType(type) && type[0] == '%';
}
function isPointerType(type) {
return type[type.length-1] == '*';
}
function isArrayType(type) {
return /^\[\d+\ x\ (.*)\]/.test(type);
}
function isStructType(type) {
if (isPointerType(type)) return false;
if (isArrayType(type)) return true;
if (/<?\{ ?[^}]* ?\}>?/.test(type)) return true; // { i32, i8 } etc. - anonymous struct types
// See comment in isStructPointerType()
return type[0] == '%';
}
function isVectorType(type) {
return type[type.length-1] === '>';
}
function isStructuralType(type) {
return /^\{ ?[^}]* ?\}$/.test(type); // { i32, i8 } etc. - anonymous struct types
}
function getStructuralTypeParts(type) { // split { i32, i8 } etc. into parts
return type.replace(/[ {}]/g, '').split(',');
}
function getStructureTypeParts(type) {
if (isStructuralType(type)) {
return type.replace(/[ {}]/g, '').split(',');
} else {
var typeData = Types.types[type];
assert(typeData, type);
return typeData.fields;
}
}
function getStructuralTypePartBits(part) {
return Math.ceil((getBits(part) || 32)/32)*32; // simple 32-bit alignment. || 32 is for pointers
}
function isIntImplemented(type) {
return type[0] == 'i' || isPointerType(type);
}
// Note: works for iX types and structure types, not pointers (even though they are implemented as ints)
function getBits(type, allowPointers) {
if (allowPointers && isPointerType(type)) return 32;
if (!type) return 0;
if (type[0] == 'i') {
var left = type.substr(1);
if (!isNumber(left)) return 0;
return parseInt(left);
}
if (isStructuralType(type)) {
return sum(getStructuralTypeParts(type).map(getStructuralTypePartBits));
}
if (isStructType(type)) {
var typeData = Types.types[type];
if (typeData === undefined) return 0;
return typeData.flatSize*8;
}
return 0;
}
function getNumIntChunks(type) {
return Math.ceil(getBits(type, true)/32);
}
function isIdenticallyImplemented(type1, type2) {
var floats = +(type1 in Compiletime.FLOAT_TYPES) + +(type2 in Compiletime.FLOAT_TYPES);
if (floats == 2) return true;
if (floats == 1) return false;
return getNumIntChunks(type1) == getNumIntChunks(type2);
}
function isIllegalType(type) {
switch (type) {
case 'i1':
case 'i8':
case 'i16':
case 'i32':
case 'float':
case 'double':
case 'rawJS':
case '<2 x float>':
case '<4 x float>':
case '<2 x i32>':
case '<4 x i32>':
case 'void': return false;
}
if (!type || type[type.length-1] === '*') return false;
return true;
}
function isVoidType(type) {
return type == 'void';
}
// Detects a function definition, ([...|type,[type,...]])
function isFunctionDef(token, out) {
var text = token.text;
var nonPointing = removeAllPointing(text);
if (nonPointing[0] != '(' || nonPointing.substr(-1) != ')')
return false;
if (nonPointing === '()') return true;
if (!token.tokens) return false;
var fail = false;
var segments = splitTokenList(token.tokens);
segments.forEach(function(segment) {
var subtext = segment[0].text;
fail = fail || segment.length > 1 || !(isType(subtext) || subtext == '...');
});
if (out) {
out.segments = segments;
out.numArgs = segments.length;
}
return !fail;
}
function isPossiblyFunctionType(type) {
// A quick but unreliable way to see if something is a function type. Yes is just 'maybe', no is definite.
var len = type.length;
return type[len-2] == ')' && type[len-1] == '*';
}
function isFunctionType(type, out) {
if (!isPossiblyFunctionType(type)) return false;
type = type.substr(0, type.length-1); // remove final '*'
var firstOpen = type.indexOf('(');
if (firstOpen <= 0) return false;
type = type.replace(/"[^"]+"/g, '".."');
var lastOpen = type.lastIndexOf('(');
var returnType;
if (firstOpen == lastOpen) {
returnType = getReturnType(type);
if (!isType(returnType)) return false;
} else {
returnType = 'i8*'; // some pointer type, no point in analyzing further
}
if (out) out.returnType = returnType;
// find ( that starts the arguments
var depth = 0, i = type.length-1, argText = null;
while (i >= 0) {
var curr = type[i];
if (curr == ')') depth++;
else if (curr == '(') {
depth--;
if (depth == 0) {
argText = type.substr(i);
break;
}
}
i--;
}
assert(argText);
return isFunctionDef({ text: argText, tokens: tokenize(argText.substr(1, argText.length-2)) }, out);
}
function getReturnType(type) {
if (pointingLevels(type) > 1) return '*'; // the type of a call can be either the return value, or the entire function. ** or more means it is a return value
var lastOpen = type.lastIndexOf('(');
if (lastOpen > 0) {
// handle things like void (i32)* (i32, void (i32)*)*
var closeStar = type.indexOf(')*');
if (closeStar > 0 && closeStar < type.length-2) lastOpen = closeStar+3;
return type.substr(0, lastOpen-1);
}
return type;
}
var isTypeCache = {}; // quite hot, optimize as much as possible
function isType(type) {
if (type in isTypeCache) return isTypeCache[type];
var ret = isPointerType(type) || isVoidType(type) || Compiletime.isNumberType(type) || isStructType(type) || isFunctionType(type);
isTypeCache[type] = ret;
return ret;
}
function isVarArgsFunctionType(type) {
// assumes this is known to be a function type already
var varArgsSuffix = '...)*';
return type.substr(-varArgsSuffix.length) == varArgsSuffix;
}
function getNumLegalizedVars(type) { // how many legalized variables are needed to represent this type
if (type in Compiletime.FLOAT_TYPES) return 1;
return Math.max(getNumIntChunks(type), 1);
}
function countNormalArgs(type, out, legalized) {
out = out || {};
if (!isFunctionType(type, out)) return -1;
var ret = 0;
if (out.segments) {
for (var i = 0; i < out.segments.length; i++) {
ret += legalized ? getNumLegalizedVars(out.segments[i][0].text) : 1;
}
}
if (isVarArgsFunctionType(type)) ret--;
return ret;
}
function getVectorSize(type) {
return parseInt(type.substring(1, type.indexOf(' ')));
}
function getVectorNativeType(type) {
Types.usesSIMD = true;
switch (type) {
case '<2 x float>':
case '<4 x float>': return 'float';
case '<2 x i32>':
case '<4 x i32>': return 'i32';
default: throw 'unknown vector type ' + type;
}
}
function getSIMDName(type) {
switch (type) {
case 'i32': return 'int';
case 'float': return 'float';
default: throw 'getSIMDName ' + type;
}
}
function getVectorBaseType(type) {
return getSIMDName(getVectorNativeType(type));
}
function addIdent(token) {
token.ident = token.text;
return token;
}
function combineTokens(tokens) {
var ret = {
lineNum: tokens[0].lineNum,
text: '',
tokens: []
};
tokens.forEach(function(token) {
ret.text += token.text;
ret.tokens.push(token);
});
return ret;
}
function compareTokens(a, b) {
var aId = a.__uid__;
var bId = b.__uid__;
a.__uid__ = 0;
b.__uid__ = 0;
var ret = JSON.stringify(a) == JSON.stringify(b);
a.__uid__ = aId;
b.__uid__ = bId;
return ret;
}
function getTokenIndexByText(tokens, text) {
var i = 0;
while (tokens[i] && tokens[i].text != text) i++;
return i;
}
function findTokenText(item, text) {
return findTokenTextAfter(item, text, 0);
}
function findTokenTextAfter(item, text, startAt) {
for (var i = startAt; i < item.tokens.length; i++) {
if (item.tokens[i].text == text) return i;
}
return -1;
}
var SPLIT_TOKEN_LIST_SPLITTERS = set(',', 'to'); // 'to' can separate parameters as well...
// Splits a list of tokens separated by commas. For example, a list of arguments in a function call
function splitTokenList(tokens) {
if (tokens.length == 0) return [];
if (!tokens.slice) tokens = tokens.tokens;
var ret = [];
var seg = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.text in SPLIT_TOKEN_LIST_SPLITTERS) {
ret.push(seg);
seg = [];
} else if (token.text == ';') {
ret.push(seg);
return ret;
} else {
seg.push(token);
}
}
if (seg.length) ret.push(seg);
return ret;
}
function parseParamTokens(params) {
if (params.length === 0) return [];
var ret = [];
var anonymousIndex = 0;
while (params.length > 0) {
var i = 0;
while (i < params.length && params[i].text != ',') i++;
var segment = params.slice(0, i);
params = params.slice(i+1);
segment = cleanSegment(segment);
var byVal = 0;
if (segment[1] && segment[1].text === 'byval') {
// handle 'byval' and 'byval align X'. We store the alignment in 'byVal'
byVal = QUANTUM_SIZE;
segment.splice(1, 1);
if (segment[1] && (segment[1].text in LLVM.PARAM_IGNORABLES)) {
segment.splice(1, 1);
}
if (segment[1] && segment[1].text === 'align') {
assert(isNumber(segment[2].text));
byVal = parseInt(segment[2].text);
segment.splice(1, 2);
}
}
if (segment[1] && (segment[1].text in LLVM.PARAM_IGNORABLES)) {
segment.splice(1, 1);
}
if (segment.length == 1) {
if (segment[0].text == '...') {
ret.push({
intertype: 'varargs',
type: 'i8*',
ident: 'varrp' // the conventional name we have for this
});
} else {
// Clang sometimes has a parameter with just a type,
// no name... the name is implied to be %{the index}
ret.push({
intertype: 'value',
type: segment[0].text,
ident: toNiceIdent('%') + anonymousIndex
});
Types.needAnalysis[ret[ret.length-1].type] = 0;
anonymousIndex ++;
}
} else {
if (segment[2] && segment[2].text == 'to') { // part of bitcast params
segment = segment.slice(0, 2);
}
var parsed = parseLLVMSegment(segment);
if (parsed.intertype === 'value' && !isIllegalType(parsed.type)) parsed.ident = parseNumerical(parsed.ident, parsed.type);
ret.push(parsed);
}
ret[ret.length-1].byVal = byVal;
}
return ret;
}
function hasVarArgs(params) {
for (var i = 0; i < params.length; i++) {
if (params[i].intertype == 'varargs') {
return true;
}
}
return false;
}
var UNINDEXABLE_GLOBALS = set(
'_llvm_global_ctors' // special-cased
);
function isIndexableGlobal(ident) {
if (!(ident in Variables.globals)) return false;
if (ident in UNINDEXABLE_GLOBALS) {
Variables.globals[ident].unIndexable = true;
return false;
}
var data = Variables.globals[ident];
return !data.alias && !data.external;
}
function isBSS(item) {
if (!USE_BSS) {
return false;
}
if (item.external) return false; // externals are typically implemented in a JS library, and must be accessed by name, explicitly
// return true if a global is uninitialized or initialized to 0
return (item.value && item.value.intertype === 'emptystruct') ||
(item.value && item.value.value !== undefined && item.value.value === '0');
}
function makeGlobalDef(ident) {
if (!NAMED_GLOBALS && isIndexableGlobal(ident)) return '';
return 'var ' + ident + ';';
}
function makeGlobalUse(ident) {
if (!NAMED_GLOBALS && isIndexableGlobal(ident)) {
var index = Variables.indexedGlobals[ident];
if (index === undefined) {
// we are accessing this before we index globals, likely from the library. mark as unindexable
UNINDEXABLE_GLOBALS[ident] = 1;
return ident;
}
var ret = (Runtime.GLOBAL_BASE + index).toString();
if (SIDE_MODULE) ret = '(H_BASE+' + ret + ')';
return ret;
}
return ident;
}
function sortGlobals(globals) {
var ks = keys(globals);
ks.sort();
var inv = invertArray(ks);
return values(globals).sort(function(a, b) {
// sort globals based on if they need to be explicitly initialized or not (moving
// values that don't need to be to the end of the array). if equal, sort by name.
return (Number(isBSS(a)) - Number(isBSS(b))) ||
(inv[b.ident] - inv[a.ident]);
});
}
// Segment ==> Parameter
function parseLLVMSegment(segment) {
var type;
if (segment.length == 1) {
if (isType(segment[0].text)) {
Types.needAnalysis[segment[0].text] = 0;
return {
intertype: 'type',
ident: toNiceIdent(segment[0].text),
type: segment[0].text
};
} else {
return {
intertype: 'value',
ident: toNiceIdent(segment[0].text),
type: 'i32'
};
}
} else if (segment[1].type && segment[1].type == '{') {
type = segment[0].text;
Types.needAnalysis[type] = 0;
return {
intertype: 'structvalue',
params: splitTokenList(segment[1].tokens).map(parseLLVMSegment),
type: type
};
} else if (segment[0].text in PARSABLE_LLVM_FUNCTIONS) {
return parseLLVMFunctionCall([{text: '?'}].concat(segment));
} else if (segment[1].text in PARSABLE_LLVM_FUNCTIONS) {
return parseLLVMFunctionCall(segment);
} else if (segment[1].text === 'blockaddress') {
return parseBlockAddress(segment);
} else {
type = segment[0].text;
if (type[type.length-1] === '>' && segment[1].text[0] === '<') {
// vector literal
var nativeType = getVectorNativeType(type);
return {
intertype: 'vector',
idents: splitTokenList(segment[1].tokens).map(function(pair) {
return parseNumerical(pair[1].text, nativeType);
}),
type: type
};
}
Types.needAnalysis[type] = 0;
return {
intertype: 'value',
ident: toNiceIdent(segment[1].text),
type: type
};
}
}
function cleanSegment(segment) {
while (segment.length >= 2 && ['noalias', 'sret', 'nocapture', 'nest', 'zeroext', 'signext', 'readnone'].indexOf(segment[1].text) != -1) {
segment.splice(1, 1);
}
return segment;
}
var MATHOPS = set(['add', 'sub', 'sdiv', 'udiv', 'mul', 'icmp', 'zext', 'urem', 'srem', 'fadd', 'fsub', 'fmul', 'fdiv', 'fcmp', 'frem', 'uitofp', 'sitofp', 'fpext', 'fptrunc', 'fptoui', 'fptosi', 'trunc', 'sext', 'select', 'shl', 'shr', 'ashl', 'ashr', 'lshr', 'lshl', 'xor', 'or', 'and', 'ptrtoint', 'inttoptr']);
var JS_MATH_BUILTINS = set(['Math_sin', 'Math_cos', 'Math_tan', 'Math_asin', 'Math_acos', 'Math_atan', 'Math_ceil', 'Math_floor', 'Math_exp', 'Math_log', 'Math_sqrt']);
var PARSABLE_LLVM_FUNCTIONS = set('getelementptr', 'bitcast');
mergeInto(PARSABLE_LLVM_FUNCTIONS, MATHOPS);
// Parses a function call of form
// TYPE functionname MODIFIERS (...)
// e.g.
// i32* getelementptr inbounds (...)
function parseLLVMFunctionCall(segment) {
segment = segment.slice(0);
segment = cleanSegment(segment);
// Remove additional modifiers
var variant = null;
if (!segment[2] || !segment[2].tokens) {
variant = segment.splice(2, 1)[0];
if (variant && variant.text) variant = variant.text; // needed for mathops
}
assertTrue(['inreg', 'byval'].indexOf(segment[1].text) == -1);
assert(segment[1].text in PARSABLE_LLVM_FUNCTIONS);
while (!segment[2].tokens) {
segment.splice(2, 1); // Remove modifiers
if (!segment[2]) throw 'Invalid segment!';
}
var intertype = segment[1].text;
var type = segment[0].text;
if (type === '?') {
if (intertype === 'getelementptr') {
type = '*'; // a pointer, we can easily say, this is
} else if (segment[2].tokens.slice(-2)[0].text === 'to') {
type = segment[2].tokens.slice(-1)[0].text;
}
}
var ret = {
intertype: intertype,
variant: variant,
type: type,
params: parseParamTokens(segment[2].tokens)
};
Types.needAnalysis[ret.type] = 0;
ret.ident = toNiceIdent(ret.params[0].ident || 'NOIDENT');
return ret;
}
// Gets an array of tokens, we parse out the first
// 'ident' - either a simple ident of one token, or
// an LLVM internal function that generates an ident.
// We shift out of the array list the tokens that
// we ate.
function eatLLVMIdent(tokens) {
var ret;
if (tokens[0].text in PARSABLE_LLVM_FUNCTIONS) {
var item = parseLLVMFunctionCall([{text: '?'}].concat(tokens.slice(0,2))); // TODO: Handle more cases, return a full object, process it later
if (item.intertype == 'bitcast') checkBitcast(item);
ret = item.ident;
tokens.shift();
tokens.shift();
} else {
ret = tokens[0].text;
tokens.shift();
}
return ret;
}
function cleanOutTokens(filterOut, tokens, indexes) {
if (typeof indexes !== 'object') indexes = [indexes];
for (var i = indexes.length-1; i >=0; i--) {
var index = indexes[i];
while (index < tokens.length && tokens[index].text in filterOut) {
tokens.splice(index, 1);
}
}
}
function _IntToHex(x) {
assert(x >= 0 && x <= 15);
if (x <= 9) {
return String.fromCharCode('0'.charCodeAt(0) + x);
} else {
return String.fromCharCode('A'.charCodeAt(0) + x - 10);
}
}
function IEEEUnHex(stringy) {
stringy = stringy.substr(2); // leading '0x';
if (stringy.replace(/0/g, '') === '') return 0;
while (stringy.length < 16) stringy = '0' + stringy;
if (FAKE_X86_FP80 && stringy.length > 16) {
stringy = stringy.substr(stringy.length-16, 16);
assert(TARGET_X86, 'must only see >64 bit floats in x86, as fp80s');
warnOnce('.ll contains floating-point values with more than 64 bits. Faking values for them. If they are used, this will almost certainly break horribly!');
}
assert(stringy.length === 16, 'Can only unhex 16-digit double numbers, nothing platform-specific'); // |long double| can cause x86_fp80 which causes this
var top = eval('0x' + stringy[0]);
var neg = !!(top & 8); // sign
if (neg) {
stringy = _IntToHex(top & ~8) + stringy.substr(1);
}
var a = eval('0x' + stringy.substr(0, 8)); // top half
var b = eval('0x' + stringy.substr(8)); // bottom half
var e = a >> ((52 - 32) & 0x7ff); // exponent
a = a & 0xfffff;
if (e === 0x7ff) {
if (a == 0 && b == 0) {
return neg ? '-Infinity' : 'Infinity';
} else {
return 'NaN';
}
}
e -= 1023; // offset
var absolute = ((((a | 0x100000) * 1.0) / Math.pow(2,52-32)) * Math.pow(2, e)) + (((b * 1.0) / Math.pow(2, 52)) * Math.pow(2, e));
return (absolute * (neg ? -1 : 1)).toString();
}
// Given an expression like (VALUE=VALUE*2,VALUE<10?VALUE:t+1) , this will
// replace VALUE with value. If value is not a simple identifier of a variable,
// value will be replaced with tempVar.
function makeInlineCalculation(expression, value, tempVar) {
if (!isNiceIdent(value, true)) {
expression = tempVar + '=' + value + ',' + expression;
value = tempVar;
}
return '(' + expression.replace(/VALUE/g, value) + ')';
}
// Makes a proper runtime value for a 64-bit value from low and high i32s. low and high are assumed to be unsigned.
function makeI64(low, high) {
high = high || '0';
if (USE_TYPED_ARRAYS == 2) {
return '[' + makeSignOp(low, 'i32', 'un', 1, 1) + ',' + makeSignOp(high, 'i32', 'un', 1, 1) + ']';
} else {
if (high) return RuntimeGenerator.makeBigInt(low, high);
return low;
}
}
// XXX Make all i64 parts signed
// Splits a number (an integer in a double, possibly > 32 bits) into an USE_TYPED_ARRAYS == 2 i64 value.
// Will suffer from rounding. mergeI64 does the opposite.
function splitI64(value, floatConversion) {
// general idea:
//
// $1$0 = ~~$d >>> 0;
// $1$1 = Math_abs($d) >= 1 ? (
// $d > 0 ? Math.min(Math_floor(($d)/ 4294967296.0), 4294967295.0)
// : Math_ceil(Math.min(-4294967296.0, $d - $1$0)/ 4294967296.0)
// ) : 0;
//
// We need to min on positive values here, since our input might be a double, and large values are rounded, so they can
// be slightly higher than expected. And if we get 4294967296, that will turn into a 0 if put into a
// HEAP32 or |0'd, etc.
//
// For negatives, we need to ensure a -1 if the value is overall negative, even if not significant negative component
var lowInput = legalizedI64s ? value : 'VALUE';
if (floatConversion && ASM_JS) lowInput = asmFloatToInt(lowInput);
var low = lowInput + '>>>0';
var high = makeInlineCalculation(
asmCoercion('Math_abs(VALUE)', 'double') + ' >= ' + asmEnsureFloat('1', 'double') + ' ? ' +
'(VALUE > ' + asmEnsureFloat('0', 'double') + ' ? ' +
asmCoercion('Math_min(' + asmCoercion('Math_floor((VALUE)/' + asmEnsureFloat(4294967296, 'double') + ')', 'double') + ', ' + asmEnsureFloat(4294967295, 'double') + ')', 'i32') + '>>>0' +
' : ' + asmFloatToInt(asmCoercion('Math_ceil((VALUE - +((' + asmFloatToInt('VALUE') + ')>>>0))/' + asmEnsureFloat(4294967296, 'double') + ')', 'double')) + '>>>0' +
')' +
' : 0',
value,
'tempDouble'
);
if (legalizedI64s) {
return [low, high];
} else {
return makeI64(low, high);
}
}
function mergeI64(value, unsigned) {
assert(USE_TYPED_ARRAYS == 2);
if (legalizedI64s) {
return RuntimeGenerator.makeBigInt(value + '$0', value + '$1', unsigned);
} else {
return makeInlineCalculation(RuntimeGenerator.makeBigInt('VALUE[0]', 'VALUE[1]', unsigned), value, 'tempI64');
}
}
// Takes an i64 value and changes it into the [low, high] form used in i64 mode 1. In that
// mode, this is a no-op
function ensureI64_1(value) {
if (USE_TYPED_ARRAYS == 2) return value;
return splitI64(value, 1);
}
function makeCopyI64(value) {
assert(USE_TYPED_ARRAYS == 2);
return value + '.slice(0)';
}
// Given a string representation of an integer of arbitrary size, return it
// split up into 32-bit chunks
function parseArbitraryInt(str, bits) {
// We parse the string into a vector of digits, base 10. This is convenient to work on.
assert(bits > 0); // NB: we don't check that the value in str can fit in this amount of bits
function str2vec(s) { // index 0 is the highest value
var ret = [];
for (var i = 0; i < s.length; i++) {
ret.push(s.charCodeAt(i) - '0'.charCodeAt(0));
}
return ret;
}
function divide2(v) { // v /= 2
for (var i = v.length-1; i >= 0; i--) {
var d = v[i];
var r = d % 2;
d = Math.floor(d/2);
v[i] = d;
if (r) {
assert(i+1 < v.length);
var d2 = v[i+1];
d2 += 5;
if (d2 >= 10) {
v[i] = d+1;
d2 -= 10;
}
v[i+1] = d2;
}
}
}
function mul2(v) { // v *= 2
for (var i = v.length-1; i >= 0; i--) {
var d = v[i]*2;
r = d >= 10;
v[i] = d%10;
var j = i-1;
if (r) {
if (j < 0) {
v.unshift(1);
break;
}
v[j] += 0.5; // will be multiplied
}
}
}
function subtract(v, w) { // v -= w. we assume v >= w
while (v.length > w.length) w.splice(0, 0, 0);
for (var i = 0; i < v.length; i++) {
v[i] -= w[i];
if (v[i] < 0) {
v[i] += 10;
// find something to take from
var j = i-1;
while (v[j] == 0) {
v[j] = 9;
j--;
assert(j >= 0);
}
v[j]--;
}
}
}
function isZero(v) {
for (var i = 0; i < v.length; i++) {
if (v[i] > 0) return false;
}
return true;
}
var v;
if (str[0] == '-') {
// twos-complement is needed
str = str.substr(1);
v = str2vec('1');
for (var i = 0; i < bits; i++) {
mul2(v);
}
subtract(v, str2vec(str));
} else {
v = str2vec(str);
}
var bitsv = [];
while (!isZero(v)) {
bitsv.push((v[v.length-1] % 2 != 0)+0);
v[v.length-1] = v[v.length-1] & 0xfe;
divide2(v);
}
var ret = zeros(Math.ceil(bits/32));
for (var i = 0; i < bitsv.length; i++) {
ret[Math.floor(i/32)] += bitsv[i]*Math.pow(2, i % 32);
}
return ret;
}
function parseI64Constant(str, legalized) {
if (!isNumber(str)) {
// This is a variable. Copy it, so we do not modify the original
return legalizedI64s ? str : makeCopyI64(str);
}
var parsed = parseArbitraryInt(str, 64);
if (legalizedI64s || legalized) return parsed;
return '[' + parsed[0] + ',' + parsed[1] + ']';
}
function parseNumerical(value, type) {
if ((!type || type === 'double' || type === 'float') && /^0x/.test(value)) {
// Hexadecimal double value, as the llvm docs say,
// "The one non-intuitive notation for constants is the hexadecimal form of floating point constants."
value = IEEEUnHex(value);
} else if (USE_TYPED_ARRAYS == 2 && isIllegalType(type)) {
return value; // do not parseFloat etc., that can lead to loss of precision
} else if (value === 'null') {
// NULL *is* 0, in C/C++. No JS null! (null == 0 is false, etc.)
value = '0';
} else if (value === 'true') {
return '1';
} else if (value === 'false') {
return '0';
}
if (isNumber(value)) {
var ret = parseFloat(value); // will change e.g. 5.000000e+01 to 50
// type may be undefined here, like when this is called from makeConst with a single argument.
// but if it is a number, then we can safely assume that this should handle negative zeros
// correctly.
if (type === undefined || type === 'double' || type === 'float') {
if (value[0] === '-' && ret === 0) { return '-.0'; } // fix negative 0, toString makes it 0
}
if (type === 'double' || type === 'float') {
if (!RUNNING_JS_OPTS) ret = asmEnsureFloat(ret, type);
}
return ret.toString();
} else {
return value;
}
}
// \0Dsometext is really '\r', then sometext
// This function returns an array of int values
function parseLLVMString(str) {
var ret = [];
var i = 0;
while (i < str.length) {
var chr = str.charCodeAt(i);
if (chr !== 92) { // 92 === '//'.charCodeAt(0)
ret.push(chr);
i++;
} else {
ret.push(parseInt(str[i+1]+str[i+2], '16'));
i += 3;
}
}
return ret;
}