-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathCheerpWasmWriter.cpp
More file actions
6152 lines (5749 loc) · 187 KB
/
CheerpWasmWriter.cpp
File metadata and controls
6152 lines (5749 loc) · 187 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- CheerpWasmWriter.cpp - The Cheerp JavaScript generator ------------===//
//
// Cheerp: The C++ compiler for the Web
//
// This file is distributed under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE.TXT for details.
//
// Copyright 2017-2023 Leaning Technologies
//
//===----------------------------------------------------------------------===//
#include <algorithm>
#include <limits>
#include "CFGStackifier.h"
#include "llvm/IR/Dominators.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Cheerp/BuiltinInstructions.h"
#include "llvm/Cheerp/CommandLine.h"
#include "llvm/Cheerp/PHIHandler.h"
#include "llvm/Cheerp/NameGenerator.h"
#include "llvm/Cheerp/WasmWriter.h"
#include "llvm/Cheerp/Writer.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/IR/ProfDataUtils.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/LEB128.h"
using namespace cheerp;
using namespace llvm;
using namespace std;
//#define WASM_DUMP_SECTIONS 1
//#define WASM_DUMP_SECTION_DATA 1
//#define WASM_DUMP_METHODS 1
//#define WASM_DUMP_METHOD_DATA 1
//#define STRESS_DEFERRED 1
static uint32_t COMPILE_METHOD_LIMIT = 100000;
static inline void encodeF32(float f, WasmBuffer& stream)
{
stream.write(reinterpret_cast<const char*>(&f), sizeof(float));
}
static inline void encodeF64(double f, WasmBuffer& stream)
{
stream.write(reinterpret_cast<const char*>(&f), sizeof(double));
}
static inline void encodeRegisterKind(Registerize::REGISTER_KIND regKind, WasmBuffer& stream)
{
switch(regKind)
{
case Registerize::DOUBLE:
encodeULEB128(0x7c, stream);
break;
case Registerize::FLOAT:
encodeULEB128(0x7d, stream);
break;
case Registerize::INTEGER:
encodeULEB128(0x7f, stream);
break;
case Registerize::INTEGER64:
encodeULEB128(0x7e, stream);
break;
case Registerize::OBJECT:
encodeULEB128(0x6f, stream);
break;
case Registerize::VECTOR:
encodeULEB128(0x7b, stream);
break;
}
}
static uint32_t getValType(const Type* t)
{
if (t->isIntegerTy(64))
return 0x7e;
else if (t->isIntegerTy() || TypeSupport::isRawPointer(t, true))
return 0x7f;
else if (t->isFloatTy())
return 0x7d;
else if (t->isDoubleTy())
return 0x7c;
else if (t->isPointerTy())
return 0x6f;
else if (t->isVectorTy())
return 0x7b;
else
{
#ifndef NDEBUG
llvm::errs() << "Unsupported type ";
t->dump();
#endif
llvm_unreachable("Unsuppored type");
}
}
static void encodeValType(const Type* t, WasmBuffer& stream)
{
encodeULEB128(getValType(t), stream);
}
static void encodeLiteralType(const Type* t, WasmBuffer& stream)
{
if (t->isIntegerTy(64))
encodeULEB128(0x42, stream);
else if (t->isIntegerTy() || TypeSupport::isRawPointer(t, true))
encodeULEB128(0x41, stream);
else if(t->isFloatTy())
encodeULEB128(0x43, stream);
else if(t->isDoubleTy())
encodeULEB128(0x44, stream);
else
{
#ifndef NDEBUG
llvm::errs() << "Unsupported type: ";
t->dump();
#endif
llvm_unreachable("Unsuppored type");
}
}
std::string string_to_hex(StringRef input)
{
static const char* const lut = "0123456789abcdef";
size_t len = input.size();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i)
{
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
if ((i & 1) == 1 && (i + 1) < len)
output.push_back(' ');
}
return output;
}
enum class BranchHint
{
Likely,
Unlikely,
Neutral,
};
static BranchHint shouldBranchBeHinted(const llvm::BranchInst* bi, const bool IfNot)
{
uint64_t weight_false = 0;
uint64_t weight_true = 0;
if (extractBranchWeights(*bi, weight_true, weight_false))
{
if (IfNot)
std::swap(weight_false, weight_true);
const uint64_t total = weight_true + weight_false;
if (total == 0)
return BranchHint::Neutral;
auto isConvenientToHint = [](uint64_t part, uint64_t total) -> bool {
return (part*1.0 / total) > 0.8;
};
if (isConvenientToHint(weight_true, total))
return BranchHint::Likely;
if (isConvenientToHint(weight_false, total))
return BranchHint::Unlikely;
}
return BranchHint::Neutral;
}
Section::Section(uint32_t sectionId, const char* sectionName, CheerpWasmWriter* writer)
: hasName(sectionName), name(hasName ? (sectionName) : ""), sectionId(sectionId), writer(writer)
{
// Custom sections have a section name.
if (!sectionId) {
encodeULEB128(strlen(sectionName), *this);
(*this) << sectionName;
}
}
void Section::encode()
{
assert(state == State::GENERATING);
#if WASM_DUMP_SECTIONS
uint64_t start = writer->stream.tell();
if (hasName)
llvm::errs() << name << " ";
else
llvm::errs() << "unnamed section ";
llvm::errs() << "id=" << sectionId << " ";
llvm::errs() << "start=" << start << " ";
llvm::errs() << "end=" << start + tell() << " ";
llvm::errs() << "size=" << tell() << "\n";
#if WASM_DUMP_SECTION_DATA
llvm::errs() << "section: " << string_to_hex(str()) << '\n';
#endif
#endif
encodeULEB128(sectionId, writer->stream);
encodeULEB128(tell(), writer->stream);
writer->stream << str();
state = State::ENCODED;
}
void Section::discard()
{
assert(state == State::GENERATING);
state = State::DISCARDED;
}
Section::~Section()
{
assert(state == State::ENCODED || state == State::DISCARDED);
}
enum ConditionRenderMode {
NormalCondition = 0,
InvertCondition
};
uint32_t CheerpWasmWriter::findDepth(const Value* v) const
{
// Must be an instruction
const Instruction* I = dyn_cast<Instruction>(v);
if(!I)
return -1;
if(isInlineable(*I))
{
if(I->getNumOperands() < 1)
return -1;
uint32_t res = findDepth(I->getOperand(0));
if(I->isCommutative())
{
assert(I->getNumOperands() == 2);
res = std::min(res, findDepth(I->getOperand(1)));
}
return res;
}
else
{
return teeLocals.findDepth(v);
}
}
void CheerpWasmWriter::filterNop(SmallVectorImpl<char>& buf, std::function<void(uint32_t, char)> filterCallback) const
{
assert(buf.back() == 0x0b);
nopLocations.push_back(buf.size());
std::sort(nopLocations.begin(), nopLocations.end());
uint32_t nopIndex = 0;
uint32_t old = 0;
uint32_t curr = 0;
while (old < buf.size())
{
if (nopLocations[nopIndex] <= old)
{
//TODO: improve/justify the logic here
if (buf[old] == 0x01)
{
while (buf[old] == 0x01)
{
++old;
}
}
else if (buf[old] == (char)WasmInvalidOpcode::BRANCH_LIKELY || buf[old] == (char)WasmInvalidOpcode::BRANCH_UNLIKELY)
{
filterCallback(curr, buf[old]);
++old;
}
++nopIndex;
continue;
}
buf[curr] = buf[old];
++curr;
++old;
}
buf.resize(curr);
assert(buf.back() == 0x0b);
}
void CheerpWasmWriter::encodeBinOp(const llvm::Instruction& I, WasmBuffer& code)
{
switch (I.getOpcode()) {
case Instruction::URem:
case Instruction::UDiv:
compileUnsignedInteger(code, I.getOperand(0));
compileUnsignedInteger(code, I.getOperand(1));
break;
case Instruction::SRem:
case Instruction::SDiv:
compileSignedInteger(code, I.getOperand(0), /*forComparison*/ false);
compileSignedInteger(code, I.getOperand(1), /*forComparison*/ false);
break;
case Instruction::LShr:
compileUnsignedInteger(code, I.getOperand(0));
compileOperand(code, I.getOperand(1));
break;
case Instruction::AShr:
compileSignedInteger(code, I.getOperand(0), /*forComparison*/ false);
compileOperand(code, I.getOperand(1));
break;
case Instruction::FSub:
if (I.getOperand(0) == ConstantFP::getZeroValueForNegation(I.getOperand(0)->getType()))
{
//Wasm has an operator negate on floating point
//(-0.0) - something -> neg(something)
//Note that this transformation is safe only for negative zero
compileOperand(code, I.getOperand(1));
const Type* t = I.getType();
if (t->isFloatTy())
encodeInst(WasmOpcode::F32_NEG, code);
else if (t->isDoubleTy())
encodeInst(WasmOpcode::F64_NEG, code);
//We just encoded the operation, so now we can return
return;
}
else
{
compileOperand(code, I.getOperand(0));
compileOperand(code, I.getOperand(1));
break;
}
default:
if(I.isCommutative())
{
// Favor tee_local from the current candidate's stack
if (findDepth(I.getOperand(0)) > findDepth(I.getOperand(1)))
{
compileOperand(code, I.getOperand(1));
compileOperand(code, I.getOperand(0));
// Go out of the switch
break;
}
// Fallthrough
}
compileOperand(code, I.getOperand(0));
compileOperand(code, I.getOperand(1));
break;
}
const Type* t = I.getType();
if (t->isVectorTy())
{
const Type *et = dyn_cast<VectorType>(t)->getElementType();
if (I.getOpcode() == Instruction::Mul)
{
if (et->isIntegerTy(32))
encodeInst(WasmSIMDOpcode::I32x4_MUL, code);
else if (et->isIntegerTy(64))
encodeInst(WasmSIMDOpcode::I64x2_MUL, code);
else if (et->isIntegerTy(16))
encodeInst(WasmSIMDOpcode::I16x8_MUL, code);
else
llvm::report_fatal_error("unsupported bit width for vector integer mul");
return ;
}
else if (I.getOpcode() == Instruction::Add)
{
if (et->isIntegerTy(32))
encodeInst(WasmSIMDOpcode::I32x4_ADD, code);
else if (et->isIntegerTy(64))
encodeInst(WasmSIMDOpcode::I64x2_ADD, code);
else if (et->isIntegerTy(16))
encodeInst(WasmSIMDOpcode::I16x8_ADD, code);
else if (et->isIntegerTy(8))
encodeInst(WasmSIMDOpcode::I8x16_ADD, code);
else
llvm::report_fatal_error("unsupported bit width for vector integer add");
return ;
}
else if (I.getOpcode() == Instruction::Sub)
{
if (et->isIntegerTy(32))
encodeInst(WasmSIMDOpcode::I32x4_SUB, code);
else if (et->isIntegerTy(64))
encodeInst(WasmSIMDOpcode::I64x2_SUB, code);
else if (et->isIntegerTy(16))
encodeInst(WasmSIMDOpcode::I16x8_SUB, code);
else if (et->isIntegerTy(8))
encodeInst(WasmSIMDOpcode::I8x16_SUB, code);
else
llvm::report_fatal_error("unsupported bit width for vector integer sub");
return ;
}
else if (I.getOpcode() == Instruction::FMul)
{
if (et->isFloatTy())
encodeInst(WasmSIMDOpcode::F32x4_MUL, code);
else if (et->isDoubleTy())
encodeInst(WasmSIMDOpcode::F64x2_MUL, code);
else
llvm::report_fatal_error("unsupported format for vector float mul");
return ;
}
else if (I.getOpcode() == Instruction::FAdd)
{
if (et->isFloatTy())
encodeInst(WasmSIMDOpcode::F32x4_ADD, code);
else if (et->isDoubleTy())
encodeInst(WasmSIMDOpcode::F64x2_ADD, code);
else
llvm::report_fatal_error("unsupported format for vector float add");
return ;
}
else if (I.getOpcode() == Instruction::FSub)
{
if (et->isFloatTy())
encodeInst(WasmSIMDOpcode::F32x4_SUB, code);
else if (et->isDoubleTy())
encodeInst(WasmSIMDOpcode::F64x2_SUB, code);
else
llvm::report_fatal_error("unsupported format for vector float sub");
return ;
}
else if (I.getOpcode() == Instruction::FDiv)
{
if (et->isFloatTy())
encodeInst(WasmSIMDOpcode::F32x4_DIV, code);
else if (et->isDoubleTy())
encodeInst(WasmSIMDOpcode::F64x2_DIV, code);
else
llvm::report_fatal_error("unsupported format for vector float div");
return ;
}
else if (I.getOpcode() == Instruction::Xor)
{
encodeInst(WasmSIMDOpcode::V128_XOR, code);
return ;
}
else if (I.getOpcode() == Instruction::Or)
{
encodeInst(WasmSIMDOpcode::V128_OR, code);
return ;
}
else if (I.getOpcode() == Instruction::And)
{
encodeInst(WasmSIMDOpcode::V128_AND, code);
return ;
}
llvm::errs() << "Opcode is: " << I.getOpcodeName() << "\n";
llvm::report_fatal_error("unhandled vector op");
return ;
}
switch (I.getOpcode())
{
#define BINOPI(Ty, name) \
case Instruction::Ty: \
{ \
assert(t->isIntegerTy() || t->isPointerTy()); \
if (t->isIntegerTy(64)) { \
encodeInst(WasmOpcode::I64_##name, code); \
} \
else { \
encodeInst(WasmOpcode::I32_##name, code); \
} \
return; \
}
BINOPI( Add, ADD)
BINOPI( Sub, SUB)
BINOPI( Mul, MUL)
BINOPI(SDiv, DIV_S)
BINOPI(UDiv, DIV_U)
BINOPI(SRem, REM_S)
BINOPI(URem, REM_U)
BINOPI( And, AND)
BINOPI( Or, OR)
BINOPI( Xor, XOR)
BINOPI( Shl, SHL)
BINOPI(AShr, SHR_S)
BINOPI(LShr, SHR_U)
#undef BINOPI
#define BINOPF(Ty, name) \
case Instruction::Ty: \
{ \
if (t->isFloatTy()) { \
encodeInst(WasmOpcode::F32_##name, code); \
return; \
} \
else if (t->isDoubleTy()) { \
encodeInst(WasmOpcode::F64_##name, code); \
return; \
} \
else { \
llvm_unreachable("unsupported type"); \
} \
break; \
}
BINOPF(FAdd, ADD)
BINOPF(FSub, SUB)
BINOPF(FMul, MUL)
BINOPF(FDiv, DIV)
#undef BINOPF
default:
{
#ifndef NDEBUG
I.dump();
#endif
llvm_unreachable("unknown binop instruction");
}
}
#ifndef NDEBUG
I.dump();
#endif
llvm_unreachable("unknown type for binop instruction");
}
void CheerpWasmWriter::encodeInst(WasmOpcode opcode, WasmBuffer& code)
{
code << static_cast<char>(opcode);
}
void CheerpWasmWriter::encodeInst(WasmS32Opcode opcode, int32_t immediate, WasmBuffer& code)
{
code << static_cast<char>(opcode);
encodeSLEB128(immediate, code);
}
void CheerpWasmWriter::encodeInst(WasmS64Opcode opcode, int64_t immediate, WasmBuffer& code)
{
code << static_cast<char>(opcode);
encodeSLEB128(immediate, code);
}
void CheerpWasmWriter::encodeInst(WasmU32Opcode opcode, uint32_t immediate, WasmBuffer& code)
{
code << static_cast<char>(opcode);
encodeULEB128(immediate, code);
}
void CheerpWasmWriter::encodeInst(WasmU32U32Opcode opcode, uint32_t i1, uint32_t i2, WasmBuffer& code)
{
code << static_cast<char>(opcode);
encodeULEB128(i1, code);
encodeULEB128(i2, code);
}
void CheerpWasmWriter::encodeInst(WasmFCU32Opcode opcode, uint32_t immediate, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::FC);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(immediate, code);
}
void CheerpWasmWriter::encodeInst(WasmFCU32U32Opcode opcode, uint32_t i1, uint32_t i2, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::FC);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(i1, code);
encodeULEB128(i2, code);
}
void CheerpWasmWriter::encodeInst(WasmSIMDOpcode opcode, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(opcode), code);
}
void CheerpWasmWriter::encodeInst(WasmSIMDU32Opcode opcode, uint32_t immediate, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(immediate, code);
}
void CheerpWasmWriter::encodeInst(WasmSIMDU32U32Opcode opcode, uint32_t i1, uint32_t i2, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(i1, code);
encodeULEB128(i2, code);
}
void CheerpWasmWriter::encodeInst(WasmSIMDU32U32U32Opcode opcode, uint32_t i1, uint32_t i2, uint32_t i3, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(i1, code);
encodeULEB128(i2, code);
encodeULEB128(i3, code);
}
void CheerpWasmWriter::encodeInst(WasmThreadsU32Opcode opcode, uint32_t immediate, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::Threads);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(immediate, code);
}
void CheerpWasmWriter::encodeInst(WasmThreadsU32U32Opcode opcode, uint32_t i1, uint32_t i2, WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::Threads);
encodeULEB128(static_cast<uint64_t>(opcode), code);
encodeULEB128(i1, code);
encodeULEB128(i2, code);
}
void CheerpWasmWriter::encodeInst(WasmInvalidOpcode opcode, WasmBuffer& code)
{
nopLocations.push_back(code.tell());
code << static_cast<char>(opcode);
}
void CheerpWasmWriter::encodeVectorConstantZero(WasmBuffer& code)
{
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(WasmSIMDOpcode::V128_CONST), code);
for (int i = 0; i < 16; i++)
code << static_cast<char>(0);
}
void CheerpWasmWriter::encodeConstantDataVector(WasmBuffer& code, const llvm::ConstantDataVector* cdv)
{
char bytes[16];
memset(bytes, 0, 16);
const unsigned amount = cdv->getNumElements();
const unsigned fakeWidth = 128 / amount;
unsigned offset = 0;
if (cdv->getElementType()->isIntegerTy(32))
{
for (unsigned i = 0; i < amount; i++)
{
support::endian::write32le(bytes + offset, cdv->getElementAsInteger(i));
offset += fakeWidth / 8;
}
}
else if (cdv->getElementType()->isIntegerTy(64))
{
support::endian::write64le(bytes, cdv->getElementAsInteger(0));
support::endian::write64le(bytes + 8, cdv->getElementAsInteger(1));
}
else if (cdv->getElementType()->isIntegerTy(8))
{
for (unsigned i = 0; i < amount; i++)
{
bytes[offset] = cdv->getElementAsInteger(i);
offset += fakeWidth / 8;
}
}
else if (cdv->getElementType()->isIntegerTy(16))
{
for (unsigned i = 0; i < amount; i++)
{
support::endian::write16le(bytes + offset, cdv->getElementAsInteger(i));
offset += fakeWidth / 8;
}
}
else if (cdv->getElementType()->isFloatTy())
{
for (unsigned i = 0; i < amount; i++)
{
float floatElement = cdv->getElementAsFloat(i);
uint32_t intReinterpret = *reinterpret_cast<uint32_t*>(&floatElement);
support::endian::write32le(bytes + offset, intReinterpret);
offset += fakeWidth / 8;
}
}
else if (cdv->getElementType()->isDoubleTy())
{
for (unsigned i = 0; i < 2; i++)
{
double doubleElement = cdv->getElementAsDouble(i);
uint64_t intReinterpret = *reinterpret_cast<uint64_t*>(&doubleElement);
support::endian::write64le(bytes + i * 8, intReinterpret);
}
}
else
llvm::report_fatal_error("unhandled type for encode vector constant");
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(WasmSIMDOpcode::V128_CONST), code);
for (int i = 0; i < 16; i++)
code << bytes[i];
}
void CheerpWasmWriter::encodeConstantVector(WasmBuffer& code, const llvm::ConstantVector* cv)
{
// Loop over each element, encode it into the bytes array, then write the bytes array
const FixedVectorType* vecType = cv->getType();
const unsigned num = vecType->getNumElements();
char bytes[16];
memset(bytes, 0, 16);
int offset = 0;
Constant* element;
Type* type;
for (unsigned i = 0; i < num; i++)
{
element = cv->getAggregateElement(i);
if (ConstantInt* ci = dyn_cast<ConstantInt>(element))
{
int width = ci->getBitWidth();
// If it's a boolean, calculate the correct size by the number of elements.
if (width == 1)
width = 128 / vecType->getNumElements();
if (width == 8)
bytes[offset] = ci->getZExtValue();
else if (width == 16)
support::endian::write16le(bytes + offset, ci->getZExtValue());
else if (width == 32)
support::endian::write32le(bytes + offset, ci->getZExtValue());
else if (width == 64)
support::endian::write64le(bytes + offset, ci->getZExtValue());
offset += width / 8;
}
else if (ConstantFP* cf = dyn_cast<ConstantFP>(element))
{
if (cf->getType()->isDoubleTy())
{
support::endian::write64le(bytes + offset, cf->getValueAPF().convertToDouble());
offset += 8;
}
else
{
assert(cf->getType()->isFloatTy());
support::endian::write32le(bytes + offset, cf->getValueAPF().convertToFloat());
offset += 4;
}
}
else if (isa<ConstantPointerNull>(element))
{
support::endian::write32le(bytes + offset, 0);
offset += 4;
}
else if (UndefValue* uv = dyn_cast<UndefValue>(element))
{
type = uv->getType();
if (type->isIntegerTy(32) || type->isFloatTy() || type->isPointerTy())
{
support::endian::write32le(bytes + offset, 0);
offset += 4;
}
else if (type->isIntegerTy(64) || type->isDoubleTy())
{
support::endian::write64le(bytes + offset, 0);
offset += 8;
}
else if (type->isIntegerTy(16))
{
support::endian::write16le(bytes + offset, 0);
offset += 2;
}
else if (type->isIntegerTy(8))
{
bytes[offset] = 0;
offset++;
}
else
llvm::report_fatal_error("Unimplemented type for UndefValue");
}
else if (GlobalVariable* gv = dyn_cast<GlobalVariable>(element))
{
uint32_t address = linearHelper.getGlobalVariableAddress(gv);
support::endian::write32le(bytes + offset, address);
offset += 4;
}
else if (Function* f = dyn_cast<Function>(element))
{
if (linearHelper.functionHasAddress(f))
{
uint32_t addr = linearHelper.getFunctionAddress(f);
assert(addr && "function address is zero (aka nullptr conflict)");
encodeInst(WasmS32Opcode::I32_CONST, addr, code);
}
else
{
// When dealing with indirectly used undefined functions forward them to the null function
// TODO: This improve the robustness of the compiler, but it might generate unexpected behavor
// if the address is ever explicitly compared to 0
assert(f->empty());
encodeInst(WasmS32Opcode::I32_CONST, 0, code);
}
offset += 4;
}
else
llvm::report_fatal_error("Unimplemented type for encodeConstantVector");
}
code << static_cast<char>(WasmOpcode::SIMD);
encodeULEB128(static_cast<uint64_t>(WasmSIMDOpcode::V128_CONST), code);
for (int i = 0; i < 16; i++)
code << bytes[i];
}
void CheerpWasmWriter::encodeExtractLane(WasmBuffer& code, const llvm::ExtractElementInst& eei)
{
const FixedVectorType* vecType = cast<FixedVectorType>(eei.getVectorOperandType());
const unsigned num = vecType->getNumElements();
const Type* elementType = vecType->getElementType();
assert(isa<ConstantInt>(eei.getIndexOperand()));
uint64_t index = (dyn_cast<ConstantInt>(eei.getIndexOperand()))->getZExtValue();
if (getVectorBitwidth(vecType) != 128 && !elementType->isIntegerTy(1))
{
// We need to recalculate the index if the vector is not 128 bits in size.
const unsigned scaleFactor = 128 / getVectorBitwidth(vecType);
index *= scaleFactor;
}
compileOperand(code, eei.getVectorOperand());
if (elementType->isIntegerTy(32) || elementType->isPointerTy() || (elementType->isIntegerTy(1) && num == 4))
encodeInst(WasmSIMDU32Opcode::I32x4_EXTRACT_LANE, index, code);
else if (elementType->isIntegerTy(64) || (elementType->isIntegerTy(1) && num == 2))
{
encodeInst(WasmSIMDU32Opcode::I64x2_EXTRACT_LANE, index, code);
// If the vector holds booleans, resize to i32.
if (elementType->isIntegerTy(1))
encodeInst(WasmOpcode::I32_WRAP_I64, code);
}
else if (elementType->isIntegerTy(16) || (elementType->isIntegerTy(1) && num == 8))
encodeInst(WasmSIMDU32Opcode::I16x8_EXTRACT_LANE_U, index, code);
else if (elementType->isIntegerTy(8) || (elementType->isIntegerTy(1) && num == 16))
encodeInst(WasmSIMDU32Opcode::I8x16_EXTRACT_LANE_U, index, code);
else if (elementType->isFloatTy())
encodeInst(WasmSIMDU32Opcode::F32x4_EXTRACT_LANE, index, code);
else if (elementType->isDoubleTy())
encodeInst(WasmSIMDU32Opcode::F64x2_EXTRACT_LANE, index, code);
else
llvm::report_fatal_error("unhandled type for extract element");
}
void CheerpWasmWriter::encodeReplaceLane(WasmBuffer& code, const llvm::InsertElementInst& iei)
{
const FixedVectorType* vecType = cast<FixedVectorType>(iei.getType());
const unsigned num = vecType->getNumElements();
const Type* elementType = vecType->getElementType();
assert(isa<ConstantInt>(iei.getOperand(2)));
uint64_t index = (cast<ConstantInt>(iei.getOperand(2)))->getZExtValue();
if (getVectorBitwidth(vecType) != 128 && !elementType->isIntegerTy(1))
{
// We need to recalculate the index if the vector is not 128 bits in size.
const unsigned scaleFactor = 128 / getVectorBitwidth(vecType);
index *= scaleFactor;
}
compileOperand(code, iei.getOperand(0));
compileOperand(code, iei.getOperand(1));
if (elementType->isIntegerTy(32) || elementType->isPointerTy() || (elementType->isIntegerTy(1) && num == 4))
encodeInst(WasmSIMDU32Opcode::I32x4_REPLACE_LANE, index, code);
else if (elementType->isIntegerTy(64) || (elementType->isIntegerTy(1) && num == 2))
{
// If the insert is from a boolean value, extend to i64 first.
if (elementType->isIntegerTy(1))
encodeInst(WasmOpcode::I64_EXTEND_S_I32, code);
encodeInst(WasmSIMDU32Opcode::I64x2_REPLACE_LANE, index, code);
}
else if (elementType->isIntegerTy(16) || (elementType->isIntegerTy(1) && num == 8))
encodeInst(WasmSIMDU32Opcode::I16x8_REPLACE_LANE, index, code);
else if (elementType->isIntegerTy(8) || (elementType->isIntegerTy(1) && num == 16))
encodeInst(WasmSIMDU32Opcode::I8x16_REPLACE_LANE, index, code);
else if (elementType->isFloatTy())
encodeInst(WasmSIMDU32Opcode::F32x4_REPLACE_LANE, index, code);
else if (elementType->isDoubleTy())
encodeInst(WasmSIMDU32Opcode::F64x2_REPLACE_LANE, index, code);
else
llvm::report_fatal_error("unhandled type for insert element");
}
void CheerpWasmWriter::encodeVectorTruncation(WasmBuffer& code, const llvm::Instruction& I)
{
// We zero out the now unused lanes.
const CastInst& ci = cast<CastInst>(I);
const FixedVectorType* destVecType = cast<FixedVectorType>(ci.getDestTy());
const unsigned amount = destVecType->getNumElements();
const unsigned elementWidth = destVecType->getScalarSizeInBits();
const unsigned fakeWidth = 128 / amount;
// We need to create a vector to function as a mask. This will be a vector with 16 bytes.
unsigned currentWidth = 0;
SmallVector<uint8_t, 16> mask;
for (unsigned i = 0; i < 16; i++)
{
if (currentWidth < elementWidth)
mask.push_back(-1);
else
mask.push_back(0);
currentWidth = (currentWidth + 8) % fakeWidth;
}
Value* maskVector = ConstantDataVector::get(module.getContext(), mask);
const ConstantDataVector* cdv = cast<ConstantDataVector>(maskVector);
encodeConstantDataVector(code, cdv);
encodeInst(WasmSIMDOpcode::V128_AND, code);
}
void CheerpWasmWriter::encodeLoadingShuffle(WasmBuffer& code, const llvm::FixedVectorType* vecType)
{
// This function will encode a shuffle instruction that is used to support vectors
// smaller than 128 bits. Only the first bits are loaded, and need to be shuffled
// to the correct spots in the vector.
encodeVectorConstantZero(code);
encodeInst(WasmSIMDOpcode::I8x16_SHUFFLE, code);
const unsigned num = vecType->getNumElements();
const Type* elementType = vecType->getElementType();
const unsigned elementWidth = elementType->isPointerTy() ? 32 : vecType->getScalarSizeInBits();
const unsigned fakeWidth = 128 / num;
unsigned currentWidth = 0;
unsigned index = 0;
for (unsigned i = 0; i < 16; i++)
{
if (currentWidth < elementWidth)
code << static_cast<char>(index++);
else
code << static_cast<char>(8);
currentWidth = (currentWidth + 8) % fakeWidth;
}
}
void CheerpWasmWriter::encodeStoringShuffle(WasmBuffer& code, const llvm::FixedVectorType* vecType)
{
// This function will encode a shuffle instruction that is used to support vector
// smaller than 128 bits. It will shuffle the elements from the various lanes into
// a single bigger lane, so they can be stored all at once.
encodeVectorConstantZero(code);
encodeInst(WasmSIMDOpcode::I8x16_SHUFFLE, code);
const unsigned num = vecType->getNumElements();
const Type* elementType = vecType->getElementType();
const unsigned elementWidth = elementType->isPointerTy() ? 32 : vecType->getScalarSizeInBits();
const unsigned fakeLaneWidth = 16 / num;
unsigned elementsHandled = 0;
unsigned currentWidth = 0;
for (unsigned i = 0; i < 16; i++)
{
if (elementsHandled < num)
{
unsigned laneNum = elementsHandled * fakeLaneWidth + (currentWidth / 8);
code << static_cast<char>(laneNum);
currentWidth += 8;
if (currentWidth == elementWidth)
{
currentWidth = 0;
elementsHandled++;
}
}
else
code << static_cast<char>(15);
}
}
void CheerpWasmWriter::encodeBranchHint(const llvm::BranchInst* BI, const bool IfNot, WasmBuffer& code)
{
if(!WasmBranchHints)
return;
auto branchHint = shouldBranchBeHinted(BI, IfNot);
if (branchHint == BranchHint::Likely)
encodeInst(WasmInvalidOpcode::BRANCH_LIKELY, code);
else if (branchHint == BranchHint::Unlikely)
encodeInst(WasmInvalidOpcode::BRANCH_UNLIKELY, code);
}
void CheerpWasmWriter::encodePredicate(const llvm::Type* ty, const llvm::CmpInst::Predicate predicate, WasmBuffer& code)
{
assert(ty->isIntegerTy() || ty->isPointerTy() || ty->isVectorTy());
const Type* elementType = nullptr;
unsigned num = 0;
bool booleanCompare = false;
if (ty->isVectorTy())
{
const FixedVectorType* vecType = cast<FixedVectorType>(ty);
elementType = vecType->getElementType();
num = vecType->getNumElements();
booleanCompare = elementType->isIntegerTy(1);
if (elementType->isIntegerTy(64) || (booleanCompare && num == 2))
{
if (predicate == CmpInst::ICMP_EQ)
encodeInst(WasmSIMDOpcode::I64x2_EQ, code);
else if (predicate == CmpInst::ICMP_NE)
encodeInst(WasmSIMDOpcode::I64x2_NE, code);
else if (predicate == CmpInst::ICMP_SLT)
encodeInst(WasmSIMDOpcode::I64x2_LT_S, code);
else if (predicate == CmpInst::ICMP_SGT)
encodeInst(WasmSIMDOpcode::I64x2_GT_S, code);
else if (predicate == CmpInst::ICMP_SLE)
encodeInst(WasmSIMDOpcode::I64x2_LE_S, code);
else if (predicate == CmpInst::ICMP_SGE)
encodeInst(WasmSIMDOpcode::I64x2_GE_S, code);
else
llvm::report_fatal_error("Unsupported predicate for 64-bit icmp");
return ;
}
}
switch(predicate)
{
#define PREDICATE(Ty, name) \
case CmpInst::ICMP_##Ty: \
if (ty->isIntegerTy(64)) \
encodeInst(WasmOpcode::I64_##name, code); \
else if (ty->isVectorTy()) \
{ \
if (elementType->isIntegerTy(32) || elementType->isPointerTy() || (booleanCompare && num == 4)) \
encodeInst(WasmSIMDOpcode::I32x4_##name, code); \
else if (elementType->isIntegerTy(8) || (booleanCompare && num == 16))\
encodeInst(WasmSIMDOpcode::I8x16_##name, code); \
else if (elementType->isIntegerTy(16) || (booleanCompare && num == 8))\
encodeInst(WasmSIMDOpcode::I16x8_##name, code); \