-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLLVMEmitIR.cpp
1379 lines (1178 loc) · 60.7 KB
/
LLVMEmitIR.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
The EOS VM Optimized Compiler was created in part based on WAVM
https://github.com/WebAssembly/wasm-jit-prototype
subject the following:
Copyright (c) 2016-2019, Andrew Scheidecker
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of WAVM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "LLVMJIT.h"
#include "llvm/ADT/SmallVector.h"
#include "IR/Operators.h"
#include "IR/OperatorPrinter.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/SymbolSize.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Utils.h"
#include <eosio/chain/webassembly/eos-vm-oc/intrinsic.hpp>
#include <eosio/chain/webassembly/eos-vm-oc/memory.hpp>
#define ENABLE_LOGGING 0
#define ENABLE_FUNCTION_ENTER_EXIT_HOOKS 0
using namespace IR;
namespace eosio { namespace chain { namespace eosvmoc {
namespace LLVMJIT
{
static std::string getExternalFunctionName(Uptr functionDefIndex)
{
return "wasmFunc" + std::to_string(functionDefIndex);
}
const char* getTableSymbolName() {
return "wasmTable";
}
bool getFunctionIndexFromExternalName(const char* externalName,Uptr& outFunctionDefIndex)
{
const char wasmFuncPrefix[] = "wasmFunc";
const Uptr numPrefixChars = sizeof(wasmFuncPrefix) - 1;
if(!strncmp(externalName,wasmFuncPrefix,numPrefixChars))
{
char* numberEnd = nullptr;
U64 functionDefIndex64 = std::strtoull(externalName + numPrefixChars,&numberEnd,10);
if(functionDefIndex64 > UINTPTR_MAX) { return false; }
outFunctionDefIndex = Uptr(functionDefIndex64);
return true;
}
else { return false; }
}
llvm::LLVMContext context;
llvm::Type* llvmResultTypes[(Uptr)ResultType::num];
llvm::Type* llvmI8Type;
llvm::Type* llvmI16Type;
llvm::Type* llvmI32Type;
llvm::Type* llvmI64Type;
llvm::Type* llvmF32Type;
llvm::Type* llvmF64Type;
llvm::Type* llvmVoidType;
llvm::Type* llvmBoolType;
llvm::Type* llvmI8PtrType;
llvm::Constant* typedZeroConstants[(Uptr)ValueType::num];
// Converts a WebAssembly type to a LLVM type.
inline llvm::Type* asLLVMType(ValueType type) { return llvmResultTypes[(Uptr)asResultType(type)]; }
inline llvm::Type* asLLVMType(ResultType type) { return llvmResultTypes[(Uptr)type]; }
// Converts a WebAssembly function type to a LLVM type.
inline llvm::FunctionType* asLLVMType(const FunctionType* functionType)
{
auto llvmArgTypes = (llvm::Type**)alloca(sizeof(llvm::Type*) * functionType->parameters.size());
for(Uptr argIndex = 0;argIndex < functionType->parameters.size();++argIndex)
{
llvmArgTypes[argIndex] = asLLVMType(functionType->parameters[argIndex]);
}
auto llvmResultType = asLLVMType(functionType->ret);
return llvm::FunctionType::get(llvmResultType,llvm::ArrayRef<llvm::Type*>(llvmArgTypes,functionType->parameters.size()),false);
}
// Overloaded functions that compile a literal value to a LLVM constant of the right type.
inline llvm::ConstantInt* emitLiteral(U32 value) { return (llvm::ConstantInt*)llvm::ConstantInt::get(llvmI32Type,llvm::APInt(32,(U64)value,false)); }
inline llvm::ConstantInt* emitLiteral(I32 value) { return (llvm::ConstantInt*)llvm::ConstantInt::get(llvmI32Type,llvm::APInt(32,(I64)value,false)); }
inline llvm::ConstantInt* emitLiteral(U64 value) { return (llvm::ConstantInt*)llvm::ConstantInt::get(llvmI64Type,llvm::APInt(64,value,false)); }
inline llvm::ConstantInt* emitLiteral(I64 value) { return (llvm::ConstantInt*)llvm::ConstantInt::get(llvmI64Type,llvm::APInt(64,value,false)); }
inline llvm::Constant* emitLiteral(F32 value) { return llvm::ConstantFP::get(context,llvm::APFloat(value)); }
inline llvm::Constant* emitLiteral(F64 value) { return llvm::ConstantFP::get(context,llvm::APFloat(value)); }
inline llvm::Constant* emitLiteral(bool value) { return llvm::ConstantInt::get(llvmBoolType,llvm::APInt(1,value ? 1 : 0,false)); }
inline llvm::Constant* emitLiteralPointer(const void* pointer,llvm::Type* type)
{
auto pointerInt = llvm::APInt(sizeof(Uptr) == 8 ? 64 : 32,reinterpret_cast<Uptr>(pointer));
return llvm::Constant::getIntegerValue(type,pointerInt);
}
// The LLVM IR for a module.
struct EmitModuleContext
{
const Module& module;
llvm::Module* llvmModule;
std::vector<llvm::Function*> functionDefs;
std::vector<size_t> importedFunctionOffsets;
std::vector<llvm::Constant*> globals;
llvm::GlobalVariable* defaultTablePointer;
llvm::Constant* defaultTableMaxElementIndex;
llvm::Constant* defaultMemoryBase;
llvm::Constant* depthCounter;
bool tableOnlyHasDefinedFuncs = true;
llvm::MDNode* likelyFalseBranchWeights;
llvm::MDNode* likelyTrueBranchWeights;
EmitModuleContext(const Module& inModule)
: module(inModule)
, llvmModule(new llvm::Module("",context))
{
auto zeroAsMetadata = llvm::ConstantAsMetadata::get(emitLiteral(I32(0)));
auto i32MaxAsMetadata = llvm::ConstantAsMetadata::get(emitLiteral(I32(INT32_MAX)));
likelyFalseBranchWeights = llvm::MDTuple::getDistinct(context,{llvm::MDString::get(context,"branch_weights"),zeroAsMetadata,i32MaxAsMetadata});
likelyTrueBranchWeights = llvm::MDTuple::getDistinct(context,{llvm::MDString::get(context,"branch_weights"),i32MaxAsMetadata,zeroAsMetadata});
}
llvm::Module* emit();
};
// The context used by functions involved in JITing a single AST function.
struct EmitFunctionContext
{
typedef void Result;
EmitModuleContext& moduleContext;
const Module& module;
const FunctionDef& functionDef;
const FunctionType* functionType;
llvm::Function* llvmFunction;
llvm::IRBuilder<> irBuilder;
std::vector<llvm::Value*> localPointers;
llvm::DISubprogram* diFunction;
// Information about an in-scope control structure.
struct ControlContext
{
enum class Type : U8
{
function,
block,
ifThen,
ifElse,
loop
};
Type type;
llvm::BasicBlock* endBlock;
llvm::PHINode* endPHI;
llvm::BasicBlock* elseBlock;
ResultType resultType;
Uptr outerStackSize;
Uptr outerBranchTargetStackSize;
bool isReachable;
bool isElseReachable;
};
struct BranchTarget
{
ResultType argumentType;
llvm::BasicBlock* block;
llvm::PHINode* phi;
};
std::vector<ControlContext> controlStack;
std::vector<BranchTarget> branchTargetStack;
std::vector<llvm::Value*> stack;
EmitFunctionContext(EmitModuleContext& inEmitModuleContext,const Module& inModule,const FunctionDef& inFunctionDef,llvm::Function* inLLVMFunction)
: moduleContext(inEmitModuleContext)
, module(inModule)
, functionDef(inFunctionDef)
, functionType(inModule.types[inFunctionDef.type.index])
, llvmFunction(inLLVMFunction)
, irBuilder(context)
{}
void emit();
// Operand stack manipulation
llvm::Value* pop()
{
WAVM_ASSERT_THROW(stack.size() - (controlStack.size() ? controlStack.back().outerStackSize : 0) >= 1);
llvm::Value* result = stack.back();
stack.pop_back();
return result;
}
void popMultiple(llvm::Value** outValues,Uptr num)
{
WAVM_ASSERT_THROW(stack.size() - (controlStack.size() ? controlStack.back().outerStackSize : 0) >= num);
std::copy(stack.end() - num,stack.end(),outValues);
stack.resize(stack.size() - num);
}
llvm::Value* getTopValue() const
{
return stack.back();
}
void push(llvm::Value* value)
{
stack.push_back(value);
}
// Creates a PHI node for the argument of branches to a basic block.
llvm::PHINode* createPHI(llvm::BasicBlock* basicBlock,ResultType type)
{
if(type == ResultType::none) { return nullptr; }
else
{
auto originalBlock = irBuilder.GetInsertBlock();
irBuilder.SetInsertPoint(basicBlock);
auto phi = irBuilder.CreatePHI(asLLVMType(type),2);
if(originalBlock) { irBuilder.SetInsertPoint(originalBlock); }
return phi;
}
}
// Debug logging.
void logOperator(const std::string& operatorDescription)
{
if(ENABLE_LOGGING)
{
std::string controlStackString;
for(Uptr stackIndex = 0;stackIndex < controlStack.size();++stackIndex)
{
if(!controlStack[stackIndex].isReachable) { controlStackString += "("; }
switch(controlStack[stackIndex].type)
{
case ControlContext::Type::function: controlStackString += "F"; break;
case ControlContext::Type::block: controlStackString += "B"; break;
case ControlContext::Type::ifThen: controlStackString += "T"; break;
case ControlContext::Type::ifElse: controlStackString += "E"; break;
case ControlContext::Type::loop: controlStackString += "L"; break;
default: Errors::unreachable();
};
if(!controlStack[stackIndex].isReachable) { controlStackString += ")"; }
}
std::string stackString;
const Uptr stackBase = controlStack.size() == 0 ? 0 : controlStack.back().outerStackSize;
for(Uptr stackIndex = 0;stackIndex < stack.size();++stackIndex)
{
if(stackIndex == stackBase) { stackString += "| "; }
{
llvm::raw_string_ostream stackTypeStream(stackString);
stack[stackIndex]->getType()->print(stackTypeStream,true);
}
stackString += " ";
}
if(stack.size() == stackBase) { stackString += "|"; }
//Log::printf(Log::Category::debug,"%-50s %-50s %-50s\n",controlStackString.c_str(),operatorDescription.c_str(),stackString.c_str());
}
}
// Coerces an I32 value to an I1, and vice-versa.
llvm::Value* coerceI32ToBool(llvm::Value* i32Value)
{
return irBuilder.CreateICmpNE(i32Value,typedZeroConstants[(Uptr)ValueType::i32]);
}
llvm::Value* coerceBoolToI32(llvm::Value* boolValue)
{
return irBuilder.CreateZExt(boolValue,llvmI32Type);
}
// Bounds checks and converts a memory operation I32 address operand to a LLVM pointer.
llvm::Value* coerceByteIndexToPointer(llvm::Value* byteIndex,U32 offset,llvm::Type* memoryType)
{
// On a 64 bit runtime, if the address is 32-bits, zext it to 64-bits.
// This is crucial for security, as LLVM will otherwise implicitly sign extend it to 64-bits in the GEP below,
// interpreting it as a signed offset and allowing access to memory outside the sandboxed memory range.
// There are no 'far addresses' in a 32 bit runtime.
byteIndex = irBuilder.CreateZExt(byteIndex,llvmI64Type);
// Add the offset to the byte index.
if(offset)
{
byteIndex = irBuilder.CreateAdd(byteIndex,irBuilder.CreateZExt(emitLiteral(offset),llvmI64Type));
}
// Cast the pointer to the appropriate type.
auto bytePointer = irBuilder.CreateInBoundsGEP(moduleContext.defaultMemoryBase, byteIndex);
return irBuilder.CreatePointerCast(bytePointer,memoryType->getPointerTo(256));
}
// Traps a divide-by-zero
void trapDivideByZero(ValueType type,llvm::Value* divisor)
{
emitConditionalTrapIntrinsic(
irBuilder.CreateICmpEQ(divisor,typedZeroConstants[(Uptr)type]),
"eosvmoc_internal.div0_or_overflow",FunctionType::get(),{});
}
// Traps on (x / 0) or (INT_MIN / -1).
void trapDivideByZeroOrIntegerOverflow(ValueType type,llvm::Value* left,llvm::Value* right)
{
emitConditionalTrapIntrinsic(
irBuilder.CreateOr(
irBuilder.CreateAnd(
irBuilder.CreateICmpEQ(left,type == ValueType::i32 ? emitLiteral((U32)INT32_MIN) : emitLiteral((U64)INT64_MIN)),
irBuilder.CreateICmpEQ(right,type == ValueType::i32 ? emitLiteral((U32)-1) : emitLiteral((U64)-1))
),
irBuilder.CreateICmpEQ(right,typedZeroConstants[(Uptr)type])
),
"eosvmoc_internal.div0_or_overflow",FunctionType::get(),{});
}
//llvm11 removed inferring the function type automatically, plumb CreateCalls through here as done for 10 & earlier
llvm::CallInst* createCall(llvm::Value* Callee, llvm::ArrayRef<llvm::Value*> Args) {
auto* PTy = llvm::cast<llvm::PointerType>(Callee->getType());
auto* FTy = llvm::cast<llvm::FunctionType>(PTy->getElementType());
return irBuilder.CreateCall(FTy, Callee, Args);
}
llvm::Value* getLLVMIntrinsic(const std::initializer_list<llvm::Type*>& argTypes,llvm::Intrinsic::ID id)
{
return llvm::Intrinsic::getDeclaration(moduleContext.llvmModule,id,llvm::ArrayRef<llvm::Type*>(argTypes.begin(),argTypes.end()));
}
// Emits a call to a WAVM intrinsic function.
llvm::Value* emitRuntimeIntrinsic(const char* intrinsicName,const FunctionType* intrinsicType,const std::initializer_list<llvm::Value*>& args)
{
const eosio::chain::eosvmoc::intrinsic_entry& ie = eosio::chain::eosvmoc::get_intrinsic_map().at(intrinsicName);
llvm::Value* ic = irBuilder.CreateLoad( emitLiteralPointer((void*)(OFFSET_OF_FIRST_INTRINSIC-ie.ordinal*8), llvmI64Type->getPointerTo(256)) );
llvm::Value* itp = irBuilder.CreateIntToPtr(ic, asLLVMType(ie.type)->getPointerTo());
return createCall(itp,llvm::ArrayRef<llvm::Value*>(args.begin(),args.end()));
}
// A helper function to emit a conditional call to a non-returning intrinsic function.
void emitConditionalTrapIntrinsic(llvm::Value* booleanCondition,const char* intrinsicName,const FunctionType* intrinsicType,const std::initializer_list<llvm::Value*>& args)
{
auto trueBlock = llvm::BasicBlock::Create(context,llvm::Twine(intrinsicName) + "Trap",llvmFunction);
auto endBlock = llvm::BasicBlock::Create(context,llvm::Twine(intrinsicName) + "Skip",llvmFunction);
irBuilder.CreateCondBr(booleanCondition,trueBlock,endBlock,moduleContext.likelyFalseBranchWeights);
irBuilder.SetInsertPoint(trueBlock);
emitRuntimeIntrinsic(intrinsicName,intrinsicType,args);
irBuilder.CreateUnreachable();
irBuilder.SetInsertPoint(endBlock);
}
//
// Misc operators
//
void nop(NoImm) {}
void unknown(Opcode opcode) { Errors::unreachable(); }
//
// Control structure operators
//
void pushControlStack(
ControlContext::Type type,
ResultType resultType,
llvm::BasicBlock* endBlock,
llvm::PHINode* endPHI,
llvm::BasicBlock* elseBlock = nullptr
)
{
// The unreachable operator filtering should filter out any opcodes that call pushControlStack.
if(controlStack.size()) { errorUnless(controlStack.back().isReachable); }
controlStack.push_back({type,endBlock,endPHI,elseBlock,resultType,stack.size(),branchTargetStack.size(),true,true});
}
void pushBranchTarget(ResultType branchArgumentType,llvm::BasicBlock* branchTargetBlock,llvm::PHINode* branchTargetPHI)
{
branchTargetStack.push_back({branchArgumentType,branchTargetBlock,branchTargetPHI});
}
void block(ControlStructureImm imm)
{
// Create an end block+phi for the block result.
auto endBlock = llvm::BasicBlock::Create(context,"blockEnd",llvmFunction);
auto endPHI = createPHI(endBlock,imm.resultType);
// Push a control context that ends at the end block/phi.
pushControlStack(ControlContext::Type::block,imm.resultType,endBlock,endPHI);
// Push a branch target for the end block/phi.
pushBranchTarget(imm.resultType,endBlock,endPHI);
}
void loop(ControlStructureImm imm)
{
// Create a loop block, and an end block+phi for the loop result.
auto loopBodyBlock = llvm::BasicBlock::Create(context,"loopBody",llvmFunction);
auto endBlock = llvm::BasicBlock::Create(context,"loopEnd",llvmFunction);
auto endPHI = createPHI(endBlock,imm.resultType);
// Branch to the loop body and switch the IR builder to emit there.
irBuilder.CreateBr(loopBodyBlock);
irBuilder.SetInsertPoint(loopBodyBlock);
// Push a control context that ends at the end block/phi.
pushControlStack(ControlContext::Type::loop,imm.resultType,endBlock,endPHI);
// Push a branch target for the loop body start.
pushBranchTarget(ResultType::none,loopBodyBlock,nullptr);
}
void if_(ControlStructureImm imm)
{
// Create a then block and else block for the if, and an end block+phi for the if result.
auto thenBlock = llvm::BasicBlock::Create(context,"ifThen",llvmFunction);
auto elseBlock = llvm::BasicBlock::Create(context,"ifElse",llvmFunction);
auto endBlock = llvm::BasicBlock::Create(context,"ifElseEnd",llvmFunction);
auto endPHI = createPHI(endBlock,imm.resultType);
// Pop the if condition from the operand stack.
auto condition = pop();
irBuilder.CreateCondBr(coerceI32ToBool(condition),thenBlock,elseBlock);
// Switch the IR builder to emit the then block.
irBuilder.SetInsertPoint(thenBlock);
// Push an ifThen control context that ultimately ends at the end block/phi, but may
// be terminated by an else operator that changes the control context to the else block.
pushControlStack(ControlContext::Type::ifThen,imm.resultType,endBlock,endPHI,elseBlock);
// Push a branch target for the if end.
pushBranchTarget(imm.resultType,endBlock,endPHI);
}
void else_(NoImm imm)
{
WAVM_ASSERT_THROW(controlStack.size());
ControlContext& currentContext = controlStack.back();
if(currentContext.isReachable)
{
// If the control context expects a result, take it from the operand stack and add it to the
// control context's end PHI.
if(currentContext.resultType != ResultType::none)
{
llvm::Value* result = pop();
currentContext.endPHI->addIncoming(result,irBuilder.GetInsertBlock());
}
// Branch to the control context's end.
irBuilder.CreateBr(currentContext.endBlock);
}
WAVM_ASSERT_THROW(stack.size() == currentContext.outerStackSize);
// Switch the IR emitter to the else block.
WAVM_ASSERT_THROW(currentContext.elseBlock);
WAVM_ASSERT_THROW(currentContext.type == ControlContext::Type::ifThen);
currentContext.elseBlock->moveAfter(irBuilder.GetInsertBlock());
irBuilder.SetInsertPoint(currentContext.elseBlock);
// Change the top of the control stack to an else clause.
currentContext.type = ControlContext::Type::ifElse;
currentContext.isReachable = currentContext.isElseReachable;
currentContext.elseBlock = nullptr;
}
void end(NoImm)
{
WAVM_ASSERT_THROW(controlStack.size());
ControlContext& currentContext = controlStack.back();
if(currentContext.isReachable)
{
// If the control context yields a result, take the top of the operand stack and
// add it to the control context's end PHI.
if(currentContext.resultType != ResultType::none)
{
llvm::Value* result = pop();
currentContext.endPHI->addIncoming(result,irBuilder.GetInsertBlock());
}
// Branch to the control context's end.
irBuilder.CreateBr(currentContext.endBlock);
}
WAVM_ASSERT_THROW(stack.size() == currentContext.outerStackSize);
if(currentContext.elseBlock)
{
// If this is the end of an if without an else clause, create a dummy else clause.
currentContext.elseBlock->moveAfter(irBuilder.GetInsertBlock());
irBuilder.SetInsertPoint(currentContext.elseBlock);
irBuilder.CreateBr(currentContext.endBlock);
}
// Switch the IR emitter to the end block.
currentContext.endBlock->moveAfter(irBuilder.GetInsertBlock());
irBuilder.SetInsertPoint(currentContext.endBlock);
if(currentContext.endPHI)
{
// If the control context yields a result, take the PHI that merges all the control flow
// to the end and push it onto the operand stack.
if(currentContext.endPHI->getNumIncomingValues()) { push(currentContext.endPHI); }
else
{
// If there weren't any incoming values for the end PHI, remove it and push a dummy value.
currentContext.endPHI->eraseFromParent();
WAVM_ASSERT_THROW(currentContext.resultType != ResultType::none);
push(typedZeroConstants[(Uptr)asValueType(currentContext.resultType)]);
}
}
// Pop and branch targets introduced by this control context.
WAVM_ASSERT_THROW(currentContext.outerBranchTargetStackSize <= branchTargetStack.size());
branchTargetStack.resize(currentContext.outerBranchTargetStackSize);
// Pop this control context.
controlStack.pop_back();
}
//
// Control flow operators
//
BranchTarget& getBranchTargetByDepth(Uptr depth)
{
WAVM_ASSERT_THROW(depth < branchTargetStack.size());
return branchTargetStack[branchTargetStack.size() - depth - 1];
}
// This is called after unconditional control flow to indicate that operators following it are unreachable until the control stack is popped.
void enterUnreachable()
{
// Unwind the operand stack to the outer control context.
WAVM_ASSERT_THROW(controlStack.back().outerStackSize <= stack.size());
stack.resize(controlStack.back().outerStackSize);
// Mark the current control context as unreachable: this will cause the outer loop to stop dispatching operators to us
// until an else/end for the current control context is reached.
controlStack.back().isReachable = false;
}
void br_if(BranchImm imm)
{
// Pop the condition from operand stack.
auto condition = pop();
BranchTarget& target = getBranchTargetByDepth(imm.targetDepth);
if(target.argumentType != ResultType::none)
{
// Use the stack top as the branch argument (don't pop it) and add it to the target phi's incoming values.
llvm::Value* argument = getTopValue();
target.phi->addIncoming(argument,irBuilder.GetInsertBlock());
}
// Create a new basic block for the case where the branch is not taken.
auto falseBlock = llvm::BasicBlock::Create(context,"br_ifElse",llvmFunction);
// Emit a conditional branch to either the falseBlock or the target block.
irBuilder.CreateCondBr(coerceI32ToBool(condition),target.block,falseBlock);
// Resume emitting instructions in the falseBlock.
irBuilder.SetInsertPoint(falseBlock);
}
void br(BranchImm imm)
{
BranchTarget& target = getBranchTargetByDepth(imm.targetDepth);
if(target.argumentType != ResultType::none)
{
// Pop the branch argument from the stack and add it to the target phi's incoming values.
llvm::Value* argument = pop();
target.phi->addIncoming(argument,irBuilder.GetInsertBlock());
}
// Branch to the target block.
irBuilder.CreateBr(target.block);
enterUnreachable();
}
void br_table(BranchTableImm imm)
{
// Pop the table index from the operand stack.
auto index = pop();
// Look up the default branch target, and assume its argument type applies to all targets.
// (this is guaranteed by the validator)
BranchTarget& defaultTarget = getBranchTargetByDepth(imm.defaultTargetDepth);
const ResultType argumentType = defaultTarget.argumentType;
llvm::Value* argument = nullptr;
if(argumentType != ResultType::none)
{
// Pop the branch argument from the stack and add it to the default target phi's incoming values.
argument = pop();
defaultTarget.phi->addIncoming(argument,irBuilder.GetInsertBlock());
}
// Create a LLVM switch instruction.
WAVM_ASSERT_THROW(imm.branchTableIndex < functionDef.branchTables.size());
const std::vector<U32>& targetDepths = functionDef.branchTables[imm.branchTableIndex];
auto llvmSwitch = irBuilder.CreateSwitch(index,defaultTarget.block,(unsigned int)targetDepths.size());
for(Uptr targetIndex = 0;targetIndex < targetDepths.size();++targetIndex)
{
BranchTarget& target = getBranchTargetByDepth(targetDepths[targetIndex]);
// Add this target to the switch instruction.
llvmSwitch->addCase(emitLiteral((U32)targetIndex),target.block);
if(argumentType != ResultType::none)
{
// If this is the first case in the table for this branch target, add the branch argument to
// the target phi's incoming values.
target.phi->addIncoming(argument,irBuilder.GetInsertBlock());
}
}
enterUnreachable();
}
void return_(NoImm)
{
if(functionType->ret != ResultType::none)
{
// Pop the return value from the stack and add it to the return phi's incoming values.
llvm::Value* result = pop();
controlStack[0].endPHI->addIncoming(result,irBuilder.GetInsertBlock());
}
// Branch to the return block.
irBuilder.CreateBr(controlStack[0].endBlock);
enterUnreachable();
}
void unreachable(NoImm)
{
// Call an intrinsic that causes a trap, and insert the LLVM unreachable terminator.
emitRuntimeIntrinsic("eosvmoc_internal.unreachable",FunctionType::get(),{});
irBuilder.CreateUnreachable();
enterUnreachable();
}
//
// Polymorphic operators
//
void drop(NoImm) { stack.pop_back(); }
void select(NoImm)
{
auto condition = pop();
auto falseValue = pop();
auto trueValue = pop();
push(irBuilder.CreateSelect(coerceI32ToBool(condition),trueValue,falseValue));
}
//
// Call operators
//
void call(CallImm imm)
{
// Map the callee function index to either an imported function pointer or a function in this module.
llvm::Value* callee;
const FunctionType* calleeType;
bool isExit = false;
bool isMemcpy = false;
if(imm.functionIndex < moduleContext.importedFunctionOffsets.size())
{
calleeType = module.types[module.functions.imports[imm.functionIndex].type.index];
llvm::Value* ic = irBuilder.CreateLoad( emitLiteralPointer((void*)(OFFSET_OF_FIRST_INTRINSIC-moduleContext.importedFunctionOffsets[imm.functionIndex]*8), llvmI64Type->getPointerTo(256)) );
callee = irBuilder.CreateIntToPtr(ic, asLLVMType(calleeType)->getPointerTo());
isExit = module.functions.imports[imm.functionIndex].moduleName == "env" && module.functions.imports[imm.functionIndex].exportName == "eosio_exit";
isMemcpy = module.functions.imports[imm.functionIndex].moduleName == "env" && module.functions.imports[imm.functionIndex].exportName == "memcpy";
}
else
{
const Uptr calleeIndex = imm.functionIndex - moduleContext.importedFunctionOffsets.size();
callee = moduleContext.functionDefs[calleeIndex];
calleeType = module.types[module.functions.defs[calleeIndex].type.index];
}
// Pop the call arguments from the operand stack.
auto llvmArgs = (llvm::Value**)alloca(sizeof(llvm::Value*) * calleeType->parameters.size());
popMultiple(llvmArgs,calleeType->parameters.size());
//convert small constant sized memcpy host function calls to a load+store (plus small call to validate non-overlap rule)
if(isMemcpy) {
assert(calleeType->parameters.size() == 3);
if(llvm::ConstantInt* const_memcpy_sz = llvm::dyn_cast<llvm::ConstantInt>(llvmArgs[2]);
const_memcpy_sz &&
const_memcpy_sz->getZExtValue() >= minimum_const_memcpy_intrinsic_to_optimize &&
const_memcpy_sz->getZExtValue() <= maximum_const_memcpy_intrinsic_to_optimize) {
const unsigned sz_value = const_memcpy_sz->getZExtValue();
llvm::IntegerType* type_of_memcpy_width = llvm::Type::getIntNTy(context, sz_value*8);
llvm::Value* load_pointer = coerceByteIndexToPointer(llvmArgs[1],0,type_of_memcpy_width);
llvm::Value* store_pointer = coerceByteIndexToPointer(llvmArgs[0],0,type_of_memcpy_width);
irBuilder.CreateStore(irBuilder.CreateLoad(load_pointer), store_pointer, true);
emitRuntimeIntrinsic("eosvmoc_internal.check_memcpy_params",
FunctionType::get(ResultType::none,{ValueType::i32,ValueType::i32,ValueType::i32}),
{llvmArgs[0],llvmArgs[1],llvmArgs[2]});
push(llvmArgs[0]);
return;
}
}
// Call the function.
auto result = createCall(callee,llvm::ArrayRef<llvm::Value*>(llvmArgs,calleeType->parameters.size()));
if(isExit) {
irBuilder.CreateUnreachable();
enterUnreachable();
}
// Push the result on the operand stack.
if(calleeType->ret != ResultType::none) { push(result); }
}
void call_indirect(CallIndirectImm imm)
{
WAVM_ASSERT_THROW(imm.type.index < module.types.size());
auto calleeType = module.types[imm.type.index];
auto functionPointerType = asLLVMType(calleeType)->getPointerTo();
// Compile the function index.
auto tableElementIndex = pop();
// Compile the call arguments.
auto llvmArgs = (llvm::Value**)alloca(sizeof(llvm::Value*) * calleeType->parameters.size());
popMultiple(llvmArgs,calleeType->parameters.size());
// Zero extend the function index to the pointer size.
auto functionIndexZExt = irBuilder.CreateZExt(tableElementIndex, llvmI64Type);
// If the function index is larger than the function table size, trap.
emitConditionalTrapIntrinsic(
irBuilder.CreateICmpUGE(functionIndexZExt,moduleContext.defaultTableMaxElementIndex),
"eosvmoc_internal.indirect_call_oob",FunctionType::get(),{});
// Load the type for this table entry.
auto tablePointer = irBuilder.CreateInBoundsGEP(moduleContext.defaultTablePointer, {emitLiteral(0), emitLiteral(0)});
auto functionTypePointerPointer = irBuilder.CreateInBoundsGEP(tablePointer, {functionIndexZExt, emitLiteral((U32)0)});
auto functionTypePointer = irBuilder.CreateLoad(functionTypePointerPointer);
auto llvmCalleeType = emitLiteralPointer(calleeType,llvmI8PtrType);
// If the function type doesn't match, trap.
emitConditionalTrapIntrinsic(
irBuilder.CreateICmpNE(llvmCalleeType,functionTypePointer),
"eosvmoc_internal.indirect_call_mismatch",
FunctionType::get(),{}
);
//If the WASM only contains table elements to function definitions internal to the wasm, we can take a
// simple and approach
if(moduleContext.tableOnlyHasDefinedFuncs) {
auto functionPointerPointer = irBuilder.CreateInBoundsGEP(tablePointer, {functionIndexZExt, emitLiteral((U32)1)});
auto functionInfo = irBuilder.CreateLoad(functionPointerPointer); //offset of code
llvm::Value* running_code_start = irBuilder.CreateLoad(emitLiteralPointer((void*)OFFSET_OF_CONTROL_BLOCK_MEMBER(running_code_base), llvmI64Type->getPointerTo(256)));
llvm::Value* offset_from_start = irBuilder.CreateAdd(running_code_start, functionInfo);
llvm::Value* ptr_cast = irBuilder.CreateIntToPtr(offset_from_start, functionPointerType);
auto result = createCall(ptr_cast,llvm::ArrayRef<llvm::Value*>(llvmArgs,calleeType->parameters.size()));
// Push the result on the operand stack.
if(calleeType->ret != ResultType::none) { push(result); }
}
else {
auto functionPointerPointer = irBuilder.CreateInBoundsGEP(tablePointer, {functionIndexZExt, emitLiteral((U32)1)});
auto functionInfo = irBuilder.CreateLoad(functionPointerPointer); //offset of code
auto is_intrnsic = irBuilder.CreateICmpSLT(functionInfo, typedZeroConstants[(Uptr)ValueType::i64]);
llvm::BasicBlock* is_intrinsic_block = llvm::BasicBlock::Create(context, "isintrinsic", llvmFunction);
llvm::BasicBlock* is_code_offset_block = llvm::BasicBlock::Create(context, "isoffset");
llvm::BasicBlock* continuation_block = llvm::BasicBlock::Create(context, "cont");
irBuilder.CreateCondBr(is_intrnsic, is_intrinsic_block, is_code_offset_block, moduleContext.likelyFalseBranchWeights);
irBuilder.SetInsertPoint(is_intrinsic_block);
llvm::Value* intrinsic_start = emitLiteral((I64)OFFSET_OF_FIRST_INTRINSIC);
llvm::Value* intrinsic_offset = irBuilder.CreateAdd(intrinsic_start, functionInfo);
llvm::Value* intrinsic_ptr = irBuilder.CreateLoad(irBuilder.CreateIntToPtr(intrinsic_offset, llvmI64Type->getPointerTo(256)));
irBuilder.CreateBr(continuation_block);
llvmFunction->getBasicBlockList().push_back(is_code_offset_block);
irBuilder.SetInsertPoint(is_code_offset_block);
llvm::Value* running_code_start = irBuilder.CreateLoad(emitLiteralPointer((void*)OFFSET_OF_CONTROL_BLOCK_MEMBER(running_code_base), llvmI64Type->getPointerTo(256)));
llvm::Value* offset_from_start = irBuilder.CreateAdd(running_code_start, functionInfo);
irBuilder.CreateBr(continuation_block);
llvmFunction->getBasicBlockList().push_back(continuation_block);
irBuilder.SetInsertPoint(continuation_block);
llvm::PHINode* PN = irBuilder.CreatePHI(llvmI64Type, 2, "indirecttypephi");
PN->addIncoming(intrinsic_ptr, is_intrinsic_block);
PN->addIncoming(offset_from_start, is_code_offset_block);
llvm::Value* ptr_cast = irBuilder.CreateIntToPtr(PN, functionPointerType);
auto result = createCall(ptr_cast,llvm::ArrayRef<llvm::Value*>(llvmArgs,calleeType->parameters.size()));
// Push the result on the operand stack.
if(calleeType->ret != ResultType::none) { push(result); }
}
}
//
// Local/global operators
//
void get_local(GetOrSetVariableImm<false> imm)
{
WAVM_ASSERT_THROW(imm.variableIndex < localPointers.size());
push(irBuilder.CreateLoad(localPointers[imm.variableIndex]));
}
void set_local(GetOrSetVariableImm<false> imm)
{
WAVM_ASSERT_THROW(imm.variableIndex < localPointers.size());
auto value = irBuilder.CreateBitCast(pop(),localPointers[imm.variableIndex]->getType()->getPointerElementType());
irBuilder.CreateStore(value,localPointers[imm.variableIndex]);
}
llvm::Value* get_mutable_global_ptr(llvm::Value* global) {
if(global->getType()->isStructTy()) {
llvm::Value* globalsBasePtr = irBuilder.CreateExtractValue(global, 0);
return irBuilder.CreateInBoundsGEP(irBuilder.CreateLoad(globalsBasePtr), irBuilder.CreateExtractValue(global, 1));
} else if(global->getType()->isPointerTy()) {
return global;
} else {
return nullptr;
}
}
void tee_local(GetOrSetVariableImm<false> imm)
{
WAVM_ASSERT_THROW(imm.variableIndex < localPointers.size());
auto value = irBuilder.CreateBitCast(getTopValue(),localPointers[imm.variableIndex]->getType()->getPointerElementType());
irBuilder.CreateStore(value,get_mutable_global_ptr(localPointers[imm.variableIndex]));
}
void get_global(GetOrSetVariableImm<true> imm)
{
WAVM_ASSERT_THROW(imm.variableIndex < moduleContext.globals.size());
if(auto* p = get_mutable_global_ptr(moduleContext.globals[imm.variableIndex]))
push(irBuilder.CreateLoad(p));
else
push(moduleContext.globals[imm.variableIndex]);
}
void set_global(GetOrSetVariableImm<true> imm)
{
WAVM_ASSERT_THROW(imm.variableIndex < moduleContext.globals.size());
auto value = irBuilder.CreateBitCast(pop(),moduleContext.globals[imm.variableIndex]->getType()->getPointerElementType());
irBuilder.CreateStore(value,get_mutable_global_ptr(moduleContext.globals[imm.variableIndex]));
}
//
// Memory size operators
// These just call out to wavmIntrinsics.growMemory/currentMemory, passing a pointer to the default memory for the module.
//
void grow_memory(MemoryImm)
{
auto deltaNumPages = pop();
auto maxMemoryPages = emitLiteral((U32)moduleContext.module.memories.defs[0].type.size.max);
auto previousNumPages = emitRuntimeIntrinsic(
"eosvmoc_internal.grow_memory",
FunctionType::get(ResultType::i32,{ValueType::i32,ValueType::i32}),
{deltaNumPages,maxMemoryPages});
push(previousNumPages);
}
void current_memory(MemoryImm)
{
auto offset = emitLiteral((I32)OFFSET_OF_CONTROL_BLOCK_MEMBER(current_linear_memory_pages));
auto bytePointer = irBuilder.CreateInBoundsGEP(moduleContext.defaultMemoryBase, offset);
auto ptrTo = irBuilder.CreatePointerCast(bytePointer,llvmI32Type->getPointerTo(256));
auto load = irBuilder.CreateLoad(ptrTo);
push(load);
}
//
// Constant operators
//
#define EMIT_CONST(typeId,nativeType) void typeId##_const(LiteralImm<nativeType> imm) { push(emitLiteral(imm.value)); }
EMIT_CONST(i32,I32) EMIT_CONST(i64,I64)
EMIT_CONST(f32,F32) EMIT_CONST(f64,F64)
//
// Load/store operators
//
#define EMIT_LOAD_OP(valueTypeId,name,llvmMemoryType,naturalAlignmentLog2,conversionOp,alignmentParam) \
void valueTypeId##_##name(LoadOrStoreImm<naturalAlignmentLog2> imm) \
{ \
auto byteIndex = pop(); \
auto pointer = coerceByteIndexToPointer(byteIndex,imm.offset,llvmMemoryType); \
auto load = irBuilder.CreateLoad(pointer); \
load->setAlignment(alignmentParam); \
load->setVolatile(true); \
push(conversionOp(load,asLLVMType(ValueType::valueTypeId))); \
}
#define EMIT_STORE_OP(valueTypeId,name,llvmMemoryType,naturalAlignmentLog2,conversionOp,alignmentParam) \
void valueTypeId##_##name(LoadOrStoreImm<naturalAlignmentLog2> imm) \
{ \
auto value = pop(); \
auto byteIndex = pop(); \
auto pointer = coerceByteIndexToPointer(byteIndex,imm.offset,llvmMemoryType); \
auto memoryValue = conversionOp(value,llvmMemoryType); \
auto store = irBuilder.CreateStore(memoryValue,pointer); \
store->setVolatile(true); \
store->setAlignment(alignmentParam); \
}
llvm::Value* identityConversion(llvm::Value* value,llvm::Type* type) { return value; }
#if LLVM_VERSION_MAJOR < 10
#define LOAD_STORE_ALIGNMENT_PARAM 1
#elif LLVM_VERSION_MAJOR == 10
#define LOAD_STORE_ALIGNMENT_PARAM llvm::MaybeAlign(1)
#else
#define LOAD_STORE_ALIGNMENT_PARAM llvm::Align(1)
#endif
EMIT_LOAD_OP(i32,load8_s,llvmI8Type,0,irBuilder.CreateSExt,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(i32,load8_u,llvmI8Type,0,irBuilder.CreateZExt,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_LOAD_OP(i32,load16_s,llvmI16Type,1,irBuilder.CreateSExt,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(i32,load16_u,llvmI16Type,1,irBuilder.CreateZExt,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_LOAD_OP(i64,load8_s,llvmI8Type,0,irBuilder.CreateSExt,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(i64,load8_u,llvmI8Type,0,irBuilder.CreateZExt,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_LOAD_OP(i64,load16_s,llvmI16Type,1,irBuilder.CreateSExt,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(i64,load16_u,llvmI16Type,1,irBuilder.CreateZExt,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_LOAD_OP(i64,load32_s,llvmI32Type,2,irBuilder.CreateSExt,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(i64,load32_u,llvmI32Type,2,irBuilder.CreateZExt,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_LOAD_OP(i32,load,llvmI32Type,2,identityConversion,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(i64,load,llvmI64Type,3,identityConversion,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_LOAD_OP(f32,load,llvmF32Type,2,identityConversion,LOAD_STORE_ALIGNMENT_PARAM) EMIT_LOAD_OP(f64,load,llvmF64Type,3,identityConversion,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_STORE_OP(i32,store8,llvmI8Type,0,irBuilder.CreateTrunc,LOAD_STORE_ALIGNMENT_PARAM) EMIT_STORE_OP(i64,store8,llvmI8Type,0,irBuilder.CreateTrunc,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_STORE_OP(i32,store16,llvmI16Type,1,irBuilder.CreateTrunc,LOAD_STORE_ALIGNMENT_PARAM) EMIT_STORE_OP(i64,store16,llvmI16Type,1,irBuilder.CreateTrunc,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_STORE_OP(i32,store,llvmI32Type,2,irBuilder.CreateTrunc,LOAD_STORE_ALIGNMENT_PARAM) EMIT_STORE_OP(i64,store32,llvmI32Type,2,irBuilder.CreateTrunc,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_STORE_OP(i64,store,llvmI64Type,3,identityConversion,LOAD_STORE_ALIGNMENT_PARAM)
EMIT_STORE_OP(f32,store,llvmF32Type,2,identityConversion,LOAD_STORE_ALIGNMENT_PARAM) EMIT_STORE_OP(f64,store,llvmF64Type,3,identityConversion,LOAD_STORE_ALIGNMENT_PARAM)
//
// Numeric operator macros
//
#define EMIT_BINARY_OP(typeId,name,emitCode) void typeId##_##name(NoImm) \
{ \
const ValueType type = ValueType::typeId; SUPPRESS_UNUSED(type); \
auto right = pop(); \
auto left = pop(); \
push(emitCode); \
}
#define EMIT_INT_BINARY_OP(name,emitCode) EMIT_BINARY_OP(i32,name,emitCode) EMIT_BINARY_OP(i64,name,emitCode)
#define EMIT_FP_BINARY_OP(name,emitCode) EMIT_BINARY_OP(f32,name,emitCode) EMIT_BINARY_OP(f64,name,emitCode)
#define EMIT_UNARY_OP(typeId,name,emitCode) void typeId##_##name(NoImm) \
{ \
const ValueType type = ValueType::typeId; SUPPRESS_UNUSED(type); \
auto operand = pop(); \
push(emitCode); \
}
#define EMIT_INT_UNARY_OP(name,emitCode) EMIT_UNARY_OP(i32,name,emitCode) EMIT_UNARY_OP(i64,name,emitCode)
#define EMIT_FP_UNARY_OP(name,emitCode) EMIT_UNARY_OP(f32,name,emitCode) EMIT_UNARY_OP(f64,name,emitCode)
//
// Int operators
//
llvm::Value* emitSRem(ValueType type,llvm::Value* left,llvm::Value* right)
{
// Trap if the dividend is zero.
trapDivideByZero(type,right);
// LLVM's srem has undefined behavior where WebAssembly's rem_s defines that it should not trap if the corresponding