V8 API Reference, 7.2.502.16 (for Deno 0.2.4)
wasm-compiler.h
1 // Copyright 2015 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef V8_COMPILER_WASM_COMPILER_H_
6 #define V8_COMPILER_WASM_COMPILER_H_
7 
8 #include <memory>
9 
10 // Clients of this interface shouldn't depend on lots of compiler internals.
11 // Do not include anything from src/compiler here!
12 #include "src/runtime/runtime.h"
13 #include "src/wasm/function-body-decoder.h"
14 #include "src/wasm/function-compiler.h"
15 #include "src/wasm/wasm-module.h"
16 #include "src/wasm/wasm-opcodes.h"
17 #include "src/wasm/wasm-result.h"
18 #include "src/zone/zone.h"
19 
20 namespace v8 {
21 namespace internal {
22 struct AssemblerOptions;
23 
24 namespace compiler {
25 // Forward declarations for some compiler data structures.
26 class CallDescriptor;
27 class Graph;
28 class MachineGraph;
29 class Node;
30 class NodeOriginTable;
31 class Operator;
32 class SourcePositionTable;
33 class WasmDecorator;
34 enum class TrapId : uint32_t;
35 } // namespace compiler
36 
37 namespace wasm {
38 struct DecodeStruct;
39 // Expose {Node} and {Graph} opaquely as {wasm::TFNode} and {wasm::TFGraph}.
40 typedef compiler::Node TFNode;
41 typedef compiler::MachineGraph TFGraph;
42 class WasmCode;
43 struct WasmFeatures;
44 } // namespace wasm
45 
46 namespace compiler {
47 
49  public:
52 
53  bool BuildGraphForWasmFunction(wasm::CompilationEnv* env,
54  const wasm::FunctionBody& func_body,
55  wasm::WasmFeatures* detected,
56  double* decode_ms, MachineGraph* mcgraph,
57  NodeOriginTable* node_origins,
58  SourcePositionTable* source_positions);
59 
60  void ExecuteCompilation(wasm::CompilationEnv*, const wasm::FunctionBody&,
61  Counters*, wasm::WasmFeatures* detected);
62 
63  private:
64  wasm::WasmCompilationUnit* const wasm_unit_;
65 
66  DISALLOW_COPY_AND_ASSIGN(TurbofanWasmCompilationUnit);
67 };
68 
69 // Calls to WASM imports are handled in several different ways, depending
70 // on the type of the target function/callable and whether the signature
71 // matches the argument arity.
72 enum class WasmImportCallKind : uint8_t {
73  kLinkError, // static WASM->WASM type error
74  kRuntimeTypeError, // runtime WASM->JS type error
75  kWasmToWasm, // fast WASM->WASM call
76  kJSFunctionArityMatch, // fast WASM->JS call
77  kJSFunctionArityMatchSloppy, // fast WASM->JS call, sloppy receiver
78  kJSFunctionArityMismatch, // WASM->JS, needs adapter frame
79  kJSFunctionArityMismatchSloppy, // WASM->JS, needs adapter frame, sloppy
80  // Math functions imported from JavaScript that are intrinsified
81  kFirstMathIntrinsic,
82  kF64Acos = kFirstMathIntrinsic,
83  kF64Asin,
84  kF64Atan,
85  kF64Cos,
86  kF64Sin,
87  kF64Tan,
88  kF64Exp,
89  kF64Log,
90  kF64Atan2,
91  kF64Pow,
92  kF64Ceil,
93  kF64Floor,
94  kF64Sqrt,
95  kF64Min,
96  kF64Max,
97  kF64Abs,
98  kF32Min,
99  kF32Max,
100  kF32Abs,
101  kF32Ceil,
102  kF32Floor,
103  kF32Sqrt,
104  kF32ConvertF64,
105  kLastMathIntrinsic = kF32ConvertF64,
106  // For everything else, there's the call builtin.
107  kUseCallBuiltin
108 };
109 
110 WasmImportCallKind GetWasmImportCallKind(Handle<JSReceiver> callable,
111  wasm::FunctionSig* sig);
112 
113 // Compiles an import call wrapper, which allows WASM to call imports.
114 wasm::WasmCode* CompileWasmImportCallWrapper(Isolate*, wasm::NativeModule*,
115  WasmImportCallKind,
117  bool source_positions);
118 
119 // Creates a code object calling a wasm function with the given signature,
120 // callable from JS.
121 V8_EXPORT_PRIVATE MaybeHandle<Code> CompileJSToWasmWrapper(Isolate*,
123  bool is_import);
124 
125 // Compiles a stub that redirects a call to a wasm function to the wasm
126 // interpreter. It's ABI compatible with the compiled wasm function.
127 wasm::WasmCode* CompileWasmInterpreterEntry(Isolate*, wasm::NativeModule*,
128  uint32_t func_index,
130 
131 enum CWasmEntryParameters {
132  kCodeEntry,
133  kObjectRef,
134  kArgumentsBuffer,
135  // marker:
136  kNumParameters
137 };
138 
139 // Compiles a stub with JS linkage, taking parameters as described by
140 // {CWasmEntryParameters}. It loads the wasm parameters from the argument
141 // buffer and calls the wasm function given as first parameter.
142 MaybeHandle<Code> CompileCWasmEntry(Isolate* isolate, wasm::FunctionSig* sig);
143 
144 // Values from the instance object are cached between WASM-level function calls.
145 // This struct allows the SSA environment handling this cache to be defined
146 // and manipulated in wasm-compiler.{h,cc} instead of inside the WASM decoder.
147 // (Note that currently, the globals base is immutable, so not cached here.)
149  Node* mem_start;
150  Node* mem_size;
151  Node* mem_mask;
152 };
153 
154 // Abstracts details of building TurboFan graph nodes for wasm to separate
155 // the wasm decoder from the internal details of TurboFan.
157  public:
158  enum EnforceBoundsCheck : bool { // --
159  kNeedsBoundsCheck = true,
160  kCanOmitBoundsCheck = false
161  };
162  enum UseRetpoline : bool { // --
163  kRetpoline = true,
164  kNoRetpoline = false
165  };
166  enum ExtraCallableParam : bool { // --
167  kExtraCallableParam = true,
168  kNoExtraCallableParam = false
169  };
170 
172  wasm::FunctionSig* sig,
173  compiler::SourcePositionTable* spt = nullptr);
174 
175  Node** Buffer(size_t count) {
176  if (count > cur_bufsize_) {
177  size_t new_size = count + cur_bufsize_ + 5;
178  cur_buffer_ =
179  reinterpret_cast<Node**>(zone_->New(new_size * sizeof(Node*)));
180  cur_bufsize_ = new_size;
181  }
182  return cur_buffer_;
183  }
184 
185  //-----------------------------------------------------------------------
186  // Operations independent of {control} or {effect}.
187  //-----------------------------------------------------------------------
188  Node* Error();
189  Node* Start(unsigned params);
190  Node* Param(unsigned index);
191  Node* Loop(Node* entry);
192  Node* TerminateLoop(Node* effect, Node* control);
193  Node* TerminateThrow(Node* effect, Node* control);
194  Node* Merge(unsigned count, Node** controls);
195  Node* Phi(wasm::ValueType type, unsigned count, Node** vals, Node* control);
196  Node* CreateOrMergeIntoPhi(MachineRepresentation rep, Node* merge,
197  Node* tnode, Node* fnode);
198  Node* CreateOrMergeIntoEffectPhi(Node* merge, Node* tnode, Node* fnode);
199  Node* EffectPhi(unsigned count, Node** effects, Node* control);
200  Node* RefNull();
201  Node* Uint32Constant(uint32_t value);
202  Node* Int32Constant(int32_t value);
203  Node* Int64Constant(int64_t value);
204  Node* IntPtrConstant(intptr_t value);
205  Node* Float32Constant(float value);
206  Node* Float64Constant(double value);
207  Node* Binop(wasm::WasmOpcode opcode, Node* left, Node* right,
208  wasm::WasmCodePosition position = wasm::kNoCodePosition);
209  Node* Unop(wasm::WasmOpcode opcode, Node* input,
210  wasm::WasmCodePosition position = wasm::kNoCodePosition);
211  Node* MemoryGrow(Node* input);
212  Node* Throw(uint32_t exception_index, const wasm::WasmException* exception,
213  const Vector<Node*> values);
214  Node* Rethrow(Node* except_obj);
215  Node* ExceptionTagEqual(Node* caught_tag, Node* expected_tag);
216  Node* LoadExceptionTagFromTable(uint32_t exception_index);
217  Node* GetExceptionTag(Node* except_obj);
218  Node** GetExceptionValues(Node* except_obj,
219  const wasm::WasmException* exception);
220  bool IsPhiWithMerge(Node* phi, Node* merge);
221  bool ThrowsException(Node* node, Node** if_success, Node** if_exception);
222  void AppendToMerge(Node* merge, Node* from);
223  void AppendToPhi(Node* phi, Node* from);
224 
225  void StackCheck(wasm::WasmCodePosition position, Node** effect = nullptr,
226  Node** control = nullptr);
227 
228  void PatchInStackCheckIfNeeded();
229 
230  //-----------------------------------------------------------------------
231  // Operations that read and/or write {control} and {effect}.
232  //-----------------------------------------------------------------------
233  Node* BranchNoHint(Node* cond, Node** true_node, Node** false_node);
234  Node* BranchExpectTrue(Node* cond, Node** true_node, Node** false_node);
235  Node* BranchExpectFalse(Node* cond, Node** true_node, Node** false_node);
236 
237  Node* TrapIfTrue(wasm::TrapReason reason, Node* cond,
238  wasm::WasmCodePosition position);
239  Node* TrapIfFalse(wasm::TrapReason reason, Node* cond,
240  wasm::WasmCodePosition position);
241  Node* TrapIfEq32(wasm::TrapReason reason, Node* node, int32_t val,
242  wasm::WasmCodePosition position);
243  Node* ZeroCheck32(wasm::TrapReason reason, Node* node,
244  wasm::WasmCodePosition position);
245  Node* TrapIfEq64(wasm::TrapReason reason, Node* node, int64_t val,
246  wasm::WasmCodePosition position);
247  Node* ZeroCheck64(wasm::TrapReason reason, Node* node,
248  wasm::WasmCodePosition position);
249 
250  Node* Switch(unsigned count, Node* key);
251  Node* IfValue(int32_t value, Node* sw);
252  Node* IfDefault(Node* sw);
253  Node* Return(unsigned count, Node** nodes);
254  template <typename... Nodes>
255  Node* Return(Node* fst, Nodes*... more) {
256  Node* arr[] = {fst, more...};
257  return Return(arraysize(arr), arr);
258  }
259  Node* ReturnVoid();
260  Node* Unreachable(wasm::WasmCodePosition position);
261 
262  Node* CallDirect(uint32_t index, Node** args, Node*** rets,
263  wasm::WasmCodePosition position);
264  Node* CallIndirect(uint32_t index, Node** args, Node*** rets,
265  wasm::WasmCodePosition position);
266 
267  Node* Invert(Node* node);
268 
269  //-----------------------------------------------------------------------
270  // Operations that concern the linear memory.
271  //-----------------------------------------------------------------------
272  Node* CurrentMemoryPages();
273  Node* GetGlobal(uint32_t index);
274  Node* SetGlobal(uint32_t index, Node* val);
275  Node* TraceMemoryOperation(bool is_store, MachineRepresentation, Node* index,
277  Node* LoadMem(wasm::ValueType type, MachineType memtype, Node* index,
278  uint32_t offset, uint32_t alignment,
279  wasm::WasmCodePosition position);
280  Node* StoreMem(MachineRepresentation mem_rep, Node* index, uint32_t offset,
281  uint32_t alignment, Node* val, wasm::WasmCodePosition position,
282  wasm::ValueType type);
283  static void PrintDebugName(Node* node);
284 
285  void set_instance_node(Node* instance_node) {
286  this->instance_node_ = instance_node;
287  }
288 
289  Node* Control() {
290  DCHECK_NOT_NULL(*control_);
291  return *control_;
292  }
293  Node* Effect() {
294  DCHECK_NOT_NULL(*effect_);
295  return *effect_;
296  }
297  Node* SetControl(Node* node) {
298  *control_ = node;
299  return node;
300  }
301  Node* SetEffect(Node* node) {
302  *effect_ = node;
303  return node;
304  }
305 
306  void set_control_ptr(Node** control) { this->control_ = control; }
307 
308  void set_effect_ptr(Node** effect) { this->effect_ = effect; }
309 
310  void GetGlobalBaseAndOffset(MachineType mem_type, const wasm::WasmGlobal&,
311  Node** base_node, Node** offset_node);
312 
313  // Utilities to manipulate sets of instance cache nodes.
314  void InitInstanceCache(WasmInstanceCacheNodes* instance_cache);
315  void PrepareInstanceCacheForLoop(WasmInstanceCacheNodes* instance_cache,
316  Node* control);
317  void NewInstanceCacheMerge(WasmInstanceCacheNodes* to,
318  WasmInstanceCacheNodes* from, Node* merge);
319  void MergeInstanceCacheInto(WasmInstanceCacheNodes* to,
320  WasmInstanceCacheNodes* from, Node* merge);
321 
322  void set_instance_cache(WasmInstanceCacheNodes* instance_cache) {
323  this->instance_cache_ = instance_cache;
324  }
325 
326  wasm::FunctionSig* GetFunctionSignature() { return sig_; }
327 
328  void LowerInt64();
329 
330  void SimdScalarLoweringForTesting();
331 
332  void SetSourcePosition(Node* node, wasm::WasmCodePosition position);
333 
334  Node* S128Zero();
335  Node* S1x4Zero();
336  Node* S1x8Zero();
337  Node* S1x16Zero();
338 
339  Node* SimdOp(wasm::WasmOpcode opcode, Node* const* inputs);
340 
341  Node* SimdLaneOp(wasm::WasmOpcode opcode, uint8_t lane, Node* const* inputs);
342 
343  Node* SimdShiftOp(wasm::WasmOpcode opcode, uint8_t shift,
344  Node* const* inputs);
345 
346  Node* Simd8x16ShuffleOp(const uint8_t shuffle[16], Node* const* inputs);
347 
348  Node* AtomicOp(wasm::WasmOpcode opcode, Node* const* inputs,
349  uint32_t alignment, uint32_t offset,
350  wasm::WasmCodePosition position);
351 
352  bool has_simd() const { return has_simd_; }
353 
354  const wasm::WasmModule* module() { return env_ ? env_->module : nullptr; }
355 
356  wasm::UseTrapHandler use_trap_handler() const {
357  return env_ ? env_->use_trap_handler : wasm::kNoTrapHandler;
358  }
359 
360  MachineGraph* mcgraph() { return mcgraph_; }
361  Graph* graph();
362 
363  void AddBytecodePositionDecorator(NodeOriginTable* node_origins,
364  wasm::Decoder* decoder);
365 
366  void RemoveBytecodePositionDecorator();
367 
368  protected:
369  static const int kDefaultBufferSize = 16;
370 
371  Zone* const zone_;
372  MachineGraph* const mcgraph_;
373  wasm::CompilationEnv* const env_;
374 
375  Node** control_ = nullptr;
376  Node** effect_ = nullptr;
377  WasmInstanceCacheNodes* instance_cache_ = nullptr;
378 
379  SetOncePointer<Node> instance_node_;
380  SetOncePointer<Node> globals_start_;
381  SetOncePointer<Node> imported_mutable_globals_;
382  SetOncePointer<Node> stack_check_code_node_;
383  SetOncePointer<const Operator> stack_check_call_operator_;
384 
385  Node** cur_buffer_;
386  size_t cur_bufsize_;
387  Node* def_buffer_[kDefaultBufferSize];
388  bool has_simd_ = false;
389  bool needs_stack_check_ = false;
390  const bool untrusted_code_mitigations_ = true;
391 
392  wasm::FunctionSig* const sig_;
393 
394  compiler::WasmDecorator* decorator_ = nullptr;
395 
396  compiler::SourcePositionTable* const source_position_table_ = nullptr;
397 
398  Node* NoContextConstant();
399 
400  Node* MemBuffer(uint32_t offset);
401  // BoundsCheckMem receives a uint32 {index} node and returns a ptrsize index.
402  Node* BoundsCheckMem(uint8_t access_size, Node* index, uint32_t offset,
403  wasm::WasmCodePosition, EnforceBoundsCheck);
404  Node* CheckBoundsAndAlignment(uint8_t access_size, Node* index,
406  Node* Uint32ToUintptr(Node*);
407  const Operator* GetSafeLoadOperator(int offset, wasm::ValueType type);
408  const Operator* GetSafeStoreOperator(int offset, wasm::ValueType type);
409  Node* BuildChangeEndiannessStore(Node* node, MachineRepresentation rep,
410  wasm::ValueType wasmtype = wasm::kWasmStmt);
411  Node* BuildChangeEndiannessLoad(Node* node, MachineType type,
412  wasm::ValueType wasmtype = wasm::kWasmStmt);
413 
414  Node* MaskShiftCount32(Node* node);
415  Node* MaskShiftCount64(Node* node);
416 
417  template <typename... Args>
418  Node* BuildCCall(MachineSignature* sig, Node* function, Args... args);
419  Node* BuildWasmCall(wasm::FunctionSig* sig, Node** args, Node*** rets,
420  wasm::WasmCodePosition position, Node* instance_node,
421  UseRetpoline use_retpoline);
422  Node* BuildImportCall(wasm::FunctionSig* sig, Node** args, Node*** rets,
423  wasm::WasmCodePosition position, int func_index);
424  Node* BuildImportCall(wasm::FunctionSig* sig, Node** args, Node*** rets,
425  wasm::WasmCodePosition position, Node* func_index);
426 
427  Node* BuildF32CopySign(Node* left, Node* right);
428  Node* BuildF64CopySign(Node* left, Node* right);
429 
430  Node* BuildIntConvertFloat(Node* input, wasm::WasmCodePosition position,
431  wasm::WasmOpcode);
432  Node* BuildI32Ctz(Node* input);
433  Node* BuildI32Popcnt(Node* input);
434  Node* BuildI64Ctz(Node* input);
435  Node* BuildI64Popcnt(Node* input);
436  Node* BuildBitCountingCall(Node* input, ExternalReference ref,
437  MachineRepresentation input_type);
438 
439  Node* BuildCFuncInstruction(ExternalReference ref, MachineType type,
440  Node* input0, Node* input1 = nullptr);
441  Node* BuildF32Trunc(Node* input);
442  Node* BuildF32Floor(Node* input);
443  Node* BuildF32Ceil(Node* input);
444  Node* BuildF32NearestInt(Node* input);
445  Node* BuildF64Trunc(Node* input);
446  Node* BuildF64Floor(Node* input);
447  Node* BuildF64Ceil(Node* input);
448  Node* BuildF64NearestInt(Node* input);
449  Node* BuildI32Rol(Node* left, Node* right);
450  Node* BuildI64Rol(Node* left, Node* right);
451 
452  Node* BuildF64Acos(Node* input);
453  Node* BuildF64Asin(Node* input);
454  Node* BuildF64Pow(Node* left, Node* right);
455  Node* BuildF64Mod(Node* left, Node* right);
456 
457  Node* BuildIntToFloatConversionInstruction(
458  Node* input, ExternalReference ref,
459  MachineRepresentation parameter_representation,
460  const MachineType result_type);
461  Node* BuildF32SConvertI64(Node* input);
462  Node* BuildF32UConvertI64(Node* input);
463  Node* BuildF64SConvertI64(Node* input);
464  Node* BuildF64UConvertI64(Node* input);
465 
466  Node* BuildCcallConvertFloat(Node* input, wasm::WasmCodePosition position,
467  wasm::WasmOpcode opcode);
468 
469  Node* BuildI32DivS(Node* left, Node* right, wasm::WasmCodePosition position);
470  Node* BuildI32RemS(Node* left, Node* right, wasm::WasmCodePosition position);
471  Node* BuildI32DivU(Node* left, Node* right, wasm::WasmCodePosition position);
472  Node* BuildI32RemU(Node* left, Node* right, wasm::WasmCodePosition position);
473 
474  Node* BuildI64DivS(Node* left, Node* right, wasm::WasmCodePosition position);
475  Node* BuildI64RemS(Node* left, Node* right, wasm::WasmCodePosition position);
476  Node* BuildI64DivU(Node* left, Node* right, wasm::WasmCodePosition position);
477  Node* BuildI64RemU(Node* left, Node* right, wasm::WasmCodePosition position);
478  Node* BuildDiv64Call(Node* left, Node* right, ExternalReference ref,
479  MachineType result_type, wasm::TrapReason trap_zero,
480  wasm::WasmCodePosition position);
481 
482  Node* BuildChangeInt32ToIntPtr(Node* value);
483  Node* BuildChangeInt32ToSmi(Node* value);
484  Node* BuildChangeUint31ToSmi(Node* value);
485  Node* BuildSmiShiftBitsConstant();
486  Node* BuildChangeSmiToInt32(Node* value);
487 
488  // Asm.js specific functionality.
489  Node* BuildI32AsmjsSConvertF32(Node* input);
490  Node* BuildI32AsmjsSConvertF64(Node* input);
491  Node* BuildI32AsmjsUConvertF32(Node* input);
492  Node* BuildI32AsmjsUConvertF64(Node* input);
493  Node* BuildI32AsmjsDivS(Node* left, Node* right);
494  Node* BuildI32AsmjsRemS(Node* left, Node* right);
495  Node* BuildI32AsmjsDivU(Node* left, Node* right);
496  Node* BuildI32AsmjsRemU(Node* left, Node* right);
497  Node* BuildAsmjsLoadMem(MachineType type, Node* index);
498  Node* BuildAsmjsStoreMem(MachineType type, Node* index, Node* val);
499 
500  uint32_t GetExceptionEncodedSize(const wasm::WasmException* exception) const;
501  void BuildEncodeException32BitValue(Node* values_array, uint32_t* index,
502  Node* value);
503  Node* BuildDecodeException32BitValue(Node* values_array, uint32_t* index);
504  Node* BuildDecodeException64BitValue(Node* values_array, uint32_t* index);
505 
506  Node** Realloc(Node* const* buffer, size_t old_count, size_t new_count) {
507  Node** buf = Buffer(new_count);
508  if (buf != buffer) memcpy(buf, buffer, old_count * sizeof(Node*));
509  return buf;
510  }
511 
512  Node* BuildLoadBuiltinFromInstance(int builtin_index);
513 
514  //-----------------------------------------------------------------------
515  // Operations involving the CEntry, a dependency we want to remove
516  // to get off the GC heap.
517  //-----------------------------------------------------------------------
518  Node* BuildCallToRuntime(Runtime::FunctionId f, Node** parameters,
519  int parameter_count);
520 
521  Node* BuildCallToRuntimeWithContext(Runtime::FunctionId f, Node* js_context,
522  Node** parameters, int parameter_count);
523  TrapId GetTrapIdForTrap(wasm::TrapReason reason);
524 };
525 
526 V8_EXPORT_PRIVATE CallDescriptor* GetWasmCallDescriptor(
527  Zone* zone, wasm::FunctionSig* signature,
528  WasmGraphBuilder::UseRetpoline use_retpoline =
529  WasmGraphBuilder::kNoRetpoline,
530  WasmGraphBuilder::ExtraCallableParam callable_param =
531  WasmGraphBuilder::kNoExtraCallableParam);
532 
533 V8_EXPORT_PRIVATE CallDescriptor* GetI32WasmCallDescriptor(
534  Zone* zone, CallDescriptor* call_descriptor);
535 
536 V8_EXPORT_PRIVATE CallDescriptor* GetI32WasmCallDescriptorForSimd(
537  Zone* zone, CallDescriptor* call_descriptor);
538 
539 AssemblerOptions WasmAssemblerOptions();
540 
541 } // namespace compiler
542 } // namespace internal
543 } // namespace v8
544 
545 #endif // V8_COMPILER_WASM_COMPILER_H_
Definition: libplatform.h:13