1/*
2 * Copyright (C) 2013-2018 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#pragma once
27
28#if ENABLE(DFG_JIT)
29
30#include "DFGGraph.h"
31
32namespace JSC { namespace DFG {
33
34template<typename AbstractStateType>
35class SafeToExecuteEdge {
36public:
37 SafeToExecuteEdge(AbstractStateType& state)
38 : m_state(state)
39 {
40 }
41
42 void operator()(Node*, Edge edge)
43 {
44 m_maySeeEmptyChild |= !!(m_state.forNode(edge).m_type & SpecEmpty);
45
46 switch (edge.useKind()) {
47 case UntypedUse:
48 case Int32Use:
49 case DoubleRepUse:
50 case DoubleRepRealUse:
51 case Int52RepUse:
52 case NumberUse:
53 case RealNumberUse:
54 case BooleanUse:
55 case CellUse:
56 case CellOrOtherUse:
57 case ObjectUse:
58 case ArrayUse:
59 case FunctionUse:
60 case FinalObjectUse:
61 case RegExpObjectUse:
62 case ProxyObjectUse:
63 case DerivedArrayUse:
64 case MapObjectUse:
65 case SetObjectUse:
66 case WeakMapObjectUse:
67 case WeakSetObjectUse:
68 case DataViewObjectUse:
69 case ObjectOrOtherUse:
70 case StringIdentUse:
71 case StringUse:
72 case StringOrOtherUse:
73 case SymbolUse:
74 case BigIntUse:
75 case StringObjectUse:
76 case StringOrStringObjectUse:
77 case NotStringVarUse:
78 case NotSymbolUse:
79 case NotCellUse:
80 case OtherUse:
81 case MiscUse:
82 case AnyIntUse:
83 case DoubleRepAnyIntUse:
84 return;
85
86 case KnownInt32Use:
87 if (m_state.forNode(edge).m_type & ~SpecInt32Only)
88 m_result = false;
89 return;
90
91 case KnownBooleanUse:
92 if (m_state.forNode(edge).m_type & ~SpecBoolean)
93 m_result = false;
94 return;
95
96 case KnownCellUse:
97 if (m_state.forNode(edge).m_type & ~SpecCell)
98 m_result = false;
99 return;
100
101 case KnownStringUse:
102 if (m_state.forNode(edge).m_type & ~SpecString)
103 m_result = false;
104 return;
105
106 case KnownPrimitiveUse:
107 if (m_state.forNode(edge).m_type & ~(SpecHeapTop & ~SpecObject))
108 m_result = false;
109 return;
110
111 case KnownOtherUse:
112 if (m_state.forNode(edge).m_type & ~SpecOther)
113 m_result = false;
114 return;
115
116 case LastUseKind:
117 RELEASE_ASSERT_NOT_REACHED();
118 break;
119 }
120 RELEASE_ASSERT_NOT_REACHED();
121 }
122
123 bool result() const { return m_result; }
124 bool maySeeEmptyChild() const { return m_maySeeEmptyChild; }
125private:
126 AbstractStateType& m_state;
127 bool m_result { true };
128 bool m_maySeeEmptyChild { false };
129};
130
131// Determines if it's safe to execute a node within the given abstract state. This may
132// return false conservatively. If it returns true, then you can hoist the given node
133// up to the given point and expect that it will not crash. It also guarantees that the
134// node will not produce a malformed JSValue or object pointer when executed in the
135// given state. But this doesn't guarantee that the node will produce the result you
136// wanted. For example, you may have a GetByOffset from a prototype that only makes
137// semantic sense if you've also checked that some nearer prototype doesn't also have
138// a property of the same name. This could still return true even if that check hadn't
139// been performed in the given abstract state. That's fine though: the load can still
140// safely execute before that check, so long as that check continues to guard any
141// user-observable things done to the loaded value.
142template<typename AbstractStateType>
143bool safeToExecute(AbstractStateType& state, Graph& graph, Node* node, bool ignoreEmptyChildren = false)
144{
145 SafeToExecuteEdge<AbstractStateType> safeToExecuteEdge(state);
146 DFG_NODE_DO_TO_CHILDREN(graph, node, safeToExecuteEdge);
147 if (!safeToExecuteEdge.result())
148 return false;
149
150 if (!ignoreEmptyChildren && safeToExecuteEdge.maySeeEmptyChild()) {
151 // We conservatively assume if the empty value flows into a node,
152 // it might not be able to handle it (e.g, crash). In general, the bytecode generator
153 // emits code in such a way that most node types don't need to worry about the empty value
154 // because they will never see it. However, code motion has to consider the empty
155 // value so it does not insert/move nodes to a place where they will crash. E.g, the
156 // type check hoisting phase needs to insert CheckStructureOrEmpty instead of CheckStructure
157 // for hoisted structure checks because it can not guarantee that a particular local is not
158 // the empty value.
159 switch (node->op()) {
160 case CheckNotEmpty:
161 case CheckStructureOrEmpty:
162 break;
163 default:
164 return false;
165 }
166 }
167
168 // NOTE: This tends to lie when it comes to effectful nodes, because it knows that they aren't going to
169 // get hoisted anyway.
170
171 switch (node->op()) {
172 case JSConstant:
173 case DoubleConstant:
174 case Int52Constant:
175 case LazyJSConstant:
176 case Identity:
177 case IdentityWithProfile:
178 case ToThis:
179 case CreateThis:
180 case ObjectCreate:
181 case ObjectKeys:
182 case GetCallee:
183 case SetCallee:
184 case GetArgumentCountIncludingThis:
185 case SetArgumentCountIncludingThis:
186 case GetRestLength:
187 case GetLocal:
188 case SetLocal:
189 case PutStack:
190 case KillStack:
191 case GetStack:
192 case MovHint:
193 case ZombieHint:
194 case ExitOK:
195 case Phantom:
196 case Upsilon:
197 case Phi:
198 case Flush:
199 case PhantomLocal:
200 case SetArgumentDefinitely:
201 case SetArgumentMaybe:
202 case ArithBitNot:
203 case ArithBitAnd:
204 case ArithBitOr:
205 case ArithBitXor:
206 case BitLShift:
207 case BitRShift:
208 case BitURShift:
209 case ValueToInt32:
210 case UInt32ToNumber:
211 case DoubleAsInt32:
212 case ArithAdd:
213 case ArithClz32:
214 case ArithSub:
215 case ArithNegate:
216 case ArithMul:
217 case ArithIMul:
218 case ArithDiv:
219 case ArithMod:
220 case ArithAbs:
221 case ArithMin:
222 case ArithMax:
223 case ArithPow:
224 case ArithRandom:
225 case ArithSqrt:
226 case ArithFRound:
227 case ArithRound:
228 case ArithFloor:
229 case ArithCeil:
230 case ArithTrunc:
231 case ArithUnary:
232 case ValueBitAnd:
233 case ValueBitXor:
234 case ValueBitOr:
235 case ValueBitNot:
236 case ValueNegate:
237 case ValueAdd:
238 case ValueSub:
239 case ValueMul:
240 case ValueDiv:
241 case ValueMod:
242 case TryGetById:
243 case DeleteById:
244 case DeleteByVal:
245 case GetById:
246 case GetByIdWithThis:
247 case GetByValWithThis:
248 case GetByIdFlush:
249 case GetByIdDirect:
250 case GetByIdDirectFlush:
251 case PutById:
252 case PutByIdFlush:
253 case PutByIdWithThis:
254 case PutByValWithThis:
255 case PutByIdDirect:
256 case PutGetterById:
257 case PutSetterById:
258 case PutGetterSetterById:
259 case PutGetterByVal:
260 case PutSetterByVal:
261 case DefineDataProperty:
262 case DefineAccessorProperty:
263 case CheckStructure:
264 case CheckStructureOrEmpty:
265 case GetExecutable:
266 case GetButterfly:
267 case CallDOMGetter:
268 case CallDOM:
269 case CheckSubClass:
270 case CheckArray:
271 case Arrayify:
272 case ArrayifyToStructure:
273 case GetScope:
274 case SkipScope:
275 case GetGlobalObject:
276 case GetGlobalThis:
277 case GetClosureVar:
278 case PutClosureVar:
279 case GetGlobalVar:
280 case GetGlobalLexicalVariable:
281 case PutGlobalVariable:
282 case CheckCell:
283 case CheckBadCell:
284 case CheckNotEmpty:
285 case AssertNotEmpty:
286 case CheckStringIdent:
287 case RegExpExec:
288 case RegExpExecNonGlobalOrSticky:
289 case RegExpTest:
290 case RegExpMatchFast:
291 case RegExpMatchFastGlobal:
292 case CompareLess:
293 case CompareLessEq:
294 case CompareGreater:
295 case CompareGreaterEq:
296 case CompareBelow:
297 case CompareBelowEq:
298 case CompareEq:
299 case CompareStrictEq:
300 case CompareEqPtr:
301 case SameValue:
302 case Call:
303 case DirectCall:
304 case TailCallInlinedCaller:
305 case DirectTailCallInlinedCaller:
306 case Construct:
307 case DirectConstruct:
308 case CallVarargs:
309 case CallEval:
310 case TailCallVarargsInlinedCaller:
311 case TailCallForwardVarargsInlinedCaller:
312 case ConstructVarargs:
313 case LoadVarargs:
314 case CallForwardVarargs:
315 case ConstructForwardVarargs:
316 case NewObject:
317 case NewArray:
318 case NewArrayWithSize:
319 case NewArrayBuffer:
320 case NewArrayWithSpread:
321 case Spread:
322 case NewRegexp:
323 case NewSymbol:
324 case ProfileType:
325 case ProfileControlFlow:
326 case CheckTypeInfoFlags:
327 case ParseInt:
328 case OverridesHasInstance:
329 case InstanceOf:
330 case InstanceOfCustom:
331 case IsEmpty:
332 case IsUndefined:
333 case IsUndefinedOrNull:
334 case IsBoolean:
335 case IsNumber:
336 case NumberIsInteger:
337 case IsObject:
338 case IsObjectOrNull:
339 case IsFunction:
340 case IsCellWithType:
341 case IsTypedArrayView:
342 case TypeOf:
343 case LogicalNot:
344 case CallObjectConstructor:
345 case ToPrimitive:
346 case ToString:
347 case ToNumber:
348 case ToObject:
349 case NumberToStringWithRadix:
350 case NumberToStringWithValidRadixConstant:
351 case SetFunctionName:
352 case StrCat:
353 case CallStringConstructor:
354 case NewStringObject:
355 case MakeRope:
356 case InByVal:
357 case InById:
358 case HasOwnProperty:
359 case PushWithScope:
360 case CreateActivation:
361 case CreateDirectArguments:
362 case CreateScopedArguments:
363 case CreateClonedArguments:
364 case GetFromArguments:
365 case GetArgument:
366 case PutToArguments:
367 case NewFunction:
368 case NewGeneratorFunction:
369 case NewAsyncGeneratorFunction:
370 case NewAsyncFunction:
371 case Jump:
372 case Branch:
373 case Switch:
374 case EntrySwitch:
375 case Return:
376 case TailCall:
377 case DirectTailCall:
378 case TailCallVarargs:
379 case TailCallForwardVarargs:
380 case Throw:
381 case ThrowStaticError:
382 case CountExecution:
383 case SuperSamplerBegin:
384 case SuperSamplerEnd:
385 case ForceOSRExit:
386 case CPUIntrinsic:
387 case CheckTraps:
388 case LogShadowChickenPrologue:
389 case LogShadowChickenTail:
390 case StringFromCharCode:
391 case NewTypedArray:
392 case Unreachable:
393 case ExtractOSREntryLocal:
394 case ExtractCatchLocal:
395 case ClearCatchLocals:
396 case CheckTierUpInLoop:
397 case CheckTierUpAtReturn:
398 case CheckTierUpAndOSREnter:
399 case LoopHint:
400 case InvalidationPoint:
401 case NotifyWrite:
402 case CheckInBounds:
403 case ConstantStoragePointer:
404 case Check:
405 case CheckVarargs:
406 case MultiPutByOffset:
407 case ValueRep:
408 case DoubleRep:
409 case Int52Rep:
410 case BooleanToNumber:
411 case FiatInt52:
412 case GetGetter:
413 case GetSetter:
414 case GetEnumerableLength:
415 case HasGenericProperty:
416 case HasStructureProperty:
417 case HasIndexedProperty:
418 case GetDirectPname:
419 case GetPropertyEnumerator:
420 case GetEnumeratorStructurePname:
421 case GetEnumeratorGenericPname:
422 case ToIndexString:
423 case PhantomNewObject:
424 case PhantomNewFunction:
425 case PhantomNewGeneratorFunction:
426 case PhantomNewAsyncGeneratorFunction:
427 case PhantomNewAsyncFunction:
428 case PhantomCreateActivation:
429 case PhantomNewRegexp:
430 case PutHint:
431 case CheckStructureImmediate:
432 case MaterializeNewObject:
433 case MaterializeCreateActivation:
434 case PhantomDirectArguments:
435 case PhantomCreateRest:
436 case PhantomSpread:
437 case PhantomNewArrayWithSpread:
438 case PhantomNewArrayBuffer:
439 case PhantomClonedArguments:
440 case GetMyArgumentByVal:
441 case GetMyArgumentByValOutOfBounds:
442 case ForwardVarargs:
443 case CreateRest:
444 case GetPrototypeOf:
445 case StringReplace:
446 case StringReplaceRegExp:
447 case GetRegExpObjectLastIndex:
448 case SetRegExpObjectLastIndex:
449 case RecordRegExpCachedResult:
450 case GetDynamicVar:
451 case PutDynamicVar:
452 case ResolveScopeForHoistingFuncDeclInEval:
453 case ResolveScope:
454 case MapHash:
455 case NormalizeMapKey:
456 case StringValueOf:
457 case StringSlice:
458 case ToLowerCase:
459 case GetMapBucket:
460 case GetMapBucketHead:
461 case GetMapBucketNext:
462 case LoadKeyFromMapBucket:
463 case LoadValueFromMapBucket:
464 case ExtractValueFromWeakMapGet:
465 case WeakMapGet:
466 case WeakSetAdd:
467 case WeakMapSet:
468 case AtomicsAdd:
469 case AtomicsAnd:
470 case AtomicsCompareExchange:
471 case AtomicsExchange:
472 case AtomicsLoad:
473 case AtomicsOr:
474 case AtomicsStore:
475 case AtomicsSub:
476 case AtomicsXor:
477 case AtomicsIsLockFree:
478 case InitializeEntrypointArguments:
479 case MatchStructure:
480 case DataViewGetInt:
481 case DataViewGetFloat:
482 return true;
483
484 case ArraySlice:
485 case ArrayIndexOf: {
486 // You could plausibly move this code around as long as you proved the
487 // incoming array base structure is an original array at the hoisted location.
488 // Instead of doing that extra work, we just conservatively return false.
489 return false;
490 }
491
492 case BottomValue:
493 // If in doubt, assume that this isn't safe to execute, just because we have no way of
494 // compiling this node.
495 return false;
496
497 case StoreBarrier:
498 case FencedStoreBarrier:
499 case PutStructure:
500 case NukeStructureAndSetButterfly:
501 // We conservatively assume that these cannot be put anywhere, which forces the compiler to
502 // keep them exactly where they were. This is sort of overkill since the clobberize effects
503 // already force these things to be ordered precisely. I'm just not confident enough in my
504 // effect based memory model to rely solely on that right now.
505 return false;
506
507 case FilterCallLinkStatus:
508 case FilterGetByIdStatus:
509 case FilterPutByIdStatus:
510 case FilterInByIdStatus:
511 // We don't want these to be moved anywhere other than where we put them, since we want them
512 // to capture "profiling" at the point in control flow here the user put them.
513 return false;
514
515 case GetByVal:
516 case GetIndexedPropertyStorage:
517 case GetArrayLength:
518 case GetVectorLength:
519 case ArrayPop:
520 case StringCharAt:
521 case StringCharCodeAt:
522 return node->arrayMode().alreadyChecked(graph, node, state.forNode(graph.child(node, 0)));
523
524 case ArrayPush:
525 return node->arrayMode().alreadyChecked(graph, node, state.forNode(graph.varArgChild(node, 1)));
526
527 case GetTypedArrayByteOffset:
528 return !(state.forNode(node->child1()).m_type & ~(SpecTypedArrayView));
529
530 case PutByValDirect:
531 case PutByVal:
532 case PutByValAlias:
533 return node->arrayMode().modeForPut().alreadyChecked(
534 graph, node, state.forNode(graph.varArgChild(node, 0)));
535
536 case AllocatePropertyStorage:
537 case ReallocatePropertyStorage:
538 return state.forNode(node->child1()).m_structure.isSubsetOf(
539 RegisteredStructureSet(node->transition()->previous));
540
541 case GetByOffset:
542 case GetGetterSetterByOffset:
543 case PutByOffset: {
544 StorageAccessData& data = node->storageAccessData();
545 PropertyOffset offset = data.offset;
546 // Graph::isSafeToLoad() is all about proofs derived from PropertyConditions. Those don't
547 // know anything about inferred types. But if we have a proof derived from watching a
548 // structure that has a type proof, then the next case below will deal with it.
549 if (state.structureClobberState() == StructuresAreWatched) {
550 if (JSObject* knownBase = node->child2()->dynamicCastConstant<JSObject*>(graph.m_vm)) {
551 if (graph.isSafeToLoad(knownBase, offset))
552 return true;
553 }
554 }
555
556 StructureAbstractValue& value = state.forNode(node->child2()).m_structure;
557 if (value.isInfinite())
558 return false;
559 for (unsigned i = value.size(); i--;) {
560 Structure* thisStructure = value[i].get();
561 if (!thisStructure->isValidOffset(offset))
562 return false;
563 }
564 return true;
565 }
566
567 case MultiGetByOffset: {
568 // We can't always guarantee that the MultiGetByOffset is safe to execute if it
569 // contains loads from prototypes. If the load requires a check in IR, which is rare, then
570 // we currently claim that we don't know if it's safe to execute because finding that
571 // check in the abstract state would be hard. If the load requires watchpoints, we just
572 // check if we're not in a clobbered state (i.e. in between a side effect and an
573 // invalidation point).
574 for (const MultiGetByOffsetCase& getCase : node->multiGetByOffsetData().cases) {
575 GetByOffsetMethod method = getCase.method();
576 switch (method.kind()) {
577 case GetByOffsetMethod::Invalid:
578 RELEASE_ASSERT_NOT_REACHED();
579 break;
580 case GetByOffsetMethod::Constant: // OK because constants are always safe to execute.
581 case GetByOffsetMethod::Load: // OK because the MultiGetByOffset has its own checks for loading from self.
582 break;
583 case GetByOffsetMethod::LoadFromPrototype:
584 // Only OK if the state isn't clobbered. That's almost always the case.
585 if (state.structureClobberState() != StructuresAreWatched)
586 return false;
587 if (!graph.isSafeToLoad(method.prototype()->cast<JSObject*>(), method.offset()))
588 return false;
589 break;
590 }
591 }
592 return true;
593 }
594
595 case DataViewSet:
596 return false;
597
598 case SetAdd:
599 case MapSet:
600 return false;
601
602 case LastNodeType:
603 RELEASE_ASSERT_NOT_REACHED();
604 return false;
605 }
606
607 RELEASE_ASSERT_NOT_REACHED();
608 return false;
609}
610
611} } // namespace JSC::DFG
612
613#endif // ENABLE(DFG_JIT)
614