Debian Codegraph @

js/src/jit/RangeAnalysis.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "jit/RangeAnalysis.h"
8
9 #include "mozilla/MathAlgorithms.h"
10
11 #include <algorithm>
12
13 #include "jsmath.h"
14
15 #include "jit/CompileInfo.h"
16 #include "jit/IonAnalysis.h"
17 #include "jit/JitSpewer.h"
18 #include "jit/MIR-wasm.h"
19 #include "jit/MIR.h"
20 #include "jit/MIRGenerator.h"
21 #include "jit/MIRGraph.h"
22 #include "js/Conversions.h"
23 #include "js/ScalarType.h" // js::Scalar::Type
24 #include "util/CheckedArithmetic.h"
25 #include "util/Unicode.h"
26 #include "vm/ArgumentsObject.h"
27 #include "vm/Float16.h"
28 #include "vm/TypedArrayObject.h"
29 #include "vm/Uint8Clamped.h"
30
31 #include "vm/BytecodeUtil-inl.h"
32
33 using namespace js;
34 using namespace js::jit;
35
36 using JS::GenericNaN;
37 using JS::ToInt32;
38 using mozilla::Abs;
39 using mozilla::CountLeadingZeroes32;
40 using mozilla::ExponentComponent;
41 using mozilla::FloorLog2;
42 using mozilla::IsNegativeZero;
43 using mozilla::NegativeInfinity;
44 using mozilla::NumberEqualsInt32;
45 using mozilla::PositiveInfinity;
46
47 // [SMDOC] IonMonkey Range Analysis
48 //
49 // This algorithm is based on the paper "Eliminating Range Checks Using
50 // Static Single Assignment Form" by Gough and Klaren.
51 //
52 // We associate a range object with each SSA name, and the ranges are consulted
53 // in order to determine whether overflow is possible for arithmetic
54 // computations.
55 //
56 // An important source of range information that requires care to take
57 // advantage of is conditional control flow. Consider the code below:
58 //
59 // if (x < 0) {
60 // y = x + 2000000000;
61 // } else {
62 // if (x < 1000000000) {
63 // y = x * 2;
64 // } else {
65 // y = x - 3000000000;
66 // }
67 // }
68 //
69 // The arithmetic operations in this code cannot overflow, but it is not
70 // sufficient to simply associate each name with a range, since the information
71 // differs between basic blocks. The traditional dataflow approach would be
72 // associate ranges with (name, basic block) pairs. This solution is not
73 // satisfying, since we lose the benefit of SSA form: in SSA form, each
74 // definition has a unique name, so there is no need to track information about
75 // the control flow of the program.
76 //
77 // The approach used here is to add a new form of pseudo operation called a
78 // beta node, which associates range information with a value. These beta
79 // instructions take one argument and additionally have an auxiliary constant
80 // range associated with them. Operationally, beta nodes are just copies, but
81 // the invariant expressed by beta node copies is that the output will fall
82 // inside the range given by the beta node. Gough and Klaeren refer to SSA
83 // extended with these beta nodes as XSA form. The following shows the example
84 // code transformed into XSA form:
85 //
86 // if (x < 0) {
87 // x1 = Beta(x, [INT_MIN, -1]);
88 // y1 = x1 + 2000000000;
89 // } else {
90 // x2 = Beta(x, [0, INT_MAX]);
91 // if (x2 < 1000000000) {
92 // x3 = Beta(x2, [INT_MIN, 999999999]);
93 // y2 = x3*2;
94 // } else {
95 // x4 = Beta(x2, [1000000000, INT_MAX]);
96 // y3 = x4 - 3000000000;
97 // }
98 // y4 = Phi(y2, y3);
99 // }
100 // y = Phi(y1, y4);
101 //
102 // We insert beta nodes for the purposes of range analysis (they might also be
103 // usefully used for other forms of bounds check elimination) and remove them
104 // after range analysis is performed. The remaining compiler phases do not ever
105 // encounter beta nodes.
106
107 static bool IsDominatedUse(const MBasicBlock* block, const MUse* use) {
108 MNode* n = use->consumer();
109 bool isPhi = n->isDefinition() && n->toDefinition()->isPhi();
110
111 if (isPhi) {
112 MPhi* phi = n->toDefinition()->toPhi();
113 return block->dominates(phi->block()->getPredecessor(phi->indexOf(use)));
114 }
115
116 return block->dominates(n->block());
117 }
118
119 static inline void SpewRange(const MDefinition* def) {
120 #ifdef JS_JITSPEW
121 if (JitSpewEnabled(JitSpew_Range) && def->type() != MIRType::None &&
122 def->range()) {
123 JitSpewHeader(JitSpew_Range);
124 Fprinter& out = JitSpewPrinter();
125 out.printf(" ");
126 def->printName(out);
127 out.printf(" has range ");
128 def->range()->dump(out);
129 out.printf("\n");
130 }
131 #endif
132 }
133
134 #ifdef JS_JITSPEW
135 static const char* TruncateKindString(TruncateKind kind) {
136 switch (kind) {
137 case TruncateKind::NoTruncate:
138 return "NoTruncate";
139 case TruncateKind::TruncateAfterBailouts:
140 return "TruncateAfterBailouts";
141 case TruncateKind::IndirectTruncate:
142 return "IndirectTruncate";
143 case TruncateKind::Truncate:
144 return "Truncate";
145 default:
146 MOZ_CRASH("Unknown truncate kind.");
147 }
148 }
149
150 static inline void SpewTruncate(const MDefinition* def, TruncateKind kind,
151 bool shouldClone) {
152 if (JitSpewEnabled(JitSpew_Range)) {
153 JitSpewHeader(JitSpew_Range);
154 Fprinter& out = JitSpewPrinter();
155 out.printf(" ");
156 out.printf("truncating ");
157 def->printName(out);
158 out.printf(" (kind: %s, clone: %d)\n", TruncateKindString(kind),
159 shouldClone);
160 }
161 }
162 #else
163 static inline void SpewTruncate(MDefinition* def, TruncateKind kind,
164 bool shouldClone) {}
165 #endif
166
167 TempAllocator& RangeAnalysis::alloc() const { return graph_.alloc(); }
168
169 static void ReplaceDominatedUsesWith(const MDefinition* orig, MDefinition* dom,
170 const MBasicBlock* block) {
171 for (MUseIterator i(orig->usesBegin()); i != orig->usesEnd();) {
172 MUse* use = *i++;
173 if (use->consumer() != dom && IsDominatedUse(block, use)) {
174 use->replaceProducer(dom);
175 }
176 }
177 }
178
179 bool RangeAnalysis::addBetaNodes() {
180 JitSpew(JitSpew_Range, "Adding beta nodes");
181
182 for (PostorderIterator i(graph_.poBegin()); i != graph_.poEnd(); i++) {
183 if (mir->shouldCancel("RangeAnalysis addBetaNodes")) {
184 return false;
185 }
186
187 MBasicBlock* block = *i;
188 JitSpew(JitSpew_Range, "Looking at block %u", block->id());
189
190 BranchDirection branch_dir;
191 MTest* test = block->immediateDominatorBranch(&branch_dir);
192
193 if (!test || !test->getOperand(0)->isCompare()) {
194 continue;
195 }
196
197 MCompare* compare = test->getOperand(0)->toCompare();
198
199 if (!compare->isNumericComparison()) {
200 continue;
201 }
202
203 // TODO: support unsigned comparisons
204 if (compare->compareType() == MCompare::Compare_UInt32) {
205 continue;
206 }
207
208 // isNumericComparison should return false for (U)IntPtr.
209 MOZ_ASSERT(compare->compareType() != MCompare::Compare_IntPtr &&
210 compare->compareType() != MCompare::Compare_UIntPtr);
211
212 MDefinition* left = compare->getOperand(0);
213 MDefinition* right = compare->getOperand(1);
214 double bound;
215 double conservativeLower = NegativeInfinity<double>();
216 double conservativeUpper = PositiveInfinity<double>();
217 MDefinition* val = nullptr;
218
219 JSOp jsop = compare->jsop();
220
221 if (branch_dir == FALSE_BRANCH) {
222 jsop = NegateCompareOp(jsop);
223 conservativeLower = GenericNaN();
224 conservativeUpper = GenericNaN();
225 }
226
227 MConstant* leftConst = left->maybeConstantValue();
228 MConstant* rightConst = right->maybeConstantValue();
229 if (leftConst && leftConst->isTypeRepresentableAsDouble()) {
230 bound = leftConst->numberToDouble();
231 val = right;
232 jsop = ReverseCompareOp(jsop);
233 } else if (rightConst && rightConst->isTypeRepresentableAsDouble()) {
234 bound = rightConst->numberToDouble();
235 val = left;
236 } else if (left->type() == MIRType::Int32 &&
237 right->type() == MIRType::Int32) {
238 MDefinition* smaller = nullptr;
239 MDefinition* greater = nullptr;
240 if (jsop == JSOp::Lt) {
241 smaller = left;
242 greater = right;
243 } else if (jsop == JSOp::Gt) {
244 smaller = right;
245 greater = left;
246 }
247 if (smaller && greater) {
248 if (!alloc().ensureBallast()) {
249 return false;
250 }
251
252 MBeta* beta;
253 beta = MBeta::New(
254 alloc(), smaller,
255 Range::NewInt32Range(alloc(), JSVAL_INT_MIN, JSVAL_INT_MAX - 1));
256 block->insertBefore(*block->begin(), beta);
257 ReplaceDominatedUsesWith(smaller, beta, block);
258 JitSpew(JitSpew_Range, " Adding beta node for smaller %u",
259 smaller->id());
260 beta = MBeta::New(
261 alloc(), greater,
262 Range::NewInt32Range(alloc(), JSVAL_INT_MIN + 1, JSVAL_INT_MAX));
263 block->insertBefore(*block->begin(), beta);
264 ReplaceDominatedUsesWith(greater, beta, block);
265 JitSpew(JitSpew_Range, " Adding beta node for greater %u",
266 greater->id());
267 }
268 continue;
269 } else {
270 continue;
271 }
272
273 // At this point, one of the operands if the compare is a constant, and
274 // val is the other operand.
275 MOZ_ASSERT(val);
276
277 Range comp;
278 switch (jsop) {
279 case JSOp::Le:
280 comp.setDouble(conservativeLower, bound);
281 break;
282 case JSOp::Lt:
283 // For integers, if x < c, the upper bound of x is c-1.
284 if (val->type() == MIRType::Int32) {
285 int32_t intbound;
286 if (NumberEqualsInt32(bound, &intbound) &&
287 SafeSub(intbound, 1, &intbound)) {
288 bound = intbound;
289 }
290 }
291 comp.setDouble(conservativeLower, bound);
292
293 // Negative zero is not less than zero.
294 if (bound == 0) {
295 comp.refineToExcludeNegativeZero();
296 }
297 break;
298 case JSOp::Ge:
299 comp.setDouble(bound, conservativeUpper);
300 break;
301 case JSOp::Gt:
302 // For integers, if x > c, the lower bound of x is c+1.
303 if (val->type() == MIRType::Int32) {
304 int32_t intbound;
305 if (NumberEqualsInt32(bound, &intbound) &&
306 SafeAdd(intbound, 1, &intbound)) {
307 bound = intbound;
308 }
309 }
310 comp.setDouble(bound, conservativeUpper);
311
312 // Negative zero is not greater than zero.
313 if (bound == 0) {
314 comp.refineToExcludeNegativeZero();
315 }
316 break;
317 case JSOp::StrictEq:
318 case JSOp::Eq:
319 comp.setDouble(bound, bound);
320 break;
321 case JSOp::StrictNe:
322 case JSOp::Ne:
323 // Negative zero is not not-equal to zero.
324 if (bound == 0) {
325 comp.refineToExcludeNegativeZero();
326 break;
327 }
328 continue; // well, we could have
329 // [-\inf, bound-1] U [bound+1, \inf] but we only use
330 // contiguous ranges.
331 default:
332 continue;
333 }
334
335 if (JitSpewEnabled(JitSpew_Range)) {
336 JitSpewHeader(JitSpew_Range);
337 Fprinter& out = JitSpewPrinter();
338 out.printf(" Adding beta node for %u with range ", val->id());
339 comp.dump(out);
340 out.printf("\n");
341 }
342
343 if (!alloc().ensureBallast()) {
344 return false;
345 }
346
347 MBeta* beta = MBeta::New(alloc(), val, new (alloc()) Range(comp));
348 block->insertBefore(*block->begin(), beta);
349 ReplaceDominatedUsesWith(val, beta, block);
350 }
351
352 return true;
353 }
354
355 bool RangeAnalysis::removeBetaNodes() {
356 JitSpew(JitSpew_Range, "Removing beta nodes");
357
358 for (PostorderIterator i(graph_.poBegin()); i != graph_.poEnd(); i++) {
359 MBasicBlock* block = *i;
360 for (MDefinitionIterator iter(*i); iter;) {
361 MDefinition* def = *iter++;
362 if (def->isBeta()) {
363 auto* beta = def->toBeta();
364 MDefinition* op = beta->input();
365 JitSpew(JitSpew_Range, " Removing beta node %u for %u", beta->id(),
366 op->id());
367 beta->justReplaceAllUsesWith(op);
368 block->discard(beta);
369 } else {
370 // We only place Beta nodes at the beginning of basic
371 // blocks, so if we see something else, we can move on
372 // to the next block.
373 break;
374 }
375 }
376 }
377 return true;
378 }
379
380 void SymbolicBound::dump(GenericPrinter& out) const {
381 if (loop) {
382 out.printf("[loop] ");
383 }
384 sum.dump(out);
385 }
386
387 void SymbolicBound::dump() const {
388 Fprinter out(stderr);
389 dump(out);
390 out.printf("\n");
391 out.finish();
392 }
393
394 // Test whether the given range's exponent tells us anything that its lower
395 // and upper bound values don't.
396 static bool IsExponentInteresting(const Range* r) {
397 // If it lacks either a lower or upper bound, the exponent is interesting.
398 if (!r->hasInt32Bounds()) {
399 return true;
400 }
401
402 // Otherwise if there's no fractional part, the lower and upper bounds,
403 // which are integers, are perfectly precise.
404 if (!r->canHaveFractionalPart()) {
405 return false;
406 }
407
408 // Otherwise, if the bounds are conservatively rounded across a power-of-two
409 // boundary, the exponent may imply a tighter range.
410 return FloorLog2(std::max(Abs(r->lower()), Abs(r->upper()))) > r->exponent();
411 }
412
413 void Range::dump(GenericPrinter& out) const {
414 assertInvariants();
415
416 // Floating-point or Integer subset.
417 if (canHaveFractionalPart_) {
418 out.printf("F");
419 } else {
420 out.printf("I");
421 }
422
423 out.printf("[");
424
425 if (!hasInt32LowerBound_) {
426 out.printf("?");
427 } else {
428 out.printf("%d", lower_);
429 }
430 if (symbolicLower_) {
431 out.printf(" {");
432 symbolicLower_->dump(out);
433 out.printf("}");
434 }
435
436 out.printf(", ");
437
438 if (!hasInt32UpperBound_) {
439 out.printf("?");
440 } else {
441 out.printf("%d", upper_);
442 }
443 if (symbolicUpper_) {
444 out.printf(" {");
445 symbolicUpper_->dump(out);
446 out.printf("}");
447 }
448
449 out.printf("]");
450
451 bool includesNaN = max_exponent_ == IncludesInfinityAndNaN;
452 bool includesNegativeInfinity =
453 max_exponent_ >= IncludesInfinity && !hasInt32LowerBound_;
454 bool includesPositiveInfinity =
455 max_exponent_ >= IncludesInfinity && !hasInt32UpperBound_;
456 bool includesNegativeZero = canBeNegativeZero_;
457
458 if (includesNaN || includesNegativeInfinity || includesPositiveInfinity ||
459 includesNegativeZero) {
460 out.printf(" (");
461 bool first = true;
462 if (includesNaN) {
463 if (first) {
464 first = false;
465 } else {
466 out.printf(" ");
467 }
468 out.printf("U NaN");
469 }
470 if (includesNegativeInfinity) {
471 if (first) {
472 first = false;
473 } else {
474 out.printf(" ");
475 }
476 out.printf("U -Infinity");
477 }
478 if (includesPositiveInfinity) {
479 if (first) {
480 first = false;
481 } else {
482 out.printf(" ");
483 }
484 out.printf("U Infinity");
485 }
486 if (includesNegativeZero) {
487 if (first) {
488 first = false;
489 } else {
490 out.printf(" ");
491 }
492 out.printf("U -0");
493 }
494 out.printf(")");
495 }
496 if (max_exponent_ < IncludesInfinity && IsExponentInteresting(this)) {
497 out.printf(" (< pow(2, %d+1))", max_exponent_);
498 }
499 }
500
501 void Range::dump() const {
502 Fprinter out(stderr);
503 dump(out);
504 out.printf("\n");
505 out.finish();
506 }
507
508 Range* Range::intersect(TempAllocator& alloc, const Range* lhs,
509 const Range* rhs, bool* emptyRange) {
510 *emptyRange = false;
511
512 if (!lhs && !rhs) {
513 return nullptr;
514 }
515
516 if (!lhs) {
517 return new (alloc) Range(*rhs);
518 }
519 if (!rhs) {
520 return new (alloc) Range(*lhs);
521 }
522
523 int32_t newLower = std::max(lhs->lower_, rhs->lower_);
524 int32_t newUpper = std::min(lhs->upper_, rhs->upper_);
525
526 // If upper < lower, then we have conflicting constraints. Consider:
527 //
528 // if (x < 0) {
529 // if (x > 0) {
530 // [Some code.]
531 // }
532 // }
533 //
534 // In this case, the block is unreachable.
535 if (newUpper < newLower) {
536 // If both ranges can be NaN, the result can still be NaN.
537 if (!lhs->canBeNaN() || !rhs->canBeNaN()) {
538 *emptyRange = true;
539 }
540 return nullptr;
541 }
542
543 bool newHasInt32LowerBound =
544 lhs->hasInt32LowerBound_ || rhs->hasInt32LowerBound_;
545 bool newHasInt32UpperBound =
546 lhs->hasInt32UpperBound_ || rhs->hasInt32UpperBound_;
547
548 FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
549 lhs->canHaveFractionalPart_ && rhs->canHaveFractionalPart_);
550 NegativeZeroFlag newMayIncludeNegativeZero =
551 NegativeZeroFlag(lhs->canBeNegativeZero_ && rhs->canBeNegativeZero_);
552
553 uint16_t newExponent = std::min(lhs->max_exponent_, rhs->max_exponent_);
554
555 // NaN is a special value which is neither greater than infinity or less than
556 // negative infinity. When we intersect two ranges like [?, 0] and [0, ?], we
557 // can end up thinking we have both a lower and upper bound, even though NaN
558 // is still possible. In this case, just be conservative, since any case where
559 // we can have NaN is not especially interesting.
560 if (newHasInt32LowerBound && newHasInt32UpperBound &&
561 newExponent == IncludesInfinityAndNaN) {
562 return nullptr;
563 }
564
565 // If one of the ranges has a fractional part and the other doesn't, it's
566 // possible that we will have computed a newExponent that's more precise
567 // than our newLower and newUpper. This is unusual, so we handle it here
568 // instead of in optimize().
569 //
570 // For example, consider the range F[0,1.5]. Range analysis represents the
571 // lower and upper bound as integers, so we'd actually have
572 // F[0,2] (< pow(2, 0+1)). In this case, the exponent gives us a slightly
573 // more precise upper bound than the integer upper bound.
574 //
575 // When intersecting such a range with an integer range, the fractional part
576 // of the range is dropped. The max exponent of 0 remains valid, so the
577 // upper bound needs to be adjusted to 1.
578 //
579 // When intersecting F[0,2] (< pow(2, 0+1)) with a range like F[2,4],
580 // the naive intersection is I[2,2], but since the max exponent tells us
581 // that the value is always less than 2, the intersection is actually empty.
582 if (lhs->canHaveFractionalPart() != rhs->canHaveFractionalPart() ||
583 (lhs->canHaveFractionalPart() && newHasInt32LowerBound &&
584 newHasInt32UpperBound && newLower == newUpper)) {
585 refineInt32BoundsByExponent(newExponent, &newLower, &newHasInt32LowerBound,
586 &newUpper, &newHasInt32UpperBound);
587
588 // If we're intersecting two ranges that don't overlap, this could also
589 // push the bounds past each other, since the actual intersection is
590 // the empty set.
591 if (newLower > newUpper) {
592 *emptyRange = true;
593 return nullptr;
594 }
595 }
596
597 return new (alloc)
598 Range(newLower, newHasInt32LowerBound, newUpper, newHasInt32UpperBound,
599 newCanHaveFractionalPart, newMayIncludeNegativeZero, newExponent);
600 }
601
602 void Range::unionWith(const Range* other) {
603 int32_t newLower = std::min(lower_, other->lower_);
604 int32_t newUpper = std::max(upper_, other->upper_);
605
606 bool newHasInt32LowerBound =
607 hasInt32LowerBound_ && other->hasInt32LowerBound_;
608 bool newHasInt32UpperBound =
609 hasInt32UpperBound_ && other->hasInt32UpperBound_;
610
611 FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
612 canHaveFractionalPart_ || other->canHaveFractionalPart_);
613 NegativeZeroFlag newMayIncludeNegativeZero =
614 NegativeZeroFlag(canBeNegativeZero_ || other->canBeNegativeZero_);
615
616 uint16_t newExponent = std::max(max_exponent_, other->max_exponent_);
617
618 rawInitialize(newLower, newHasInt32LowerBound, newUpper,
619 newHasInt32UpperBound, newCanHaveFractionalPart,
620 newMayIncludeNegativeZero, newExponent);
621 }
622
623 Range::Range(const MDefinition* def)
624 : symbolicLower_(nullptr), symbolicUpper_(nullptr) {
625 if (const Range* other = def->range()) {
626 // The instruction has range information; use it.
627 *this = *other;
628
629 // Simulate the effect of converting the value to its type.
630 // Note: we cannot clamp here, since ranges aren't allowed to shrink
631 // and truncation can increase range again. So doing wrapAround to
632 // mimick a possible truncation.
633 switch (def->type()) {
634 case MIRType::Int32:
635 // MToNumberInt32 cannot truncate. So we can safely clamp.
636 if (def->isToNumberInt32()) {
637 clampToInt32();
638 } else {
639 wrapAroundToInt32();
640 }
641 break;
642 case MIRType::Boolean:
643 wrapAroundToBoolean();
644 break;
645 case MIRType::None:
646 MOZ_CRASH("Asking for the range of an instruction with no value");
647 default:
648 break;
649 }
650 } else {
651 // Otherwise just use type information. We can trust the type here
652 // because we don't care what value the instruction actually produces,
653 // but what value we might get after we get past the bailouts.
654 switch (def->type()) {
655 case MIRType::Int32:
656 setInt32(JSVAL_INT_MIN, JSVAL_INT_MAX);
657 break;
658 case MIRType::Boolean:
659 setInt32(0, 1);
660 break;
661 case MIRType::None:
662 MOZ_CRASH("Asking for the range of an instruction with no value");
663 default:
664 setUnknown();
665 break;
666 }
667 }
668
669 // As a special case, MUrsh is permitted to claim a result type of
670 // MIRType::Int32 while actually returning values in [0,UINT32_MAX] without
671 // bailouts. If range analysis hasn't ruled out values in
672 // (INT32_MAX,UINT32_MAX], set the range to be conservatively correct for
673 // use as either a uint32 or an int32.
674 if (!hasInt32UpperBound() && def->isUrsh() &&
675 def->toUrsh()->bailoutsDisabled() && def->type() != MIRType::Int64) {
676 lower_ = INT32_MIN;
677 }
678
679 assertInvariants();
680 }
681
682 static uint16_t ExponentImpliedByDouble(double d) {
683 // Handle the special values.
684 if (std::isnan(d)) {
685 return Range::IncludesInfinityAndNaN;
686 }
687 if (std::isinf(d)) {
688 return Range::IncludesInfinity;
689 }
690
691 // Otherwise take the exponent part and clamp it at zero, since the Range
692 // class doesn't track fractional ranges.
693 return uint16_t(std::max(int_fast16_t(0), ExponentComponent(d)));
694 }
695
696 void Range::setDouble(double l, double h) {
697 MOZ_ASSERT(!(l > h));
698
699 // Infer lower_, upper_, hasInt32LowerBound_, and hasInt32UpperBound_.
700 if (l >= INT32_MIN && l <= INT32_MAX) {
701 lower_ = int32_t(::floor(l));
702 hasInt32LowerBound_ = true;
703 } else if (l >= INT32_MAX) {
704 lower_ = INT32_MAX;
705 hasInt32LowerBound_ = true;
706 } else {
707 lower_ = INT32_MIN;
708 hasInt32LowerBound_ = false;
709 }
710 if (h >= INT32_MIN && h <= INT32_MAX) {
711 upper_ = int32_t(::ceil(h));
712 hasInt32UpperBound_ = true;
713 } else if (h <= INT32_MIN) {
714 upper_ = INT32_MIN;
715 hasInt32UpperBound_ = true;
716 } else {
717 upper_ = INT32_MAX;
718 hasInt32UpperBound_ = false;
719 }
720
721 // Infer max_exponent_.
722 uint16_t lExp = ExponentImpliedByDouble(l);
723 uint16_t hExp = ExponentImpliedByDouble(h);
724 max_exponent_ = std::max(lExp, hExp);
725
726 canHaveFractionalPart_ = ExcludesFractionalParts;
727 canBeNegativeZero_ = ExcludesNegativeZero;
728
729 // Infer the canHaveFractionalPart_ setting. We can have a
730 // fractional part if the range crosses through the neighborhood of zero. We
731 // won't have a fractional value if the value is always beyond the point at
732 // which double precision can't represent fractional values.
733 uint16_t minExp = std::min(lExp, hExp);
734 bool includesNegative = std::isnan(l) || l < 0;
735 bool includesPositive = std::isnan(h) || h > 0;
736 bool crossesZero = includesNegative && includesPositive;
737 if (crossesZero || minExp < MaxTruncatableExponent) {
738 canHaveFractionalPart_ = IncludesFractionalParts;
739 }
740
741 // Infer the canBeNegativeZero_ setting. We can have a negative zero if
742 // either bound is zero.
743 if (!(l > 0) && !(h < 0)) {
744 canBeNegativeZero_ = IncludesNegativeZero;
745 }
746
747 optimize();
748 }
749
750 void Range::setDoubleSingleton(double d) {
751 setDouble(d, d);
752
753 // The above setDouble call is for comparisons, and treats negative zero
754 // as equal to zero. We're aiming for a minimum range, so we can clear the
755 // negative zero flag if the value isn't actually negative zero.
756 if (!IsNegativeZero(d)) {
757 canBeNegativeZero_ = ExcludesNegativeZero;
758 }
759
760 assertInvariants();
761 }
762
763 static inline bool MissingAnyInt32Bounds(const Range* lhs, const Range* rhs) {
764 return !lhs->hasInt32Bounds() || !rhs->hasInt32Bounds();
765 }
766
767 Range* Range::add(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
768 int64_t l = (int64_t)lhs->lower_ + (int64_t)rhs->lower_;
769 if (!lhs->hasInt32LowerBound() || !rhs->hasInt32LowerBound()) {
770 l = NoInt32LowerBound;
771 }
772
773 int64_t h = (int64_t)lhs->upper_ + (int64_t)rhs->upper_;
774 if (!lhs->hasInt32UpperBound() || !rhs->hasInt32UpperBound()) {
775 h = NoInt32UpperBound;
776 }
777
778 // The exponent is at most one greater than the greater of the operands'
779 // exponents, except for NaN and infinity cases.
780 uint16_t e = std::max(lhs->max_exponent_, rhs->max_exponent_);
781 if (e <= Range::MaxFiniteExponent) {
782 ++e;
783 }
784
785 // Infinity + -Infinity is NaN.
786 if (lhs->canBeInfiniteOrNaN() && rhs->canBeInfiniteOrNaN()) {
787 e = Range::IncludesInfinityAndNaN;
788 }
789
790 return new (alloc) Range(
791 l, h,
792 FractionalPartFlag(lhs->canHaveFractionalPart() ||
793 rhs->canHaveFractionalPart()),
794 NegativeZeroFlag(lhs->canBeNegativeZero() && rhs->canBeNegativeZero()),
795 e);
796 }
797
798 Range* Range::sub(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
799 int64_t l = (int64_t)lhs->lower_ - (int64_t)rhs->upper_;
800 if (!lhs->hasInt32LowerBound() || !rhs->hasInt32UpperBound()) {
801 l = NoInt32LowerBound;
802 }
803
804 int64_t h = (int64_t)lhs->upper_ - (int64_t)rhs->lower_;
805 if (!lhs->hasInt32UpperBound() || !rhs->hasInt32LowerBound()) {
806 h = NoInt32UpperBound;
807 }
808
809 // The exponent is at most one greater than the greater of the operands'
810 // exponents, except for NaN and infinity cases.
811 uint16_t e = std::max(lhs->max_exponent_, rhs->max_exponent_);
812 if (e <= Range::MaxFiniteExponent) {
813 ++e;
814 }
815
816 // Infinity - Infinity is NaN.
817 if (lhs->canBeInfiniteOrNaN() && rhs->canBeInfiniteOrNaN()) {
818 e = Range::IncludesInfinityAndNaN;
819 }
820
821 return new (alloc)
822 Range(l, h,
823 FractionalPartFlag(lhs->canHaveFractionalPart() ||
824 rhs->canHaveFractionalPart()),
825 NegativeZeroFlag(lhs->canBeNegativeZero() && rhs->canBeZero()), e);
826 }
827
828 Range* Range::and_(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
829 MOZ_ASSERT(lhs->isInt32());
830 MOZ_ASSERT(rhs->isInt32());
831
832 // If both numbers can be negative, result can be negative in the whole range
833 if (lhs->lower() < 0 && rhs->lower() < 0) {
834 return Range::NewInt32Range(alloc, INT32_MIN,
835 std::max(lhs->upper(), rhs->upper()));
836 }
837
838 // Only one of both numbers can be negative.
839 // - result can't be negative
840 // - Upper bound is minimum of both upper range,
841 int32_t lower = 0;
842 int32_t upper = std::min(lhs->upper(), rhs->upper());
843
844 // EXCEPT when upper bound of non negative number is max value,
845 // because negative value can return the whole max value.
846 // -1 & 5 = 5
847 if (lhs->lower() < 0) {
848 upper = rhs->upper();
849 }
850 if (rhs->lower() < 0) {
851 upper = lhs->upper();
852 }
853
854 return Range::NewInt32Range(alloc, lower, upper);
855 }
856
857 Range* Range::or_(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
858 MOZ_ASSERT(lhs->isInt32());
859 MOZ_ASSERT(rhs->isInt32());
860 // When one operand is always 0 or always -1, it's a special case where we
861 // can compute a fully precise result. Handling these up front also
862 // protects the code below from calling CountLeadingZeroes32 with a zero
863 // operand or from shifting an int32_t by 32.
864 if (lhs->lower() == lhs->upper()) {
865 if (lhs->lower() == 0) {
866 return new (alloc) Range(*rhs);
867 }
868 if (lhs->lower() == -1) {
869 return new (alloc) Range(*lhs);
870 }
871 }
872 if (rhs->lower() == rhs->upper()) {
873 if (rhs->lower() == 0) {
874 return new (alloc) Range(*lhs);
875 }
876 if (rhs->lower() == -1) {
877 return new (alloc) Range(*rhs);
878 }
879 }
880
881 // The code below uses CountLeadingZeroes32, which has undefined behavior
882 // if its operand is 0. We rely on the code above to protect it.
883 MOZ_ASSERT_IF(lhs->lower() >= 0, lhs->upper() != 0);
884 MOZ_ASSERT_IF(rhs->lower() >= 0, rhs->upper() != 0);
885 MOZ_ASSERT_IF(lhs->upper() < 0, lhs->lower() != -1);
886 MOZ_ASSERT_IF(rhs->upper() < 0, rhs->lower() != -1);
887
888 int32_t lower = INT32_MIN;
889 int32_t upper = INT32_MAX;
890
891 if (lhs->lower() >= 0 && rhs->lower() >= 0) {
892 // Both operands are non-negative, so the result won't be less than either.
893 lower = std::max(lhs->lower(), rhs->lower());
894 // The result will have leading zeros where both operands have leading
895 // zeros. CountLeadingZeroes32 of a non-negative int32 will at least be 1 to
896 // account for the bit of sign.
897 upper = int32_t(UINT32_MAX >> std::min(CountLeadingZeroes32(lhs->upper()),
898 CountLeadingZeroes32(rhs->upper())));
899 } else {
900 // The result will have leading ones where either operand has leading ones.
901 if (lhs->upper() < 0) {
902 unsigned leadingOnes = CountLeadingZeroes32(~lhs->lower());
903 lower = std::max(lower, ~int32_t(UINT32_MAX >> leadingOnes));
904 upper = -1;
905 }
906 if (rhs->upper() < 0) {
907 unsigned leadingOnes = CountLeadingZeroes32(~rhs->lower());
908 lower = std::max(lower, ~int32_t(UINT32_MAX >> leadingOnes));
909 upper = -1;
910 }
911 }
912
913 return Range::NewInt32Range(alloc, lower, upper);
914 }
915
916 Range* Range::xor_(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
917 MOZ_ASSERT(lhs->isInt32());
918 MOZ_ASSERT(rhs->isInt32());
919 int32_t lhsLower = lhs->lower();
920 int32_t lhsUpper = lhs->upper();
921 int32_t rhsLower = rhs->lower();
922 int32_t rhsUpper = rhs->upper();
923 bool invertAfter = false;
924
925 // If either operand is negative, bitwise-negate it, and arrange to negate
926 // the result; ~((~x)^y) == x^y. If both are negative the negations on the
927 // result cancel each other out; effectively this is (~x)^(~y) == x^y.
928 // These transformations reduce the number of cases we have to handle below.
929 if (lhsUpper < 0) {
930 lhsLower = ~lhsLower;
931 lhsUpper = ~lhsUpper;
932 std::swap(lhsLower, lhsUpper);
933 invertAfter = !invertAfter;
934 }
935 if (rhsUpper < 0) {
936 rhsLower = ~rhsLower;
937 rhsUpper = ~rhsUpper;
938 std::swap(rhsLower, rhsUpper);
939 invertAfter = !invertAfter;
940 }
941
942 // Handle cases where lhs or rhs is always zero specially, because they're
943 // easy cases where we can be perfectly precise, and because it protects the
944 // CountLeadingZeroes32 calls below from seeing 0 operands, which would be
945 // undefined behavior.
946 int32_t lower = INT32_MIN;
947 int32_t upper = INT32_MAX;
948 if (lhsLower == 0 && lhsUpper == 0) {
949 upper = rhsUpper;
950 lower = rhsLower;
951 } else if (rhsLower == 0 && rhsUpper == 0) {
952 upper = lhsUpper;
953 lower = lhsLower;
954 } else if (lhsLower >= 0 && rhsLower >= 0) {
955 // Both operands are non-negative. The result will be non-negative.
956 lower = 0;
957 // To compute the upper value, take each operand's upper value and
958 // set all bits that don't correspond to leading zero bits in the
959 // other to one. For each one, this gives an upper bound for the
960 // result, so we can take the minimum between the two.
961 unsigned lhsLeadingZeros = CountLeadingZeroes32(lhsUpper);
962 unsigned rhsLeadingZeros = CountLeadingZeroes32(rhsUpper);
963 upper = std::min(rhsUpper | int32_t(UINT32_MAX >> lhsLeadingZeros),
964 lhsUpper | int32_t(UINT32_MAX >> rhsLeadingZeros));
965 }
966
967 // If we bitwise-negated one (but not both) of the operands above, apply the
968 // bitwise-negate to the result, completing ~((~x)^y) == x^y.
969 if (invertAfter) {
970 lower = ~lower;
971 upper = ~upper;
972 std::swap(lower, upper);
973 }
974
975 return Range::NewInt32Range(alloc, lower, upper);
976 }
977
978 Range* Range::not_(TempAllocator& alloc, const Range* op) {
979 MOZ_ASSERT(op->isInt32());
980 return Range::NewInt32Range(alloc, ~op->upper(), ~op->lower());
981 }
982
983 Range* Range::mul(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
984 FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
985 lhs->canHaveFractionalPart_ || rhs->canHaveFractionalPart_);
986
987 NegativeZeroFlag newMayIncludeNegativeZero = NegativeZeroFlag(
988 (lhs->canHaveSignBitSet() && rhs->canBeFiniteNonNegative()) ||
989 (rhs->canHaveSignBitSet() && lhs->canBeFiniteNonNegative()));
990
991 uint16_t exponent;
992 if (!lhs->canBeInfiniteOrNaN() && !rhs->canBeInfiniteOrNaN()) {
993 // Two finite values.
994 exponent = lhs->numBits() + rhs->numBits() - 1;
995 if (exponent > Range::MaxFiniteExponent) {
996 exponent = Range::IncludesInfinity;
997 }
998 } else if (!lhs->canBeNaN() && !rhs->canBeNaN() &&
999 !(lhs->canBeZero() && rhs->canBeInfiniteOrNaN()) &&
1000 !(rhs->canBeZero() && lhs->canBeInfiniteOrNaN())) {
1001 // Two values that multiplied together won't produce a NaN.
1002 exponent = Range::IncludesInfinity;
1003 } else {
1004 // Could be anything.
1005 exponent = Range::IncludesInfinityAndNaN;
1006 }
1007
1008 if (MissingAnyInt32Bounds(lhs, rhs)) {
1009 return new (alloc)
1010 Range(NoInt32LowerBound, NoInt32UpperBound, newCanHaveFractionalPart,
1011 newMayIncludeNegativeZero, exponent);
1012 }
1013 int64_t a = (int64_t)lhs->lower() * (int64_t)rhs->lower();
1014 int64_t b = (int64_t)lhs->lower() * (int64_t)rhs->upper();
1015 int64_t c = (int64_t)lhs->upper() * (int64_t)rhs->lower();
1016 int64_t d = (int64_t)lhs->upper() * (int64_t)rhs->upper();
1017 return new (alloc)
1018 Range(std::min(std::min(a, b), std::min(c, d)),
1019 std::max(std::max(a, b), std::max(c, d)), newCanHaveFractionalPart,
1020 newMayIncludeNegativeZero, exponent);
1021 }
1022
1023 Range* Range::lsh(TempAllocator& alloc, const Range* lhs, int32_t c) {
1024 MOZ_ASSERT(lhs->isInt32());
1025 int32_t shift = c & 0x1f;
1026
1027 // If the shift doesn't loose bits or shift bits into the sign bit, we
1028 // can simply compute the correct range by shifting.
1029 if ((int32_t)((uint32_t)lhs->lower() << shift << 1 >> shift >> 1) ==
1030 lhs->lower() &&
1031 (int32_t)((uint32_t)lhs->upper() << shift << 1 >> shift >> 1) ==
1032 lhs->upper()) {
1033 return Range::NewInt32Range(alloc, uint32_t(lhs->lower()) << shift,
1034 uint32_t(lhs->upper()) << shift);
1035 }
1036
1037 return Range::NewInt32Range(alloc, INT32_MIN, INT32_MAX);
1038 }
1039
1040 Range* Range::rsh(TempAllocator& alloc, const Range* lhs, int32_t c) {
1041 MOZ_ASSERT(lhs->isInt32());
1042 int32_t shift = c & 0x1f;
1043 return Range::NewInt32Range(alloc, lhs->lower() >> shift,
1044 lhs->upper() >> shift);
1045 }
1046
1047 Range* Range::ursh(TempAllocator& alloc, const Range* lhs, int32_t c) {
1048 // ursh's left operand is uint32, not int32, but for range analysis we
1049 // currently approximate it as int32. We assume here that the range has
1050 // already been adjusted accordingly by our callers.
1051 MOZ_ASSERT(lhs->isInt32());
1052
1053 int32_t shift = c & 0x1f;
1054
1055 // If the value is always non-negative or always negative, we can simply
1056 // compute the correct range by shifting.
1057 if (lhs->isFiniteNonNegative() || lhs->isFiniteNegative()) {
1058 return Range::NewUInt32Range(alloc, uint32_t(lhs->lower()) >> shift,
1059 uint32_t(lhs->upper()) >> shift);
1060 }
1061
1062 // Otherwise return the most general range after the shift.
1063 return Range::NewUInt32Range(alloc, 0, UINT32_MAX >> shift);
1064 }
1065
1066 Range* Range::lsh(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
1067 MOZ_ASSERT(lhs->isInt32());
1068 MOZ_ASSERT(rhs->isInt32());
1069 return Range::NewInt32Range(alloc, INT32_MIN, INT32_MAX);
1070 }
1071
1072 Range* Range::rsh(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
1073 MOZ_ASSERT(lhs->isInt32());
1074 MOZ_ASSERT(rhs->isInt32());
1075
1076 // Canonicalize the shift range to 0 to 31.
1077 int32_t shiftLower = rhs->lower();
1078 int32_t shiftUpper = rhs->upper();
1079 if ((int64_t(shiftUpper) - int64_t(shiftLower)) >= 31) {
1080 shiftLower = 0;
1081 shiftUpper = 31;
1082 } else {
1083 shiftLower &= 0x1f;
1084 shiftUpper &= 0x1f;
1085 if (shiftLower > shiftUpper) {
1086 shiftLower = 0;
1087 shiftUpper = 31;
1088 }
1089 }
1090 MOZ_ASSERT(shiftLower >= 0 && shiftUpper <= 31);
1091
1092 // The lhs bounds are signed, thus the minimum is either the lower bound
1093 // shift by the smallest shift if negative or the lower bound shifted by the
1094 // biggest shift otherwise. And the opposite for the maximum.
1095 int32_t lhsLower = lhs->lower();
1096 int32_t min = lhsLower < 0 ? lhsLower >> shiftLower : lhsLower >> shiftUpper;
1097 int32_t lhsUpper = lhs->upper();
1098 int32_t max = lhsUpper >= 0 ? lhsUpper >> shiftLower : lhsUpper >> shiftUpper;
1099
1100 return Range::NewInt32Range(alloc, min, max);
1101 }
1102
1103 Range* Range::ursh(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
1104 // ursh's left operand is uint32, not int32, but for range analysis we
1105 // currently approximate it as int32. We assume here that the range has
1106 // already been adjusted accordingly by our callers.
1107 MOZ_ASSERT(lhs->isInt32());
1108 MOZ_ASSERT(rhs->isInt32());
1109 return Range::NewUInt32Range(
1110 alloc, 0, lhs->isFiniteNonNegative() ? lhs->upper() : UINT32_MAX);
1111 }
1112
1113 Range* Range::abs(TempAllocator& alloc, const Range* op) {
1114 int32_t l = op->lower_;
1115 int32_t u = op->upper_;
1116 FractionalPartFlag canHaveFractionalPart = op->canHaveFractionalPart_;
1117
1118 // Abs never produces a negative zero.
1119 NegativeZeroFlag canBeNegativeZero = ExcludesNegativeZero;
1120
1121 return new (alloc) Range(
1122 std::max(std::max(int32_t(0), l), u == INT32_MIN ? INT32_MAX : -u), true,
1123 std::max(std::max(int32_t(0), u), l == INT32_MIN ? INT32_MAX : -l),
1124 op->hasInt32Bounds() && l != INT32_MIN, canHaveFractionalPart,
1125 canBeNegativeZero, op->max_exponent_);
1126 }
1127
1128 Range* Range::min(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
1129 // If either operand is NaN, the result is NaN.
1130 if (lhs->canBeNaN() || rhs->canBeNaN()) {
1131 return nullptr;
1132 }
1133
1134 FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
1135 lhs->canHaveFractionalPart_ || rhs->canHaveFractionalPart_);
1136 NegativeZeroFlag newMayIncludeNegativeZero =
1137 NegativeZeroFlag(lhs->canBeNegativeZero_ || rhs->canBeNegativeZero_);
1138
1139 return new (alloc) Range(std::min(lhs->lower_, rhs->lower_),
1140 lhs->hasInt32LowerBound_ && rhs->hasInt32LowerBound_,
1141 std::min(lhs->upper_, rhs->upper_),
1142 lhs->hasInt32UpperBound_ || rhs->hasInt32UpperBound_,
1143 newCanHaveFractionalPart, newMayIncludeNegativeZero,
1144 std::max(lhs->max_exponent_, rhs->max_exponent_));
1145 }
1146
1147 Range* Range::max(TempAllocator& alloc, const Range* lhs, const Range* rhs) {
1148 // If either operand is NaN, the result is NaN.
1149 if (lhs->canBeNaN() || rhs->canBeNaN()) {
1150 return nullptr;
1151 }
1152
1153 FractionalPartFlag newCanHaveFractionalPart = FractionalPartFlag(
1154 lhs->canHaveFractionalPart_ || rhs->canHaveFractionalPart_);
1155 NegativeZeroFlag newMayIncludeNegativeZero =
1156 NegativeZeroFlag(lhs->canBeNegativeZero_ || rhs->canBeNegativeZero_);
1157
1158 return new (alloc) Range(std::max(lhs->lower_, rhs->lower_),
1159 lhs->hasInt32LowerBound_ || rhs->hasInt32LowerBound_,
1160 std::max(lhs->upper_, rhs->upper_),
1161 lhs->hasInt32UpperBound_ && rhs->hasInt32UpperBound_,
1162 newCanHaveFractionalPart, newMayIncludeNegativeZero,
1163 std::max(lhs->max_exponent_, rhs->max_exponent_));
1164 }
1165
1166 Range* Range::floor(TempAllocator& alloc, const Range* op) {
1167 Range* copy = new (alloc) Range(*op);
1168 // Decrement lower bound of copy range if op have a factional part and lower
1169 // bound is Int32 defined. Also we avoid to decrement when op have a
1170 // fractional part but lower_ >= JSVAL_INT_MAX.
1171 if (op->canHaveFractionalPart() && op->hasInt32LowerBound()) {
1172 copy->setLowerInit(int64_t(copy->lower_) - 1);
1173 }
1174
1175 // Also refine max_exponent_ because floor may have decremented int value
1176 // If we've got int32 defined bounds, just deduce it using defined bounds.
1177 // But, if we don't have those, value's max_exponent_ may have changed.
1178 // Because we're looking to maintain an over estimation, if we can,
1179 // we increment it.
1180 if (copy->hasInt32Bounds())
1181 copy->max_exponent_ = copy->exponentImpliedByInt32Bounds();
1182 else if (copy->max_exponent_ < MaxFiniteExponent)
1183 copy->max_exponent_++;
1184
1185 copy->canHaveFractionalPart_ = ExcludesFractionalParts;
1186 copy->assertInvariants();
1187 return copy;
1188 }
1189
1190 Range* Range::ceil(TempAllocator& alloc, const Range* op) {
1191 Range* copy = new (alloc) Range(*op);
1192
1193 // We need to refine max_exponent_ because ceil may have incremented the int
1194 // value. If we have got int32 bounds defined, just deduce it using the
1195 // defined bounds. Else we can just increment its value, as we are looking to
1196 // maintain an over estimation.
1197 if (copy->hasInt32Bounds()) {
1198 copy->max_exponent_ = copy->exponentImpliedByInt32Bounds();
1199 } else if (copy->max_exponent_ < MaxFiniteExponent) {
1200 copy->max_exponent_++;
1201 }
1202
1203 // If the range is definitely above 0 or below -1, we don't need to include
1204 // -0; otherwise we do.
1205
1206 copy->canBeNegativeZero_ = ((copy->lower_ > 0) || (copy->upper_ <= -1))
1207 ? copy->canBeNegativeZero_
1208 : IncludesNegativeZero;
1209
1210 copy->canHaveFractionalPart_ = ExcludesFractionalParts;
1211 copy->assertInvariants();
1212 return copy;
1213 }
1214
1215 Range* Range::sign(TempAllocator& alloc, const Range* op) {
1216 if (op->canBeNaN()) {
1217 return nullptr;
1218 }
1219
1220 return new (alloc)
1221 Range(std::clamp(op->lower_, -1, 1), std::clamp(op->upper_, -1, 1),
1222 Range::ExcludesFractionalParts,
1223 NegativeZeroFlag(op->canBeNegativeZero()), 0);
1224 }
1225
1226 Range* Range::NaNToZero(TempAllocator& alloc, const Range* op) {
1227 Range* copy = new (alloc) Range(*op);
1228 if (copy->canBeNaN()) {
1229 copy->max_exponent_ = Range::IncludesInfinity;
1230 if (!copy->canBeZero()) {
1231 Range zero;
1232 zero.setDoubleSingleton(0);
1233 copy->unionWith(&zero);
1234 }
1235 }
1236 copy->refineToExcludeNegativeZero();
1237 return copy;
1238 }
1239
1240 bool Range::negativeZeroMul(const Range* lhs, const Range* rhs) {
1241 // The result can only be negative zero if both sides are finite and they
1242 // have differing signs.
1243 return (lhs->canHaveSignBitSet() && rhs->canBeFiniteNonNegative()) ||
1244 (rhs->canHaveSignBitSet() && lhs->canBeFiniteNonNegative());
1245 }
1246
1247 bool Range::update(const Range* other) {
1248 bool changed = lower_ != other->lower_ ||
1249 hasInt32LowerBound_ != other->hasInt32LowerBound_ ||
1250 upper_ != other->upper_ ||
1251 hasInt32UpperBound_ != other->hasInt32UpperBound_ ||
1252 canHaveFractionalPart_ != other->canHaveFractionalPart_ ||
1253 canBeNegativeZero_ != other->canBeNegativeZero_ ||
1254 max_exponent_ != other->max_exponent_;
1255 if (changed) {
1256 lower_ = other->lower_;
1257 hasInt32LowerBound_ = other->hasInt32LowerBound_;
1258 upper_ = other->upper_;
1259 hasInt32UpperBound_ = other->hasInt32UpperBound_;
1260 canHaveFractionalPart_ = other->canHaveFractionalPart_;
1261 canBeNegativeZero_ = other->canBeNegativeZero_;
1262 max_exponent_ = other->max_exponent_;
1263 assertInvariants();
1264 }
1265
1266 return changed;
1267 }
1268
1269 ///////////////////////////////////////////////////////////////////////////////
1270 // Range Computation for MIR Nodes
1271 ///////////////////////////////////////////////////////////////////////////////
1272
1273 void MPhi::computeRange(TempAllocator& alloc) {
1274 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1275 return;
1276 }
1277
1278 Range* range = nullptr;
1279 for (size_t i = 0, e = numOperands(); i < e; i++) {
1280 if (getOperand(i)->block()->unreachable()) {
1281 JitSpew(JitSpew_Range, "Ignoring unreachable input %u",
1282 getOperand(i)->id());
1283 continue;
1284 }
1285
1286 // Peek at the pre-bailout range so we can take a short-cut; if any of
1287 // the operands has an unknown range, this phi has an unknown range.
1288 if (!getOperand(i)->range()) {
1289 return;
1290 }
1291
1292 Range input(getOperand(i));
1293
1294 if (range) {
1295 range->unionWith(&input);
1296 } else {
1297 range = new (alloc) Range(input);
1298 }
1299 }
1300
1301 setRange(range);
1302 }
1303
1304 void MBeta::computeRange(TempAllocator& alloc) {
1305 bool emptyRange = false;
1306
1307 Range opRange(getOperand(0));
1308 Range* range = Range::intersect(alloc, &opRange, comparison_, &emptyRange);
1309 if (emptyRange) {
1310 JitSpew(JitSpew_Range, "Marking block for inst %u unreachable", id());
1311 block()->setUnreachableUnchecked();
1312 } else {
1313 setRange(range);
1314 }
1315 }
1316
1317 void MConstant::computeRange(TempAllocator& alloc) {
1318 if (isTypeRepresentableAsDouble()) {
1319 double d = numberToDouble();
1320 setRange(Range::NewDoubleSingletonRange(alloc, d));
1321 } else if (type() == MIRType::Boolean) {
1322 bool b = toBoolean();
1323 setRange(Range::NewInt32Range(alloc, b, b));
1324 }
1325 }
1326
1327 void MCharCodeAt::computeRange(TempAllocator& alloc) {
1328 // ECMA 262 says that the integer will be non-negative and at most 65535.
1329 setRange(Range::NewInt32Range(alloc, 0, unicode::UTF16Max));
1330 }
1331
1332 void MCodePointAt::computeRange(TempAllocator& alloc) {
1333 setRange(Range::NewInt32Range(alloc, 0, unicode::NonBMPMax));
1334 }
1335
1336 void MClampToUint8::computeRange(TempAllocator& alloc) {
1337 setRange(Range::NewUInt32Range(alloc, 0, 255));
1338 }
1339
1340 void MBitAnd::computeRange(TempAllocator& alloc) {
1341 if (type() != MIRType::Int32) {
1342 return;
1343 }
1344
1345 Range left(getOperand(0));
1346 Range right(getOperand(1));
1347 left.wrapAroundToInt32();
1348 right.wrapAroundToInt32();
1349
1350 setRange(Range::and_(alloc, &left, &right));
1351 }
1352
1353 void MBitOr::computeRange(TempAllocator& alloc) {
1354 if (type() != MIRType::Int32) {
1355 return;
1356 }
1357
1358 Range left(getOperand(0));
1359 Range right(getOperand(1));
1360 left.wrapAroundToInt32();
1361 right.wrapAroundToInt32();
1362
1363 setRange(Range::or_(alloc, &left, &right));
1364 }
1365
1366 void MBitXor::computeRange(TempAllocator& alloc) {
1367 if (type() != MIRType::Int32) {
1368 return;
1369 }
1370
1371 Range left(getOperand(0));
1372 Range right(getOperand(1));
1373 left.wrapAroundToInt32();
1374 right.wrapAroundToInt32();
1375
1376 setRange(Range::xor_(alloc, &left, &right));
1377 }
1378
1379 void MBitNot::computeRange(TempAllocator& alloc) {
1380 if (type() == MIRType::Int64) {
1381 return;
1382 }
1383 MOZ_ASSERT(type() == MIRType::Int32);
1384
1385 Range op(getOperand(0));
1386 op.wrapAroundToInt32();
1387
1388 setRange(Range::not_(alloc, &op));
1389 }
1390
1391 void MLsh::computeRange(TempAllocator& alloc) {
1392 if (type() != MIRType::Int32) {
1393 return;
1394 }
1395
1396 Range left(getOperand(0));
1397 Range right(getOperand(1));
1398 left.wrapAroundToInt32();
1399
1400 MConstant* rhsConst = getOperand(1)->maybeConstantValue();
1401 if (rhsConst && rhsConst->type() == MIRType::Int32) {
1402 int32_t c = rhsConst->toInt32();
1403 setRange(Range::lsh(alloc, &left, c));
1404 return;
1405 }
1406
1407 right.wrapAroundToShiftCount();
1408 setRange(Range::lsh(alloc, &left, &right));
1409 }
1410
1411 void MRsh::computeRange(TempAllocator& alloc) {
1412 if (type() != MIRType::Int32) {
1413 return;
1414 }
1415
1416 Range left(getOperand(0));
1417 Range right(getOperand(1));
1418 left.wrapAroundToInt32();
1419
1420 MConstant* rhsConst = getOperand(1)->maybeConstantValue();
1421 if (rhsConst && rhsConst->type() == MIRType::Int32) {
1422 int32_t c = rhsConst->toInt32();
1423 setRange(Range::rsh(alloc, &left, c));
1424 return;
1425 }
1426
1427 right.wrapAroundToShiftCount();
1428 setRange(Range::rsh(alloc, &left, &right));
1429 }
1430
1431 void MUrsh::computeRange(TempAllocator& alloc) {
1432 if (type() != MIRType::Int32) {
1433 return;
1434 }
1435
1436 Range left(getOperand(0));
1437 Range right(getOperand(1));
1438
1439 // ursh can be thought of as converting its left operand to uint32, or it
1440 // can be thought of as converting its left operand to int32, and then
1441 // reinterpreting the int32 bits as a uint32 value. Both approaches yield
1442 // the same result. Since we lack support for full uint32 ranges, we use
1443 // the second interpretation, though it does cause us to be conservative.
1444 left.wrapAroundToInt32();
1445 right.wrapAroundToShiftCount();
1446
1447 MConstant* rhsConst = getOperand(1)->maybeConstantValue();
1448 if (rhsConst && rhsConst->type() == MIRType::Int32) {
1449 int32_t c = rhsConst->toInt32();
1450 setRange(Range::ursh(alloc, &left, c));
1451 } else {
1452 setRange(Range::ursh(alloc, &left, &right));
1453 }
1454
1455 MOZ_ASSERT(range()->lower() >= 0);
1456 }
1457
1458 void MAbs::computeRange(TempAllocator& alloc) {
1459 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1460 return;
1461 }
1462
1463 Range other(getOperand(0));
1464 Range* next = Range::abs(alloc, &other);
1465 if (implicitTruncate_) {
1466 next->wrapAroundToInt32();
1467 }
1468 setRange(next);
1469 }
1470
1471 void MFloor::computeRange(TempAllocator& alloc) {
1472 Range other(getOperand(0));
1473 setRange(Range::floor(alloc, &other));
1474 }
1475
1476 void MCeil::computeRange(TempAllocator& alloc) {
1477 Range other(getOperand(0));
1478 setRange(Range::ceil(alloc, &other));
1479 }
1480
1481 void MClz::computeRange(TempAllocator& alloc) {
1482 if (type() != MIRType::Int32) {
1483 return;
1484 }
1485 setRange(Range::NewUInt32Range(alloc, 0, 32));
1486 }
1487
1488 void MCtz::computeRange(TempAllocator& alloc) {
1489 if (type() != MIRType::Int32) {
1490 return;
1491 }
1492 setRange(Range::NewUInt32Range(alloc, 0, 32));
1493 }
1494
1495 void MPopcnt::computeRange(TempAllocator& alloc) {
1496 if (type() != MIRType::Int32) {
1497 return;
1498 }
1499 setRange(Range::NewUInt32Range(alloc, 0, 32));
1500 }
1501
1502 void MMinMax::computeRange(TempAllocator& alloc) {
1503 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1504 return;
1505 }
1506
1507 Range left(getOperand(0));
1508 Range right(getOperand(1));
1509 setRange(isMax() ? Range::max(alloc, &left, &right)
1510 : Range::min(alloc, &left, &right));
1511 }
1512
1513 void MAdd::computeRange(TempAllocator& alloc) {
1514 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1515 return;
1516 }
1517 Range left(getOperand(0));
1518 Range right(getOperand(1));
1519 Range* next = Range::add(alloc, &left, &right);
1520 if (isTruncated()) {
1521 next->wrapAroundToInt32();
1522 }
1523 setRange(next);
1524 }
1525
1526 void MSub::computeRange(TempAllocator& alloc) {
1527 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1528 return;
1529 }
1530 Range left(getOperand(0));
1531 Range right(getOperand(1));
1532 Range* next = Range::sub(alloc, &left, &right);
1533 if (isTruncated()) {
1534 next->wrapAroundToInt32();
1535 }
1536 setRange(next);
1537 }
1538
1539 void MMul::computeRange(TempAllocator& alloc) {
1540 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1541 return;
1542 }
1543 Range left(getOperand(0));
1544 Range right(getOperand(1));
1545 if (canBeNegativeZero()) {
1546 canBeNegativeZero_ = Range::negativeZeroMul(&left, &right);
1547 }
1548 Range* next = Range::mul(alloc, &left, &right);
1549 if (!next->canBeNegativeZero()) {
1550 canBeNegativeZero_ = false;
1551 }
1552 // Truncated multiplications could overflow in both directions
1553 if (isTruncated()) {
1554 next->wrapAroundToInt32();
1555 }
1556 setRange(next);
1557 }
1558
1559 void MMod::computeRange(TempAllocator& alloc) {
1560 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1561 return;
1562 }
1563 Range lhs(getOperand(0));
1564 Range rhs(getOperand(1));
1565
1566 // If either operand is a NaN, the result is NaN. This also conservatively
1567 // handles Infinity cases.
1568 if (!lhs.hasInt32Bounds() || !rhs.hasInt32Bounds()) {
1569 return;
1570 }
1571
1572 // If RHS can be zero, the result can be NaN.
1573 if (rhs.lower() <= 0 && rhs.upper() >= 0) {
1574 return;
1575 }
1576
1577 // If both operands are non-negative integers, we can optimize this to an
1578 // unsigned mod.
1579 if (type() == MIRType::Int32 && rhs.lower() > 0) {
1580 bool hasDoubles = lhs.lower() < 0 || lhs.canHaveFractionalPart() ||
1581 rhs.canHaveFractionalPart();
1582 // It is not possible to check that lhs.lower() >= 0, since the range
1583 // of a ursh with rhs a 0 constant is wrapped around the int32 range in
1584 // Range::Range(). However, IsUint32Type() will only return true for
1585 // nodes that lie in the range [0, UINT32_MAX].
1586 bool hasUint32s =
1587 IsUint32Type(getOperand(0)) &&
1588 getOperand(1)->type() == MIRType::Int32 &&
1589 (IsUint32Type(getOperand(1)) || getOperand(1)->isConstant());
1590 if (!hasDoubles || hasUint32s) {
1591 unsigned_ = true;
1592 }
1593 }
1594
1595 // For unsigned mod, we have to convert both operands to unsigned.
1596 // Note that we handled the case of a zero rhs above.
1597 if (unsigned_) {
1598 // The result of an unsigned mod will never be unsigned-greater than
1599 // either operand.
1600 uint32_t lhsBound = std::max<uint32_t>(lhs.lower(), lhs.upper());
1601 uint32_t rhsBound = std::max<uint32_t>(rhs.lower(), rhs.upper());
1602
1603 // If either range crosses through -1 as a signed value, it could be
1604 // the maximum unsigned value when interpreted as unsigned. If the range
1605 // doesn't include -1, then the simple max value we computed above is
1606 // correct.
1607 if (lhs.lower() <= -1 && lhs.upper() >= -1) {
1608 lhsBound = UINT32_MAX;
1609 }
1610 if (rhs.lower() <= -1 && rhs.upper() >= -1) {
1611 rhsBound = UINT32_MAX;
1612 }
1613
1614 // The result will never be equal to the rhs, and we shouldn't have
1615 // any rounding to worry about.
1616 MOZ_ASSERT(!lhs.canHaveFractionalPart() && !rhs.canHaveFractionalPart());
1617 --rhsBound;
1618
1619 // This gives us two upper bounds, so we can take the best one.
1620 setRange(Range::NewUInt32Range(alloc, 0, std::min(lhsBound, rhsBound)));
1621 return;
1622 }
1623
1624 // Math.abs(lhs % rhs) == Math.abs(lhs) % Math.abs(rhs).
1625 // First, the absolute value of the result will always be less than the
1626 // absolute value of rhs. (And if rhs is zero, the result is NaN).
1627 int64_t a = Abs<int64_t>(rhs.lower());
1628 int64_t b = Abs<int64_t>(rhs.upper());
1629 if (a == 0 && b == 0) {
1630 return;
1631 }
1632 int64_t rhsAbsBound = std::max(a, b);
1633
1634 // If the value is known to be integer, less-than abs(rhs) is equivalent
1635 // to less-than-or-equal abs(rhs)-1. This is important for being able to
1636 // say that the result of x%256 is an 8-bit unsigned number.
1637 if (!lhs.canHaveFractionalPart() && !rhs.canHaveFractionalPart()) {
1638 --rhsAbsBound;
1639 }
1640
1641 // Next, the absolute value of the result will never be greater than the
1642 // absolute value of lhs.
1643 int64_t lhsAbsBound =
1644 std::max(Abs<int64_t>(lhs.lower()), Abs<int64_t>(lhs.upper()));
1645
1646 // This gives us two upper bounds, so we can take the best one.
1647 int64_t absBound = std::min(lhsAbsBound, rhsAbsBound);
1648
1649 // Now consider the sign of the result.
1650 // If lhs is non-negative, the result will be non-negative.
1651 // If lhs is non-positive, the result will be non-positive.
1652 int64_t lower = lhs.lower() >= 0 ? 0 : -absBound;
1653 int64_t upper = lhs.upper() <= 0 ? 0 : absBound;
1654
1655 Range::FractionalPartFlag newCanHaveFractionalPart =
1656 Range::FractionalPartFlag(lhs.canHaveFractionalPart() ||
1657 rhs.canHaveFractionalPart());
1658
1659 // If the lhs can have the sign bit set and we can return a zero, it'll be a
1660 // negative zero.
1661 Range::NegativeZeroFlag newMayIncludeNegativeZero =
1662 Range::NegativeZeroFlag(lhs.canHaveSignBitSet());
1663
1664 setRange(new (alloc) Range(lower, upper, newCanHaveFractionalPart,
1665 newMayIncludeNegativeZero,
1666 std::min(lhs.exponent(), rhs.exponent())));
1667 }
1668
1669 void MDiv::computeRange(TempAllocator& alloc) {
1670 if (type() != MIRType::Int32 && type() != MIRType::Double) {
1671 return;
1672 }
1673 Range lhs(getOperand(0));
1674 Range rhs(getOperand(1));
1675
1676 // If either operand is a NaN, the result is NaN. This also conservatively
1677 // handles Infinity cases.
1678 if (!lhs.hasInt32Bounds() || !rhs.hasInt32Bounds()) {
1679 return;
1680 }
1681
1682 // Something simple for now: When dividing by a positive rhs, the result
1683 // won't be further from zero than lhs.
1684 if (lhs.lower() >= 0 && rhs.lower() >= 1) {
1685 setRange(new (alloc) Range(0, lhs.upper(), Range::IncludesFractionalParts,
1686 Range::IncludesNegativeZero, lhs.exponent()));
1687 } else if (unsigned_ && rhs.lower() >= 1) {
1688 // We shouldn't set the unsigned flag if the inputs can have
1689 // fractional parts.
1690 MOZ_ASSERT(!lhs.canHaveFractionalPart() && !rhs.canHaveFractionalPart());
1691 // We shouldn't set the unsigned flag if the inputs can be
1692 // negative zero.
1693 MOZ_ASSERT(!lhs.canBeNegativeZero() && !rhs.canBeNegativeZero());
1694 // Unsigned division by a non-zero rhs will return a uint32 value.
1695 setRange(Range::NewUInt32Range(alloc, 0, UINT32_MAX));
1696 }
1697 }
1698
1699 void MSqrt::computeRange(TempAllocator& alloc) {
1700 Range input(getOperand(0));
1701
1702 // If either operand is a NaN, the result is NaN. This also conservatively
1703 // handles Infinity cases.
1704 if (!input.hasInt32Bounds()) {
1705 return;
1706 }
1707
1708 // Sqrt of a negative non-zero value is NaN.
1709 if (input.lower() < 0) {
1710 return;
1711 }
1712
1713 // Something simple for now: When taking the sqrt of a positive value, the
1714 // result won't be further from zero than the input.
1715 // And, sqrt of an integer may have a fractional part.
1716 setRange(new (alloc) Range(0, input.upper(), Range::IncludesFractionalParts,
1717 input.canBeNegativeZero(), input.exponent()));
1718 }
1719
1720 void MToDouble::computeRange(TempAllocator& alloc) {
1721 setRange(new (alloc) Range(getOperand(0)));
1722 }
1723
1724 void MToFloat32::computeRange(TempAllocator& alloc) {}
1725
1726 void MTruncateToInt32::computeRange(TempAllocator& alloc) {
1727 Range* output = new (alloc) Range(getOperand(0));
1728 output->wrapAroundToInt32();
1729 setRange(output);
1730 }
1731
1732 void MToNumberInt32::computeRange(TempAllocator& alloc) {
1733 // No clamping since this computes the range *before* bailouts.
1734 setRange(new (alloc) Range(getOperand(0)));
1735 }
1736
1737 void MBooleanToInt32::computeRange(TempAllocator& alloc) {
1738 setRange(Range::NewUInt32Range(alloc, 0, 1));
1739 }
1740
1741 void MLimitedTruncate::computeRange(TempAllocator& alloc) {
1742 Range* output = new (alloc) Range(input());
1743 setRange(output);
1744 }
1745
1746 static Range* GetArrayBufferViewRange(TempAllocator& alloc, Scalar::Type type) {
1747 switch (type) {
1748 case Scalar::Uint8Clamped:
1749 case Scalar::Uint8:
1750 return Range::NewUInt32Range(alloc, 0, UINT8_MAX);
1751 case Scalar::Uint16:
1752 return Range::NewUInt32Range(alloc, 0, UINT16_MAX);
1753 case Scalar::Uint32:
1754 return Range::NewUInt32Range(alloc, 0, UINT32_MAX);
1755
1756 case Scalar::Int8:
1757 return Range::NewInt32Range(alloc, INT8_MIN, INT8_MAX);
1758 case Scalar::Int16:
1759 return Range::NewInt32Range(alloc, INT16_MIN, INT16_MAX);
1760 case Scalar::Int32:
1761 return Range::NewInt32Range(alloc, INT32_MIN, INT32_MAX);
1762
1763 case Scalar::BigInt64:
1764 case Scalar::BigUint64:
1765 case Scalar::Int64:
1766 case Scalar::Simd128:
1767 case Scalar::Float16:
1768 case Scalar::Float32:
1769 case Scalar::Float64:
1770 case Scalar::MaxTypedArrayViewType:
1771 break;
1772 }
1773 return nullptr;
1774 }
1775
1776 void MLoadUnboxedScalar::computeRange(TempAllocator& alloc) {
1777 // We have an Int32 type and if this is a UInt32 load it may produce a value
1778 // outside of our range, but we have a bailout to handle those cases.
1779 setRange(GetArrayBufferViewRange(alloc, storageType()));
1780 }
1781
1782 void MLoadDataViewElement::computeRange(TempAllocator& alloc) {
1783 // We have an Int32 type and if this is a UInt32 load it may produce a value
1784 // outside of our range, but we have a bailout to handle those cases.
1785 setRange(GetArrayBufferViewRange(alloc, storageType()));
1786 }
1787
1788 void MArrayLength::computeRange(TempAllocator& alloc) {
1789 // Array lengths can go up to UINT32_MAX. We will bail out if the array
1790 // length > INT32_MAX.
1791 MOZ_ASSERT(type() == MIRType::Int32);
1792 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1793 }
1794
1795 void MInitializedLength::computeRange(TempAllocator& alloc) {
1796 setRange(
1797 Range::NewUInt32Range(alloc, 0, NativeObject::MAX_DENSE_ELEMENTS_COUNT));
1798 }
1799
1800 void MArrayBufferViewLength::computeRange(TempAllocator& alloc) {
1801 if constexpr (ArrayBufferObject::ByteLengthLimit <= INT32_MAX) {
1802 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1803 }
1804 }
1805
1806 void MArrayBufferViewByteOffset::computeRange(TempAllocator& alloc) {
1807 if constexpr (ArrayBufferObject::ByteLengthLimit <= INT32_MAX) {
1808 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1809 }
1810 }
1811
1812 void MResizableTypedArrayByteOffsetMaybeOutOfBounds::computeRange(
1813 TempAllocator& alloc) {
1814 if constexpr (ArrayBufferObject::ByteLengthLimit <= INT32_MAX) {
1815 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1816 }
1817 }
1818
1819 void MResizableTypedArrayLength::computeRange(TempAllocator& alloc) {
1820 if constexpr (ArrayBufferObject::ByteLengthLimit <= INT32_MAX) {
1821 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1822 }
1823 }
1824
1825 void MResizableDataViewByteLength::computeRange(TempAllocator& alloc) {
1826 if constexpr (ArrayBufferObject::ByteLengthLimit <= INT32_MAX) {
1827 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1828 }
1829 }
1830
1831 void MTypedArrayElementSize::computeRange(TempAllocator& alloc) {
1832 constexpr auto MaxTypedArraySize = sizeof(double);
1833
1834 #define ASSERT_MAX_SIZE(_, T, N) \
1835 static_assert(sizeof(T) <= MaxTypedArraySize, \
1836 "unexpected typed array type exceeding 64-bits storage");
1837 JS_FOR_EACH_TYPED_ARRAY(ASSERT_MAX_SIZE)
1838 #undef ASSERT_MAX_SIZE
1839
1840 setRange(Range::NewUInt32Range(alloc, 0, MaxTypedArraySize));
1841 }
1842
1843 void MStringLength::computeRange(TempAllocator& alloc) {
1844 static_assert(JSString::MAX_LENGTH <= UINT32_MAX,
1845 "NewUInt32Range requires a uint32 value");
1846 setRange(Range::NewUInt32Range(alloc, 0, JSString::MAX_LENGTH));
1847 }
1848
1849 void MArgumentsLength::computeRange(TempAllocator& alloc) {
1850 // This is is a conservative upper bound on what |TooManyActualArguments|
1851 // checks. If exceeded, Ion will not be entered in the first place.
1852 static_assert(ARGS_LENGTH_MAX <= UINT32_MAX,
1853 "NewUInt32Range requires a uint32 value");
1854 setRange(Range::NewUInt32Range(alloc, 0, ARGS_LENGTH_MAX));
1855 }
1856
1857 void MBoundsCheck::computeRange(TempAllocator& alloc) {
1858 // Just transfer the incoming index range to the output. The length() is
1859 // also interesting, but it is handled as a bailout check, and we're
1860 // computing a pre-bailout range here.
1861 setRange(new (alloc) Range(index()));
1862 }
1863
1864 void MSpectreMaskIndex::computeRange(TempAllocator& alloc) {
1865 // Just transfer the incoming index range to the output for now.
1866 setRange(new (alloc) Range(index()));
1867 }
1868
1869 void MInt32ToIntPtr::computeRange(TempAllocator& alloc) {
1870 setRange(new (alloc) Range(input()));
1871 }
1872
1873 void MNonNegativeIntPtrToInt32::computeRange(TempAllocator& alloc) {
1874 // We will bail out if the IntPtr value > INT32_MAX.
1875 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1876 }
1877
1878 void MArrayPush::computeRange(TempAllocator& alloc) {
1879 // MArrayPush returns the new array length. It bails out if the new length
1880 // doesn't fit in an Int32.
1881 MOZ_ASSERT(type() == MIRType::Int32);
1882 setRange(Range::NewUInt32Range(alloc, 0, INT32_MAX));
1883 }
1884
1885 void MMathFunction::computeRange(TempAllocator& alloc) {
1886 Range opRange(getOperand(0));
1887 switch (function()) {
1888 case UnaryMathFunction::SinNative:
1889 case UnaryMathFunction::SinFdlibm:
1890 case UnaryMathFunction::CosNative:
1891 case UnaryMathFunction::CosFdlibm:
1892 if (!opRange.canBeInfiniteOrNaN()) {
1893 setRange(Range::NewDoubleRange(alloc, -1.0, 1.0));
1894 }
1895 break;
1896 default:
1897 break;
1898 }
1899 }
1900
1901 void MSign::computeRange(TempAllocator& alloc) {
1902 Range opRange(getOperand(0));
1903 setRange(Range::sign(alloc, &opRange));
1904 }
1905
1906 void MRandom::computeRange(TempAllocator& alloc) {
1907 Range* r = Range::NewDoubleRange(alloc, 0.0, 1.0);
1908
1909 // Random never returns negative zero.
1910 r->refineToExcludeNegativeZero();
1911
1912 setRange(r);
1913 }
1914
1915 void MNaNToZero::computeRange(TempAllocator& alloc) {
1916 Range other(input());
1917 setRange(Range::NaNToZero(alloc, &other));
1918 }
1919
1920 ///////////////////////////////////////////////////////////////////////////////
1921 // Range Analysis
1922 ///////////////////////////////////////////////////////////////////////////////
1923
1924 static BranchDirection NegateBranchDirection(BranchDirection dir) {
1925 return (dir == FALSE_BRANCH) ? TRUE_BRANCH : FALSE_BRANCH;
1926 }
1927
1928 bool RangeAnalysis::analyzeLoop(const MBasicBlock* header) {
1929 MOZ_ASSERT(header->hasUniqueBackedge());
1930
1931 // Try to compute an upper bound on the number of times the loop backedge
1932 // will be taken. Look for tests that dominate the backedge and which have
1933 // an edge leaving the loop body.
1934 MBasicBlock* backedge = header->backedge();
1935
1936 // Ignore trivial infinite loops.
1937 if (backedge == header) {
1938 return true;
1939 }
1940
1941 bool canOsr;
1942 size_t numBlocks = MarkLoopBlocks(graph_, header, &canOsr);
1943
1944 // Ignore broken loops.
1945 if (numBlocks == 0) {
1946 return true;
1947 }
1948
1949 LoopIterationBound* iterationBound = nullptr;
1950
1951 MBasicBlock* block = backedge;
1952 do {
1953 BranchDirection direction;
1954 MTest* branch = block->immediateDominatorBranch(&direction);
1955
1956 if (block == block->immediateDominator()) {
1957 break;
1958 }
1959
1960 block = block->immediateDominator();
1961
1962 if (branch) {
1963 direction = NegateBranchDirection(direction);
1964 MBasicBlock* otherBlock = branch->branchSuccessor(direction);
1965 if (!otherBlock->isMarked()) {
1966 if (!alloc().ensureBallast()) {
1967 return false;
1968 }
1969 iterationBound = analyzeLoopIterationCount(header, branch, direction);
1970 if (iterationBound) {
1971 break;
1972 }
1973 }
1974 }
1975 } while (block != header);
1976
1977 if (!iterationBound) {
1978 UnmarkLoopBlocks(graph_, header);
1979 return true;
1980 }
1981
1982 if (!loopIterationBounds.append(iterationBound)) {
1983 return false;
1984 }
1985
1986 #ifdef DEBUG
1987 if (JitSpewEnabled(JitSpew_Range)) {
1988 Sprinter sp(GetJitContext()->cx);
1989 if (!sp.init()) {
1990 return false;
1991 }
1992 iterationBound->boundSum.dump(sp);
1993 JS::UniqueChars str = sp.release();
1994 if (!str) {
1995 return false;
1996 }
1997 JitSpew(JitSpew_Range, "computed symbolic bound on backedges: %s",
1998 str.get());
1999 }
2000 #endif
2001
2002 // Try to compute symbolic bounds for the phi nodes at the head of this
2003 // loop, expressed in terms of the iteration bound just computed.
2004
2005 for (MPhiIterator iter(header->phisBegin()); iter != header->phisEnd();
2006 iter++) {
2007 analyzeLoopPhi(iterationBound, *iter);
2008 }
2009
2010 if (!mir->compilingWasm() && !mir->outerInfo().hadBoundsCheckBailout()) {
2011 // Try to hoist any bounds checks from the loop using symbolic bounds.
2012
2013 Vector<MBoundsCheck*, 0, JitAllocPolicy> hoistedChecks(alloc());
2014
2015 for (ReversePostorderIterator iter(graph_.rpoBegin(header));
2016 iter != graph_.rpoEnd(); iter++) {
2017 if (mir->shouldCancel("RangeAnalysis analyzeLoop")) {
2018 return false;
2019 }
2020
2021 MBasicBlock* block = *iter;
2022 if (!block->isMarked()) {
2023 continue;
2024 }
2025
2026 for (MDefinitionIterator iter(block); iter; iter++) {
2027 MDefinition* def = *iter;
2028 if (def->isBoundsCheck() && def->isMovable()) {
2029 if (!alloc().ensureBallast()) {
2030 return false;
2031 }
2032 if (tryHoistBoundsCheck(header, def->toBoundsCheck())) {
2033 if (!hoistedChecks.append(def->toBoundsCheck())) {
2034 return false;
2035 }
2036 }
2037 }
2038 }
2039 }
2040
2041 // Note: replace all uses of the original bounds check with the
2042 // actual index. This is usually done during bounds check elimination,
2043 // but in this case it's safe to do it here since the load/store is
2044 // definitely not loop-invariant, so we will never move it before
2045 // one of the bounds checks we just added.
2046 for (size_t i = 0; i < hoistedChecks.length(); i++) {
2047 MBoundsCheck* ins = hoistedChecks[i];
2048 ins->replaceAllUsesWith(ins->index());
2049 ins->block()->discard(ins);
2050 }
2051 }
2052
2053 UnmarkLoopBlocks(graph_, header);
2054 return true;
2055 }
2056
2057 // Unbox beta nodes in order to hoist instruction properly, and not be limited
2058 // by the beta nodes which are added after each branch.
2059 static inline MDefinition* DefinitionOrBetaInputDefinition(MDefinition* ins) {
2060 while (ins->isBeta()) {
2061 ins = ins->toBeta()->input();
2062 }
2063 return ins;
2064 }
2065
2066 LoopIterationBound* RangeAnalysis::analyzeLoopIterationCount(
2067 const MBasicBlock* header, const MTest* test, BranchDirection direction) {
2068 SimpleLinearSum lhs(nullptr, 0);
2069 MDefinition* rhs;
2070 bool lessEqual;
2071 if (!ExtractLinearInequality(test, direction, &lhs, &rhs, &lessEqual)) {
2072 return nullptr;
2073 }
2074
2075 // Ensure the rhs is a loop invariant term.
2076 if (rhs && rhs->block()->isMarked()) {
2077 if (lhs.term && lhs.term->block()->isMarked()) {
2078 return nullptr;
2079 }
2080 MDefinition* temp = lhs.term;
2081 lhs.term = rhs;
2082 rhs = temp;
2083 if (!SafeSub(0, lhs.constant, &lhs.constant)) {
2084 return nullptr;
2085 }
2086 lessEqual = !lessEqual;
2087 }
2088
2089 MOZ_ASSERT_IF(rhs, !rhs->block()->isMarked());
2090
2091 // Ensure the lhs is a phi node from the start of the loop body.
2092 if (!lhs.term || !lhs.term->isPhi() || lhs.term->block() != header) {
2093 return nullptr;
2094 }
2095
2096 // Check that the value of the lhs changes by a constant amount with each
2097 // loop iteration. This requires that the lhs be written in every loop
2098 // iteration with a value that is a constant difference from its value at
2099 // the start of the iteration.
2100
2101 if (lhs.term->toPhi()->numOperands() != 2) {
2102 return nullptr;
2103 }
2104
2105 // The first operand of the phi should be the lhs' value at the start of
2106 // the first executed iteration, and not a value written which could
2107 // replace the second operand below during the middle of execution.
2108 MDefinition* lhsInitial = lhs.term->toPhi()->getLoopPredecessorOperand();
2109 if (lhsInitial->block()->isMarked()) {
2110 return nullptr;
2111 }
2112
2113 // The second operand of the phi should be a value written by an add/sub
2114 // in every loop iteration, i.e. in a block which dominates the backedge.
2115 MDefinition* lhsWrite = DefinitionOrBetaInputDefinition(
2116 lhs.term->toPhi()->getLoopBackedgeOperand());
2117 if (!lhsWrite->isAdd() && !lhsWrite->isSub()) {
2118 return nullptr;
2119 }
2120 if (!lhsWrite->block()->isMarked()) {
2121 return nullptr;
2122 }
2123 MBasicBlock* bb = header->backedge();
2124 for (; bb != lhsWrite->block() && bb != header;
2125 bb = bb->immediateDominator()) {
2126 }
2127 if (bb != lhsWrite->block()) {
2128 return nullptr;
2129 }
2130
2131 SimpleLinearSum lhsModified = ExtractLinearSum(lhsWrite);
2132
2133 // Check that the value of the lhs at the backedge is of the form
2134 // 'old(lhs) + N'. We can be sure that old(lhs) is the value at the start
2135 // of the iteration, and not that written to lhs in a previous iteration,
2136 // as such a previous value could not appear directly in the addition:
2137 // it could not be stored in lhs as the lhs add/sub executes in every
2138 // iteration, and if it were stored in another variable its use here would
2139 // be as an operand to a phi node for that variable.
2140 if (lhsModified.term != lhs.term) {
2141 return nullptr;
2142 }
2143
2144 LinearSum iterationBound(alloc());
2145
2146 if (lhsModified.constant == 1 && !lessEqual) {
2147 // The value of lhs is 'initial(lhs) + iterCount' and this will end
2148 // execution of the loop if 'lhs + lhsN >= rhs'. Thus, an upper bound
2149 // on the number of backedges executed is:
2150 //
2151 // initial(lhs) + iterCount + lhsN == rhs
2152 // iterCount == rhsN - initial(lhs) - lhsN
2153
2154 if (rhs) {
2155 if (!iterationBound.add(rhs, 1)) {
2156 return nullptr;
2157 }
2158 }
2159 if (!iterationBound.add(lhsInitial, -1)) {
2160 return nullptr;
2161 }
2162
2163 int32_t lhsConstant;
2164 if (!SafeSub(0, lhs.constant, &lhsConstant)) {
2165 return nullptr;
2166 }
2167 if (!iterationBound.add(lhsConstant)) {
2168 return nullptr;
2169 }
2170 } else if (lhsModified.constant == -1 && lessEqual) {
2171 // The value of lhs is 'initial(lhs) - iterCount'. Similar to the above
2172 // case, an upper bound on the number of backedges executed is:
2173 //
2174 // initial(lhs) - iterCount + lhsN == rhs
2175 // iterCount == initial(lhs) - rhs + lhsN
2176
2177 if (!iterationBound.add(lhsInitial, 1)) {
2178 return nullptr;
2179 }
2180 if (rhs) {
2181 if (!iterationBound.add(rhs, -1)) {
2182 return nullptr;
2183 }
2184 }
2185 if (!iterationBound.add(lhs.constant)) {
2186 return nullptr;
2187 }
2188 } else {
2189 return nullptr;
2190 }
2191
2192 return new (alloc()) LoopIterationBound(test, iterationBound);
2193 }
2194
2195 void RangeAnalysis::analyzeLoopPhi(const LoopIterationBound* loopBound,
2196 MPhi* phi) {
2197 // Given a bound on the number of backedges taken, compute an upper and
2198 // lower bound for a phi node that may change by a constant amount each
2199 // iteration. Unlike for the case when computing the iteration bound
2200 // itself, the phi does not need to change the same amount every iteration,
2201 // but is required to change at most N and be either nondecreasing or
2202 // nonincreasing.
2203
2204 MOZ_ASSERT(phi->numOperands() == 2);
2205
2206 MDefinition* initial = phi->getLoopPredecessorOperand();
2207 if (initial->block()->isMarked()) {
2208 return;
2209 }
2210
2211 SimpleLinearSum modified =
2212 ExtractLinearSum(phi->getLoopBackedgeOperand(), MathSpace::Infinite);
2213
2214 if (modified.term != phi || modified.constant == 0) {
2215 return;
2216 }
2217
2218 if (!phi->range()) {
2219 phi->setRange(new (alloc()) Range(phi));
2220 }
2221
2222 LinearSum initialSum(alloc());
2223 if (!initialSum.add(initial, 1)) {
2224 return;
2225 }
2226
2227 // The phi may change by N each iteration, and is either nondecreasing or
2228 // nonincreasing. initial(phi) is either a lower or upper bound for the
2229 // phi, and initial(phi) + loopBound * N is either an upper or lower bound,
2230 // at all points within the loop, provided that loopBound >= 0.
2231 //
2232 // We are more interested, however, in the bound for phi at points
2233 // dominated by the loop bound's test; if the test dominates e.g. a bounds
2234 // check we want to hoist from the loop, using the value of the phi at the
2235 // head of the loop for this will usually be too imprecise to hoist the
2236 // check. These points will execute only if the backedge executes at least
2237 // one more time (as the test passed and the test dominates the backedge),
2238 // so we know both that loopBound >= 1 and that the phi's value has changed
2239 // at most loopBound - 1 times. Thus, another upper or lower bound for the
2240 // phi is initial(phi) + (loopBound - 1) * N, without requiring us to
2241 // ensure that loopBound >= 0.
2242
2243 LinearSum limitSum(loopBound->boundSum);
2244 if (!limitSum.multiply(modified.constant) || !limitSum.add(initialSum)) {
2245 return;
2246 }
2247
2248 int32_t negativeConstant;
2249 if (!SafeSub(0, modified.constant, &negativeConstant) ||
2250 !limitSum.add(negativeConstant)) {
2251 return;
2252 }
2253
2254 Range* initRange = initial->range();
2255 if (modified.constant > 0) {
2256 if (initRange && initRange->hasInt32LowerBound()) {
2257 phi->range()->refineLower(initRange->lower());
2258 }
2259 phi->range()->setSymbolicLower(
2260 SymbolicBound::New(alloc(), nullptr, initialSum));
2261 phi->range()->setSymbolicUpper(
2262 SymbolicBound::New(alloc(), loopBound, limitSum));
2263 } else {
2264 if (initRange && initRange->hasInt32UpperBound()) {
2265 phi->range()->refineUpper(initRange->upper());
2266 }
2267 phi->range()->setSymbolicUpper(
2268 SymbolicBound::New(alloc(), nullptr, initialSum));
2269 phi->range()->setSymbolicLower(
2270 SymbolicBound::New(alloc(), loopBound, limitSum));
2271 }
2272
2273 JitSpew(JitSpew_Range, "added symbolic range on %u", phi->id());
2274 SpewRange(phi);
2275 }
2276
2277 // Whether bound is valid at the specified bounds check instruction in a loop,
2278 // and may be used to hoist ins.
2279 static inline bool SymbolicBoundIsValid(const MBasicBlock* header,
2280 const MBoundsCheck* ins,
2281 const SymbolicBound* bound) {
2282 if (!bound->loop) {
2283 return true;
2284 }
2285 if (ins->block() == header) {
2286 return false;
2287 }
2288 MBasicBlock* bb = ins->block()->immediateDominator();
2289 while (bb != header && bb != bound->loop->test->block()) {
2290 bb = bb->immediateDominator();
2291 }
2292 return bb == bound->loop->test->block();
2293 }
2294
2295 bool RangeAnalysis::tryHoistBoundsCheck(const MBasicBlock* header,
2296 const MBoundsCheck* ins) {
2297 // The bounds check's length must be loop invariant or a constant.
2298 MDefinition* length = DefinitionOrBetaInputDefinition(ins->length());
2299 if (length->block()->isMarked() && !length->isConstant()) {
2300 return false;
2301 }
2302
2303 // The bounds check's index should not be loop invariant (else we would
2304 // already have hoisted it during LICM).
2305 SimpleLinearSum index = ExtractLinearSum(ins->index());
2306 if (!index.term || !index.term->block()->isMarked()) {
2307 return false;
2308 }
2309
2310 // Check for a symbolic lower and upper bound on the index. If either
2311 // condition depends on an iteration bound for the loop, only hoist if
2312 // the bounds check is dominated by the iteration bound's test.
2313 if (!index.term->range()) {
2314 return false;
2315 }
2316 const SymbolicBound* lower = index.term->range()->symbolicLower();
2317 if (!lower || !SymbolicBoundIsValid(header, ins, lower)) {
2318 return false;
2319 }
2320 const SymbolicBound* upper = index.term->range()->symbolicUpper();
2321 if (!upper || !SymbolicBoundIsValid(header, ins, upper)) {
2322 return false;
2323 }
2324
2325 MBasicBlock* preLoop = header->loopPredecessor();
2326 MOZ_ASSERT(!preLoop->isMarked());
2327
2328 MDefinition* lowerTerm = ConvertLinearSum(alloc(), preLoop, lower->sum,
2329 BailoutKind::HoistBoundsCheck);
2330 if (!lowerTerm) {
2331 return false;
2332 }
2333
2334 MDefinition* upperTerm = ConvertLinearSum(alloc(), preLoop, upper->sum,
2335 BailoutKind::HoistBoundsCheck);
2336 if (!upperTerm) {
2337 return false;
2338 }
2339
2340 // We are checking that index + indexConstant >= 0, and know that
2341 // index >= lowerTerm + lowerConstant. Thus, check that:
2342 //
2343 // lowerTerm + lowerConstant + indexConstant >= 0
2344 // lowerTerm >= -lowerConstant - indexConstant
2345
2346 int32_t lowerConstant = 0;
2347 if (!SafeSub(lowerConstant, index.constant, &lowerConstant)) {
2348 return false;
2349 }
2350 if (!SafeSub(lowerConstant, lower->sum.constant(), &lowerConstant)) {
2351 return false;
2352 }
2353
2354 // We are checking that index < boundsLength, and know that
2355 // index <= upperTerm + upperConstant. Thus, check that:
2356 //
2357 // upperTerm + upperConstant < boundsLength
2358
2359 int32_t upperConstant = index.constant;
2360 if (!SafeAdd(upper->sum.constant(), upperConstant, &upperConstant)) {
2361 return false;
2362 }
2363
2364 // Hoist the loop invariant lower bounds checks.
2365 MBoundsCheckLower* lowerCheck = MBoundsCheckLower::New(alloc(), lowerTerm);
2366 lowerCheck->setMinimum(lowerConstant);
2367 lowerCheck->computeRange(alloc());
2368 lowerCheck->collectRangeInfoPreTrunc();
2369 lowerCheck->setBailoutKind(BailoutKind::HoistBoundsCheck);
2370 preLoop->insertBefore(preLoop->lastIns(), lowerCheck);
2371
2372 // A common pattern for iterating over typed arrays is this:
2373 //
2374 // for (var i = 0; i < ta.length; i++) {
2375 // use ta[i];
2376 // }
2377 //
2378 // Here |upperTerm| (= ta.length) is a NonNegativeIntPtrToInt32 instruction.
2379 // Unwrap this if |length| is also an IntPtr so that we don't add an
2380 // unnecessary bounds check and Int32ToIntPtr below.
2381 if (upperTerm->isNonNegativeIntPtrToInt32() &&
2382 length->type() == MIRType::IntPtr) {
2383 upperTerm = upperTerm->toNonNegativeIntPtrToInt32()->input();
2384 }
2385
2386 // Hoist the loop invariant upper bounds checks.
2387 if (upperTerm != length || upperConstant >= 0) {
2388 // Hoist the bound check's length if it isn't already loop invariant.
2389 if (length->block()->isMarked()) {
2390 MOZ_ASSERT(length->isConstant());
2391 MInstruction* lengthIns = length->toInstruction();
2392 lengthIns->block()->moveBefore(preLoop->lastIns(), lengthIns);
2393 }
2394
2395 // If the length is IntPtr, convert the upperTerm to that as well for the
2396 // bounds check.
2397 if (length->type() == MIRType::IntPtr &&
2398 upperTerm->type() == MIRType::Int32) {
2399 upperTerm = MInt32ToIntPtr::New(alloc(), upperTerm);
2400 upperTerm->computeRange(alloc());
2401 upperTerm->collectRangeInfoPreTrunc();
2402 preLoop->insertBefore(preLoop->lastIns(), upperTerm->toInstruction());
2403 }
2404
2405 MBoundsCheck* upperCheck = MBoundsCheck::New(alloc(), upperTerm, length);
2406 upperCheck->setMinimum(upperConstant);
2407 upperCheck->setMaximum(upperConstant);
2408 upperCheck->computeRange(alloc());
2409 upperCheck->collectRangeInfoPreTrunc();
2410 upperCheck->setBailoutKind(BailoutKind::HoistBoundsCheck);
2411 preLoop->insertBefore(preLoop->lastIns(), upperCheck);
2412 }
2413
2414 return true;
2415 }
2416
2417 bool RangeAnalysis::analyze() {
2418 JitSpew(JitSpew_Range, "Doing range propagation");
2419
2420 for (ReversePostorderIterator iter(graph_.rpoBegin());
2421 iter != graph_.rpoEnd(); iter++) {
2422 if (mir->shouldCancel("RangeAnalysis analyze")) {
2423 return false;
2424 }
2425
2426 MBasicBlock* block = *iter;
2427 // No blocks are supposed to be unreachable, except when we have an OSR
2428 // block, in which case the Value Numbering phase add fixup blocks which
2429 // are unreachable.
2430 MOZ_ASSERT(!block->unreachable() || graph_.osrBlock());
2431
2432 // If the block's immediate dominator is unreachable, the block is
2433 // unreachable. Iterating in RPO, we'll always see the immediate
2434 // dominator before the block.
2435 if (block->immediateDominator()->unreachable()) {
2436 block->setUnreachableUnchecked();
2437 continue;
2438 }
2439
2440 for (MDefinitionIterator iter(block); iter; iter++) {
2441 MDefinition* def = *iter;
2442 if (!alloc().ensureBallast()) {
2443 return false;
2444 }
2445
2446 def->computeRange(alloc());
2447 JitSpew(JitSpew_Range, "computing range on %u", def->id());
2448 SpewRange(def);
2449 }
2450
2451 // Beta node range analysis may have marked this block unreachable. If
2452 // so, it's no longer interesting to continue processing it.
2453 if (block->unreachable()) {
2454 continue;
2455 }
2456
2457 if (block->isLoopHeader()) {
2458 if (!analyzeLoop(block)) {
2459 return false;
2460 }
2461 }
2462
2463 // First pass at collecting range info - while the beta nodes are still
2464 // around and before truncation.
2465 for (MInstructionIterator iter(block->begin()); iter != block->end();
2466 iter++) {
2467 iter->collectRangeInfoPreTrunc();
2468 }
2469 }
2470
2471 return true;
2472 }
2473
2474 bool RangeAnalysis::addRangeAssertions() {
2475 if (!JitOptions.checkRangeAnalysis) {
2476 return true;
2477 }
2478
2479 // Check the computed range for this instruction, if the option is set. Note
2480 // that this code is quite invasive; it adds numerous additional
2481 // instructions for each MInstruction with a computed range, and it uses
2482 // registers, so it also affects register allocation.
2483 for (ReversePostorderIterator iter(graph_.rpoBegin());
2484 iter != graph_.rpoEnd(); iter++) {
2485 MBasicBlock* block = *iter;
2486
2487 // Do not add assertions in unreachable blocks.
2488 if (block->unreachable()) {
2489 continue;
2490 }
2491
2492 for (MDefinitionIterator iter(block); iter; iter++) {
2493 MDefinition* ins = *iter;
2494
2495 // Perform range checking for all numeric and numeric-like types.
2496 if (!IsNumberType(ins->type()) && ins->type() != MIRType::Boolean &&
2497 ins->type() != MIRType::Value && ins->type() != MIRType::IntPtr) {
2498 continue;
2499 }
2500
2501 // MIsNoIter is fused with the MTest that follows it and emitted as
2502 // LIsNoIterAndBranch. Similarly, MIteratorHasIndices is fused to
2503 // become LIteratorHasIndicesAndBranch. Skip them to avoid complicating
2504 // lowering.
2505 if (ins->isIsNoIter() || ins->isIteratorHasIndices()) {
2506 MOZ_ASSERT(ins->hasOneUse());
2507 continue;
2508 }
2509
2510 Range r(ins);
2511
2512 MOZ_ASSERT_IF(ins->type() == MIRType::Int64, r.isUnknown());
2513
2514 // Don't insert assertions if there's nothing interesting to assert.
2515 if (r.isUnknown() ||
2516 (ins->type() == MIRType::Int32 && r.isUnknownInt32())) {
2517 continue;
2518 }
2519
2520 // Don't add a use to an instruction that is recovered on bailout.
2521 if (ins->isRecoveredOnBailout()) {
2522 continue;
2523 }
2524
2525 if (!alloc().ensureBallast()) {
2526 return false;
2527 }
2528 MAssertRange* guard =
2529 MAssertRange::New(alloc(), ins, new (alloc()) Range(r));
2530
2531 // Beta nodes and interrupt checks are required to be located at the
2532 // beginnings of basic blocks, so we must insert range assertions
2533 // after any such instructions.
2534 MInstruction* insertAt = nullptr;
2535 if (block->graph().osrBlock() == block) {
2536 insertAt = ins->toInstruction();
2537 } else {
2538 insertAt = block->safeInsertTop(ins);
2539 }
2540
2541 if (insertAt == *iter) {
2542 block->insertAfter(insertAt, guard);
2543 } else {
2544 block->insertBefore(insertAt, guard);
2545 }
2546 }
2547 }
2548
2549 return true;
2550 }
2551
2552 ///////////////////////////////////////////////////////////////////////////////
2553 // Range based Truncation
2554 ///////////////////////////////////////////////////////////////////////////////
2555
2556 void Range::clampToInt32() {
2557 if (isInt32()) {
2558 return;
2559 }
2560 int32_t l = hasInt32LowerBound() ? lower() : JSVAL_INT_MIN;
2561 int32_t h = hasInt32UpperBound() ? upper() : JSVAL_INT_MAX;
2562 setInt32(l, h);
2563 }
2564
2565 void Range::wrapAroundToInt32() {
2566 if (!hasInt32Bounds()) {
2567 setInt32(JSVAL_INT_MIN, JSVAL_INT_MAX);
2568 } else if (canHaveFractionalPart()) {
2569 // Clearing the fractional field may provide an opportunity to refine
2570 // lower_ or upper_.
2571 canHaveFractionalPart_ = ExcludesFractionalParts;
2572 canBeNegativeZero_ = ExcludesNegativeZero;
2573 refineInt32BoundsByExponent(max_exponent_, &lower_, &hasInt32LowerBound_,
2574 &upper_, &hasInt32UpperBound_);
2575
2576 assertInvariants();
2577 } else {
2578 // If nothing else, we can clear the negative zero flag.
2579 canBeNegativeZero_ = ExcludesNegativeZero;
2580 }
2581 MOZ_ASSERT(isInt32());
2582 }
2583
2584 void Range::wrapAroundToShiftCount() {
2585 wrapAroundToInt32();
2586 if (lower() < 0 || upper() >= 32) {
2587 setInt32(0, 31);
2588 }
2589 }
2590
2591 void Range::wrapAroundToBoolean() {
2592 wrapAroundToInt32();
2593 if (!isBoolean()) {
2594 setInt32(0, 1);
2595 }
2596 MOZ_ASSERT(isBoolean());
2597 }
2598
2599 bool MDefinition::canTruncate() const {
2600 // No procedure defined for truncating this instruction.
2601 return false;
2602 }
2603
2604 void MDefinition::truncate(TruncateKind kind) {
2605 MOZ_CRASH("No procedure defined for truncating this instruction.");
2606 }
2607
2608 bool MConstant::canTruncate() const { return IsFloatingPointType(type()); }
2609
2610 void MConstant::truncate(TruncateKind kind) {
2611 MOZ_ASSERT(canTruncate());
2612
2613 // Truncate the double to int, since all uses truncates it.
2614 int32_t res = ToInt32(numberToDouble());
2615 payload_.asBits = 0;
2616 payload_.i32 = res;
2617 setResultType(MIRType::Int32);
2618 if (range()) {
2619 range()->setInt32(res, res);
2620 }
2621 }
2622
2623 bool MPhi::canTruncate() const {
2624 return type() == MIRType::Double || type() == MIRType::Int32;
2625 }
2626
2627 void MPhi::truncate(TruncateKind kind) {
2628 MOZ_ASSERT(canTruncate());
2629 truncateKind_ = kind;
2630 setResultType(MIRType::Int32);
2631 if (kind >= TruncateKind::IndirectTruncate && range()) {
2632 range()->wrapAroundToInt32();
2633 }
2634 }
2635
2636 bool MAdd::canTruncate() const {
2637 return type() == MIRType::Double || type() == MIRType::Int32;
2638 }
2639
2640 void MAdd::truncate(TruncateKind kind) {
2641 MOZ_ASSERT(canTruncate());
2642
2643 // Remember analysis, needed for fallible checks.
2644 setTruncateKind(kind);
2645
2646 setSpecialization(MIRType::Int32);
2647 if (truncateKind() >= TruncateKind::IndirectTruncate && range()) {
2648 range()->wrapAroundToInt32();
2649 }
2650 }
2651
2652 bool MSub::canTruncate() const {
2653 return type() == MIRType::Double || type() == MIRType::Int32;
2654 }
2655
2656 void MSub::truncate(TruncateKind kind) {
2657 MOZ_ASSERT(canTruncate());
2658
2659 // Remember analysis, needed for fallible checks.
2660 setTruncateKind(kind);
2661 setSpecialization(MIRType::Int32);
2662 if (truncateKind() >= TruncateKind::IndirectTruncate && range()) {
2663 range()->wrapAroundToInt32();
2664 }
2665 }
2666
2667 bool MMul::canTruncate() const {
2668 return type() == MIRType::Double || type() == MIRType::Int32;
2669 }
2670
2671 void MMul::truncate(TruncateKind kind) {
2672 MOZ_ASSERT(canTruncate());
2673
2674 // Remember analysis, needed for fallible checks.
2675 setTruncateKind(kind);
2676 setSpecialization(MIRType::Int32);
2677 if (truncateKind() >= TruncateKind::IndirectTruncate) {
2678 setCanBeNegativeZero(false);
2679 if (range()) {
2680 range()->wrapAroundToInt32();
2681 }
2682 }
2683 }
2684
2685 bool MDiv::canTruncate() const {
2686 return type() == MIRType::Double || type() == MIRType::Int32;
2687 }
2688
2689 void MDiv::truncate(TruncateKind kind) {
2690 MOZ_ASSERT(canTruncate());
2691
2692 // Remember analysis, needed for fallible checks.
2693 setTruncateKind(kind);
2694 setSpecialization(MIRType::Int32);
2695
2696 // Divisions where the lhs and rhs are unsigned and the result is
2697 // truncated can be lowered more efficiently.
2698 if (unsignedOperands()) {
2699 replaceWithUnsignedOperands();
2700 unsigned_ = true;
2701 }
2702 }
2703
2704 bool MMod::canTruncate() const {
2705 return type() == MIRType::Double || type() == MIRType::Int32;
2706 }
2707
2708 void MMod::truncate(TruncateKind kind) {
2709 // As for division, handle unsigned modulus with a truncated result.
2710 MOZ_ASSERT(canTruncate());
2711
2712 // Remember analysis, needed for fallible checks.
2713 setTruncateKind(kind);
2714 setSpecialization(MIRType::Int32);
2715
2716 if (unsignedOperands()) {
2717 replaceWithUnsignedOperands();
2718 unsigned_ = true;
2719 }
2720 }
2721
2722 bool MToDouble::canTruncate() const {
2723 MOZ_ASSERT(type() == MIRType::Double);
2724 return true;
2725 }
2726
2727 void MToDouble::truncate(TruncateKind kind) {
2728 MOZ_ASSERT(canTruncate());
2729 setTruncateKind(kind);
2730
2731 // We use the return type to flag that this MToDouble should be replaced by
2732 // a MTruncateToInt32 when modifying the graph.
2733 setResultType(MIRType::Int32);
2734 if (truncateKind() >= TruncateKind::IndirectTruncate) {
2735 if (range()) {
2736 range()->wrapAroundToInt32();
2737 }
2738 }
2739 }
2740
2741 bool MLimitedTruncate::canTruncate() const { return true; }
2742
2743 void MLimitedTruncate::truncate(TruncateKind kind) {
2744 MOZ_ASSERT(canTruncate());
2745 setTruncateKind(kind);
2746 setResultType(MIRType::Int32);
2747 if (kind >= TruncateKind::IndirectTruncate && range()) {
2748 range()->wrapAroundToInt32();
2749 }
2750 }
2751
2752 bool MCompare::canTruncate() const {
2753 if (!isDoubleComparison()) {
2754 return false;
2755 }
2756
2757 // If both operands are naturally in the int32 range, we can convert from
2758 // a double comparison to being an int32 comparison.
2759 if (!Range(lhs()).isInt32() || !Range(rhs()).isInt32()) {
2760 return false;
2761 }
2762
2763 return true;
2764 }
2765
2766 void MCompare::truncate(TruncateKind kind) {
2767 MOZ_ASSERT(canTruncate());
2768 compareType_ = Compare_Int32;
2769
2770 // Truncating the operands won't change their value because we don't force a
2771 // truncation, but it will change their type, which we need because we
2772 // now expect integer inputs.
2773 truncateOperands_ = true;
2774 }
2775
2776 TruncateKind MDefinition::operandTruncateKind(size_t index) const {
2777 // Generic routine: We don't know anything.
2778 return TruncateKind::NoTruncate;
2779 }
2780
2781 TruncateKind MPhi::operandTruncateKind(size_t index) const {
2782 // The truncation applied to a phi is effectively applied to the phi's
2783 // operands.
2784 return truncateKind_;
2785 }
2786
2787 TruncateKind MTruncateToInt32::operandTruncateKind(size_t index) const {
2788 // This operator is an explicit truncate to int32.
2789 return TruncateKind::Truncate;
2790 }
2791
2792 TruncateKind MBinaryBitwiseInstruction::operandTruncateKind(
2793 size_t index) const {
2794 // The bitwise operators truncate to int32.
2795 return TruncateKind::Truncate;
2796 }
2797
2798 TruncateKind MLimitedTruncate::operandTruncateKind(size_t index) const {
2799 return std::min(truncateKind(), truncateLimit_);
2800 }
2801
2802 TruncateKind MAdd::operandTruncateKind(size_t index) const {
2803 // This operator is doing some arithmetic. If its result is truncated,
2804 // it's an indirect truncate for its operands.
2805 return std::min(truncateKind(), TruncateKind::IndirectTruncate);
2806 }
2807
2808 TruncateKind MSub::operandTruncateKind(size_t index) const {
2809 // See the comment in MAdd::operandTruncateKind.
2810 return std::min(truncateKind(), TruncateKind::IndirectTruncate);
2811 }
2812
2813 TruncateKind MMul::operandTruncateKind(size_t index) const {
2814 // See the comment in MAdd::operandTruncateKind.
2815 return std::min(truncateKind(), TruncateKind::IndirectTruncate);
2816 }
2817
2818 TruncateKind MToDouble::operandTruncateKind(size_t index) const {
2819 // MToDouble propagates its truncate kind to its operand.
2820 return truncateKind();
2821 }
2822
2823 TruncateKind MStoreUnboxedScalar::operandTruncateKind(size_t index) const {
2824 // An integer store truncates the stored value.
2825 return (index == 2 && isIntegerWrite()) ? TruncateKind::Truncate
2826 : TruncateKind::NoTruncate;
2827 }
2828
2829 TruncateKind MStoreDataViewElement::operandTruncateKind(size_t index) const {
2830 // An integer store truncates the stored value.
2831 return (index == 2 && isIntegerWrite()) ? TruncateKind::Truncate
2832 : TruncateKind::NoTruncate;
2833 }
2834
2835 TruncateKind MStoreTypedArrayElementHole::operandTruncateKind(
2836 size_t index) const {
2837 // An integer store truncates the stored value.
2838 return (index == 3 && isIntegerWrite()) ? TruncateKind::Truncate
2839 : TruncateKind::NoTruncate;
2840 }
2841
2842 TruncateKind MDiv::operandTruncateKind(size_t index) const {
2843 return std::min(truncateKind(), TruncateKind::TruncateAfterBailouts);
2844 }
2845
2846 TruncateKind MMod::operandTruncateKind(size_t index) const {
2847 return std::min(truncateKind(), TruncateKind::TruncateAfterBailouts);
2848 }
2849
2850 TruncateKind MCompare::operandTruncateKind(size_t index) const {
2851 // If we're doing an int32 comparison on operands which were previously
2852 // floating-point, convert them!
2853 MOZ_ASSERT_IF(truncateOperands_, isInt32Comparison());
2854 return truncateOperands_ ? TruncateKind::TruncateAfterBailouts
2855 : TruncateKind::NoTruncate;
2856 }
2857
2858 static bool TruncateTest(TempAllocator& alloc, const MTest* test) {
2859 // If all possible inputs to the test are either int32 or boolean,
2860 // convert those inputs to int32 so that an int32 test can be performed.
2861
2862 if (test->input()->type() != MIRType::Value) {
2863 return true;
2864 }
2865
2866 if (!test->input()->isPhi() || !test->input()->hasOneDefUse() ||
2867 test->input()->isImplicitlyUsed()) {
2868 return true;
2869 }
2870
2871 MPhi* phi = test->input()->toPhi();
2872 for (size_t i = 0; i < phi->numOperands(); i++) {
2873 MDefinition* def = phi->getOperand(i);
2874 if (!def->isBox()) {
2875 return true;
2876 }
2877 MDefinition* inner = def->getOperand(0);
2878 if (inner->type() != MIRType::Boolean && inner->type() != MIRType::Int32) {
2879 return true;
2880 }
2881 }
2882
2883 for (size_t i = 0; i < phi->numOperands(); i++) {
2884 MDefinition* inner = phi->getOperand(i)->getOperand(0);
2885 if (inner->type() != MIRType::Int32) {
2886 if (!alloc.ensureBallast()) {
2887 return false;
2888 }
2889 MBasicBlock* block = inner->block();
2890 inner = MToNumberInt32::New(alloc, inner);
2891 block->insertBefore(block->lastIns(), inner->toInstruction());
2892 }
2893 MOZ_ASSERT(inner->type() == MIRType::Int32);
2894 phi->replaceOperand(i, inner);
2895 }
2896
2897 phi->setResultType(MIRType::Int32);
2898 return true;
2899 }
2900
2901 // Truncating instruction result is an optimization which implies
2902 // knowing all uses of an instruction. This implies that if one of
2903 // the uses got removed, then Range Analysis is not be allowed to do
2904 // any modification which can change the result, especially if the
2905 // result can be observed.
2906 //
2907 // This corner can easily be understood with UCE examples, but it
2908 // might also happen with type inference assumptions. Note: Type
2909 // inference is implicitly branches where other types might be
2910 // flowing into.
2911 static bool CloneForDeadBranches(TempAllocator& alloc,
2912 MInstruction* candidate) {
2913 // Compare returns a boolean so it doesn't have to be recovered on bailout
2914 // because the output would remain correct.
2915 if (candidate->isCompare()) {
2916 return true;
2917 }
2918
2919 MOZ_ASSERT(candidate->canClone());
2920 if (!alloc.ensureBallast()) {
2921 return false;
2922 }
2923
2924 MDefinitionVector operands(alloc);
2925 size_t end = candidate->numOperands();
2926 if (!operands.reserve(end)) {
2927 return false;
2928 }
2929 for (size_t i = 0; i < end; ++i) {
2930 operands.infallibleAppend(candidate->getOperand(i));
2931 }
2932
2933 MInstruction* clone = candidate->clone(alloc, operands);
2934 if (!clone) {
2935 return false;
2936 }
2937 clone->setRange(nullptr);
2938
2939 // Set ImplicitlyUsed flag on the cloned instruction in order to chain recover
2940 // instruction for the bailout path.
2941 clone->setImplicitlyUsedUnchecked();
2942
2943 candidate->block()->insertBefore(candidate, clone);
2944
2945 if (!candidate->maybeConstantValue()) {
2946 MOZ_ASSERT(clone->canRecoverOnBailout());
2947 clone->setRecoveredOnBailout();
2948 }
2949
2950 // Replace the candidate by its recovered on bailout clone within recovered
2951 // instructions and resume points operands.
2952 for (MUseIterator i(candidate->usesBegin()); i != candidate->usesEnd();) {
2953 MUse* use = *i++;
2954 MNode* ins = use->consumer();
2955 if (ins->isDefinition() && !ins->toDefinition()->isRecoveredOnBailout()) {
2956 continue;
2957 }
2958
2959 use->replaceProducer(clone);
2960 }
2961
2962 return true;
2963 }
2964
2965 struct ComputedTruncateKind {
2966 TruncateKind kind = TruncateKind::NoTruncate;
2967 bool shouldClone = false;
2968 };
2969
2970 // Examine all the users of |candidate| and determine the most aggressive
2971 // truncate kind that satisfies all of them.
2972 static ComputedTruncateKind ComputeRequestedTruncateKind(
2973 const MDefinition* candidate) {
2974 // Don't call this method when truncation isn't supported, because the result
2975 // isn't used anyway.
2976 MOZ_ASSERT(candidate->canTruncate());
2977
2978 bool isCapturedResult =
2979 false; // Check if used by a recovered instruction or a resume point.
2980 bool isObservableResult =
2981 false; // Check if it can be read from another frame.
2982 bool isRecoverableResult = true; // Check if it can safely be reconstructed.
2983 bool isImplicitlyUsed = candidate->isImplicitlyUsed();
2984 bool hasTryBlock = candidate->block()->graph().hasTryBlock();
2985
2986 TruncateKind kind = TruncateKind::Truncate;
2987 for (MUseIterator use(candidate->usesBegin()); use != candidate->usesEnd();
2988 use++) {
2989 if (use->consumer()->isResumePoint()) {
2990 // Truncation is a destructive optimization, as such, we need to pay
2991 // attention to removed branches and prevent optimization
2992 // destructive optimizations if we have no alternative. (see
2993 // ImplicitlyUsed flag)
2994 isCapturedResult = true;
2995 isObservableResult =
2996 isObservableResult ||
2997 use->consumer()->toResumePoint()->isObservableOperand(*use);
2998 isRecoverableResult =
2999 isRecoverableResult &&
3000 use->consumer()->toResumePoint()->isRecoverableOperand(*use);
3001 continue;
3002 }
3003
3004 MDefinition* consumer = use->consumer()->toDefinition();
3005 if (consumer->isRecoveredOnBailout()) {
3006 isCapturedResult = true;
3007 isImplicitlyUsed = isImplicitlyUsed || consumer->isImplicitlyUsed();
3008 continue;
3009 }
3010
3011 TruncateKind consumerKind =
3012 consumer->operandTruncateKind(consumer->indexOf(*use));
3013 kind = std::min(kind, consumerKind);
3014 if (kind == TruncateKind::NoTruncate) {
3015 break;
3016 }
3017 }
3018
3019 // We cannot do full truncation on guarded instructions.
3020 if (candidate->isGuard() || candidate->isGuardRangeBailouts()) {
3021 kind = std::min(kind, TruncateKind::TruncateAfterBailouts);
3022 }
3023
3024 // If the value naturally produces an int32 value (before bailout checks)
3025 // that needs no conversion, we don't have to worry about resume points
3026 // seeing truncated values.
3027 bool needsConversion = !candidate->range() || !candidate->range()->isInt32();
3028
3029 // If the instruction is explicitly truncated (not indirectly) by all its
3030 // uses and if it is not implicitly used, then we can safely encode its
3031 // truncated result as part of the resume point operands. This is safe,
3032 // because even if we resume with a truncated double, the next baseline
3033 // instruction operating on this instruction is going to be a no-op.
3034 //
3035 // Note, that if the result can be observed from another frame, then this
3036 // optimization is not safe. Similarly, if this function contains a try
3037 // block, the result could be observed from a catch block, which we do
3038 // not compile.
3039 bool safeToConvert = kind == TruncateKind::Truncate && !isImplicitlyUsed &&
3040 !isObservableResult && !hasTryBlock;
3041
3042 // If the candidate instruction appears as operand of a resume point or a
3043 // recover instruction, and we have to truncate its result, then we might
3044 // have to either recover the result during the bailout, or avoid the
3045 // truncation.
3046 bool shouldClone = false;
3047 if (isCapturedResult && needsConversion && !safeToConvert) {
3048 // If the result can be recovered from all the resume points (not needed
3049 // for iterating over the inlined frames), and this instruction can be
3050 // recovered on bailout, then we can clone it and use the cloned
3051 // instruction to encode the recover instruction. Otherwise, we should
3052 // keep the original result and bailout if the value is not in the int32
3053 // range.
3054 if (!JitOptions.disableRecoverIns && isRecoverableResult &&
3055 candidate->canRecoverOnBailout()) {
3056 shouldClone = true;
3057 } else {
3058 kind = std::min(kind, TruncateKind::TruncateAfterBailouts);
3059 }
3060 }
3061
3062 return {kind, shouldClone};
3063 }
3064
3065 static ComputedTruncateKind ComputeTruncateKind(const MDefinition* candidate) {
3066 // Don't call this method when truncation isn't supported, because the result
3067 // isn't used anyway.
3068 MOZ_ASSERT(candidate->canTruncate());
3069
3070 // Compare operations might coerce its inputs to int32 if the ranges are
3071 // correct. So we do not need to check if all uses are coerced.
3072 if (candidate->isCompare()) {
3073 return {TruncateKind::TruncateAfterBailouts};
3074 }
3075
3076 // Set truncated flag if range analysis ensure that it has no
3077 // rounding errors and no fractional part. Note that we can't use
3078 // the MDefinition Range constructor, because we need to know if
3079 // the value will have rounding errors before any bailout checks.
3080 const Range* r = candidate->range();
3081 bool canHaveRoundingErrors = !r || r->canHaveRoundingErrors();
3082
3083 // Special case integer division and modulo: a/b can be infinite, and a%b
3084 // can be NaN but cannot actually have rounding errors induced by truncation.
3085 if ((candidate->isDiv() || candidate->isMod()) &&
3086 candidate->type() == MIRType::Int32) {
3087 canHaveRoundingErrors = false;
3088 }
3089
3090 if (canHaveRoundingErrors) {
3091 return {TruncateKind::NoTruncate};
3092 }
3093
3094 // Ensure all observable uses are truncated.
3095 return ComputeRequestedTruncateKind(candidate);
3096 }
3097
3098 static void RemoveTruncatesOnOutput(MDefinition* truncated) {
3099 // Compare returns a boolean so it doesn't have any output truncates.
3100 if (truncated->isCompare()) {
3101 return;
3102 }
3103
3104 MOZ_ASSERT(truncated->type() == MIRType::Int32);
3105 MOZ_ASSERT(Range(truncated).isInt32());
3106
3107 for (MUseDefIterator use(truncated); use; use++) {
3108 MDefinition* def = use.def();
3109 if (!def->isTruncateToInt32() || !def->isToNumberInt32()) {
3110 continue;
3111 }
3112
3113 def->replaceAllUsesWith(truncated);
3114 }
3115 }
3116
3117 void RangeAnalysis::adjustTruncatedInputs(MDefinition* truncated) {
3118 MBasicBlock* block = truncated->block();
3119 for (size_t i = 0, e = truncated->numOperands(); i < e; i++) {
3120 TruncateKind kind = truncated->operandTruncateKind(i);
3121 if (kind == TruncateKind::NoTruncate) {
3122 continue;
3123 }
3124
3125 MDefinition* input = truncated->getOperand(i);
3126 if (input->type() == MIRType::Int32) {
3127 continue;
3128 }
3129
3130 if (input->isToDouble() && input->getOperand(0)->type() == MIRType::Int32) {
3131 truncated->replaceOperand(i, input->getOperand(0));
3132 } else {
3133 MInstruction* op;
3134 if (kind == TruncateKind::TruncateAfterBailouts) {
3135 MOZ_ASSERT(!mir->outerInfo().hadEagerTruncationBailout());
3136 op = MToNumberInt32::New(alloc(), truncated->getOperand(i));
3137 op->setBailoutKind(BailoutKind::EagerTruncation);
3138 } else {
3139 op = MTruncateToInt32::New(alloc(), truncated->getOperand(i));
3140 }
3141
3142 if (truncated->isPhi()) {
3143 MBasicBlock* pred = block->getPredecessor(i);
3144 pred->insertBefore(pred->lastIns(), op);
3145 } else {
3146 block->insertBefore(truncated->toInstruction(), op);
3147 }
3148 truncated->replaceOperand(i, op);
3149 }
3150 }
3151
3152 if (truncated->isToDouble()) {
3153 truncated->replaceAllUsesWith(truncated->toToDouble()->getOperand(0));
3154 block->discard(truncated->toToDouble());
3155 }
3156 }
3157
3158 bool RangeAnalysis::canTruncate(const MDefinition* def,
3159 TruncateKind kind) const {
3160 // Don't call this method when truncation isn't supported, because the result
3161 // isn't used anyway.
3162 MOZ_ASSERT(def->canTruncate());
3163
3164 if (kind == TruncateKind::NoTruncate) {
3165 return false;
3166 }
3167
3168 // Range Analysis is sometimes eager to do optimizations, even if we
3169 // are not able to truncate an instruction. In such case, we
3170 // speculatively compile the instruction to an int32 instruction
3171 // while adding a guard. This is what is implied by
3172 // TruncateAfterBailout.
3173 //
3174 // If a previous compilation was invalidated because a speculative
3175 // truncation bailed out, we no longer attempt to make this kind of
3176 // eager optimization.
3177 if (mir->outerInfo().hadEagerTruncationBailout()) {
3178 if (kind == TruncateKind::TruncateAfterBailouts) {
3179 return false;
3180 }
3181 // MDiv and MMod always require TruncateAfterBailout for their operands.
3182 // See MDiv::operandTruncateKind and MMod::operandTruncateKind.
3183 if (def->isDiv() || def->isMod()) {
3184 return false;
3185 }
3186 }
3187
3188 return true;
3189 }
3190
3191 // Iterate backward on all instruction and attempt to truncate operations for
3192 // each instruction which respect the following list of predicates: Has been
3193 // analyzed by range analysis, the range has no rounding errors, all uses cases
3194 // are truncating the result.
3195 //
3196 // If the truncation of the operation is successful, then the instruction is
3197 // queue for later updating the graph to restore the type correctness by
3198 // converting the operands that need to be truncated.
3199 //
3200 // We iterate backward because it is likely that a truncated operation truncates
3201 // some of its operands.
3202 bool RangeAnalysis::truncate() {
3203 JitSpew(JitSpew_Range, "Do range-base truncation (backward loop)");
3204
3205 // Automatic truncation is disabled for wasm because the truncation logic
3206 // is based on IonMonkey which assumes that we can bailout if the truncation
3207 // logic fails. As wasm code has no bailout mechanism, it is safer to avoid
3208 // any automatic truncations.
3209 MOZ_ASSERT(!mir->compilingWasm());
3210
3211 Vector<MDefinition*, 16, SystemAllocPolicy> worklist;
3212
3213 for (PostorderIterator block(graph_.poBegin()); block != graph_.poEnd();
3214 block++) {
3215 if (mir->shouldCancel("RangeAnalysis truncate")) {
3216 return false;
3217 }
3218
3219 for (MInstructionReverseIterator iter(block->rbegin());
3220 iter != block->rend(); iter++) {
3221 if (iter->isRecoveredOnBailout()) {
3222 continue;
3223 }
3224
3225 if (iter->type() == MIRType::None) {
3226 if (iter->isTest()) {
3227 if (!TruncateTest(alloc(), iter->toTest())) {
3228 return false;
3229 }
3230 }
3231 continue;
3232 }
3233
3234 // Remember all bitop instructions for folding after range analysis.
3235 switch (iter->op()) {
3236 case MDefinition::Opcode::BitAnd:
3237 case MDefinition::Opcode::BitOr:
3238 case MDefinition::Opcode::BitXor:
3239 case MDefinition::Opcode::Lsh:
3240 case MDefinition::Opcode::Rsh:
3241 case MDefinition::Opcode::Ursh:
3242 if (!bitops.append(static_cast<MBinaryBitwiseInstruction*>(*iter))) {
3243 return false;
3244 }
3245 break;
3246 default:;
3247 }
3248
3249 // Skip instructions which can't be truncated.
3250 if (!iter->canTruncate()) {
3251 continue;
3252 }
3253
3254 auto [kind, shouldClone] = ComputeTruncateKind(*iter);
3255
3256 // Truncate this instruction if possible.
3257 if (!canTruncate(*iter, kind)) {
3258 continue;
3259 }
3260
3261 SpewTruncate(*iter, kind, shouldClone);
3262
3263 // If needed, clone the current instruction for keeping it for the
3264 // bailout path. This give us the ability to truncate instructions
3265 // even after the removal of branches.
3266 if (shouldClone && !CloneForDeadBranches(alloc(), *iter)) {
3267 return false;
3268 }
3269
3270 // TruncateAfterBailouts keeps the bailout code as-is and
3271 // continues with truncated operations, with the expectation
3272 // that we are unlikely to bail out. If we do bail out, then we
3273 // will set a flag in FinishBailoutToBaseline to prevent eager
3274 // truncation when we recompile, to avoid bailout loops.
3275 if (kind == TruncateKind::TruncateAfterBailouts) {
3276 iter->setBailoutKind(BailoutKind::EagerTruncation);
3277 }
3278
3279 iter->truncate(kind);
3280
3281 // Delay updates of inputs/outputs to avoid creating node which
3282 // would be removed by the truncation of the next operations.
3283 iter->setInWorklist();
3284 if (!worklist.append(*iter)) {
3285 return false;
3286 }
3287 }
3288 for (MPhiIterator iter(block->phisBegin()), end(block->phisEnd());
3289 iter != end; ++iter) {
3290 // Skip phis which can't be truncated.
3291 if (!iter->canTruncate()) {
3292 continue;
3293 }
3294
3295 auto [kind, shouldClone] = ComputeTruncateKind(*iter);
3296
3297 // Truncate this phi if possible.
3298 if (shouldClone || !canTruncate(*iter, kind)) {
3299 continue;
3300 }
3301
3302 SpewTruncate(*iter, kind, shouldClone);
3303
3304 iter->truncate(kind);
3305
3306 // Delay updates of inputs/outputs to avoid creating node which
3307 // would be removed by the truncation of the next operations.
3308 iter->setInWorklist();
3309 if (!worklist.append(*iter)) {
3310 return false;
3311 }
3312 }
3313 }
3314
3315 // Update inputs/outputs of truncated instructions.
3316 JitSpew(JitSpew_Range, "Do graph type fixup (dequeue)");
3317 while (!worklist.empty()) {
3318 if (!alloc().ensureBallast()) {
3319 return false;
3320 }
3321 MDefinition* def = worklist.popCopy();
3322 def->setNotInWorklist();
3323 RemoveTruncatesOnOutput(def);
3324 adjustTruncatedInputs(def);
3325 }
3326
3327 return true;
3328 }
3329
3330 bool RangeAnalysis::removeUnnecessaryBitops() {
3331 JitSpew(JitSpew_Range, "Begin (removeUnnecessaryBitops)");
3332 // Note: This operation change the semantic of the program in a way which
3333 // uniquely works with Int32, Recover Instructions added by the Sink phase
3334 // expects the MIR Graph to still have a valid flow as-if they were double
3335 // operations instead of Int32 operations. Thus, this phase should be
3336 // executed after the Sink phase, and before DCE.
3337
3338 // Fold any unnecessary bitops in the graph, such as (x | 0) on an integer
3339 // input. This is done after range analysis rather than during GVN as the
3340 // presence of the bitop can change which instructions are truncated.
3341 for (size_t i = 0; i < bitops.length(); i++) {
3342 MBinaryBitwiseInstruction* ins = bitops[i];
3343 if (ins->isRecoveredOnBailout()) {
3344 continue;
3345 }
3346
3347 MDefinition* folded = ins->foldUnnecessaryBitop();
3348 if (folded != ins) {
3349 ins->replaceAllLiveUsesWith(folded);
3350 ins->setRecoveredOnBailout();
3351 }
3352 }
3353
3354 bitops.clear();
3355 return true;
3356 }
3357
3358 ///////////////////////////////////////////////////////////////////////////////
3359 // Collect Range information of operands
3360 ///////////////////////////////////////////////////////////////////////////////
3361
3362 void MInArray::collectRangeInfoPreTrunc() {
3363 Range indexRange(index());
3364 if (indexRange.isFiniteNonNegative()) {
3365 needsNegativeIntCheck_ = false;
3366 setNotGuard();
3367 }
3368 }
3369
3370 void MLoadElementHole::collectRangeInfoPreTrunc() {
3371 Range indexRange(index());
3372 if (indexRange.isFiniteNonNegative()) {
3373 needsNegativeIntCheck_ = false;
3374 setNotGuard();
3375 }
3376 }
3377
3378 void MInt32ToIntPtr::collectRangeInfoPreTrunc() {
3379 Range inputRange(input());
3380 if (inputRange.isFiniteNonNegative()) {
3381 canBeNegative_ = false;
3382 }
3383 }
3384
3385 void MClz::collectRangeInfoPreTrunc() {
3386 Range inputRange(input());
3387 if (!inputRange.canBeZero()) {
3388 operandIsNeverZero_ = true;
3389 }
3390 }
3391
3392 void MCtz::collectRangeInfoPreTrunc() {
3393 Range inputRange(input());
3394 if (!inputRange.canBeZero()) {
3395 operandIsNeverZero_ = true;
3396 }
3397 }
3398
3399 void MDiv::collectRangeInfoPreTrunc() {
3400 Range lhsRange(lhs());
3401 Range rhsRange(rhs());
3402
3403 // Test if Dividend is non-negative.
3404 if (lhsRange.isFiniteNonNegative()) {
3405 canBeNegativeDividend_ = false;
3406 }
3407
3408 // Try removing divide by zero check.
3409 if (!rhsRange.canBeZero()) {
3410 canBeDivideByZero_ = false;
3411 }
3412
3413 // If lhsRange does not contain INT32_MIN in its range,
3414 // negative overflow check can be skipped.
3415 if (!lhsRange.contains(INT32_MIN)) {
3416 canBeNegativeOverflow_ = false;
3417 }
3418
3419 // If rhsRange does not contain -1 likewise.
3420 if (!rhsRange.contains(-1)) {
3421 canBeNegativeOverflow_ = false;
3422 }
3423
3424 // If lhsRange does not contain a zero,
3425 // negative zero check can be skipped.
3426 if (!lhsRange.canBeZero()) {
3427 canBeNegativeZero_ = false;
3428 }
3429
3430 // If rhsRange >= 0 negative zero check can be skipped.
3431 if (rhsRange.isFiniteNonNegative()) {
3432 canBeNegativeZero_ = false;
3433 }
3434
3435 if (type() == MIRType::Int32 && fallible()) {
3436 setGuardRangeBailoutsUnchecked();
3437 }
3438 }
3439
3440 void MMul::collectRangeInfoPreTrunc() {
3441 Range lhsRange(lhs());
3442 Range rhsRange(rhs());
3443
3444 // If lhsRange contains only positive then we can skip negative zero check.
3445 if (lhsRange.isFiniteNonNegative() && !lhsRange.canBeZero()) {
3446 setCanBeNegativeZero(false);
3447 }
3448
3449 // Likewise rhsRange.
3450 if (rhsRange.isFiniteNonNegative() && !rhsRange.canBeZero()) {
3451 setCanBeNegativeZero(false);
3452 }
3453
3454 // If rhsRange and lhsRange contain Non-negative integers only,
3455 // We skip negative zero check.
3456 if (rhsRange.isFiniteNonNegative() && lhsRange.isFiniteNonNegative()) {
3457 setCanBeNegativeZero(false);
3458 }
3459
3460 // If rhsRange and lhsRange < 0. Then we skip negative zero check.
3461 if (rhsRange.isFiniteNegative() && lhsRange.isFiniteNegative()) {
3462 setCanBeNegativeZero(false);
3463 }
3464 }
3465
3466 void MMod::collectRangeInfoPreTrunc() {
3467 Range lhsRange(lhs());
3468 Range rhsRange(rhs());
3469 if (lhsRange.isFiniteNonNegative()) {
3470 canBeNegativeDividend_ = false;
3471 }
3472 if (!rhsRange.canBeZero()) {
3473 canBeDivideByZero_ = false;
3474 }
3475 if (type() == MIRType::Int32 && fallible()) {
3476 setGuardRangeBailoutsUnchecked();
3477 }
3478 }
3479
3480 void MToNumberInt32::collectRangeInfoPreTrunc() {
3481 Range inputRange(input());
3482 if (!inputRange.canBeNegativeZero()) {
3483 needsNegativeZeroCheck_ = false;
3484 }
3485 }
3486
3487 void MBoundsCheck::collectRangeInfoPreTrunc() {
3488 Range indexRange(index());
3489 Range lengthRange(length());
3490 if (!indexRange.hasInt32LowerBound() || !indexRange.hasInt32UpperBound()) {
3491 return;
3492 }
3493 if (!lengthRange.hasInt32LowerBound() || lengthRange.canBeNaN()) {
3494 return;
3495 }
3496
3497 int64_t indexLower = indexRange.lower();
3498 int64_t indexUpper = indexRange.upper();
3499 int64_t lengthLower = lengthRange.lower();
3500 int64_t min = minimum();
3501 int64_t max = maximum();
3502
3503 if (indexLower + min >= 0 && indexUpper + max < lengthLower) {
3504 fallible_ = false;
3505 }
3506 }
3507
3508 void MBoundsCheckLower::collectRangeInfoPreTrunc() {
3509 Range indexRange(index());
3510 if (indexRange.hasInt32LowerBound() && indexRange.lower() >= minimum_) {
3511 fallible_ = false;
3512 }
3513 }
3514
3515 void MCompare::collectRangeInfoPreTrunc() {
3516 if (!Range(lhs()).canBeNaN() && !Range(rhs()).canBeNaN()) {
3517 operandsAreNeverNaN_ = true;
3518 }
3519 }
3520
3521 void MNot::collectRangeInfoPreTrunc() {
3522 if (!Range(input()).canBeNaN()) {
3523 operandIsNeverNaN_ = true;
3524 }
3525 }
3526
3527 void MPowHalf::collectRangeInfoPreTrunc() {
3528 Range inputRange(input());
3529 if (!inputRange.canBeInfiniteOrNaN() || inputRange.hasInt32LowerBound()) {
3530 operandIsNeverNegativeInfinity_ = true;
3531 }
3532 if (!inputRange.canBeNegativeZero()) {
3533 operandIsNeverNegativeZero_ = true;
3534 }
3535 if (!inputRange.canBeNaN()) {
3536 operandIsNeverNaN_ = true;
3537 }
3538 }
3539
3540 void MUrsh::collectRangeInfoPreTrunc() {
3541 if (type() == MIRType::Int64) {
3542 return;
3543 }
3544
3545 Range lhsRange(lhs()), rhsRange(rhs());
3546
3547 // As in MUrsh::computeRange(), convert the inputs.
3548 lhsRange.wrapAroundToInt32();
3549 rhsRange.wrapAroundToShiftCount();
3550
3551 // If the most significant bit of our result is always going to be zero,
3552 // we can optimize by disabling bailout checks for enforcing an int32 range.
3553 if (lhsRange.lower() >= 0 || rhsRange.lower() >= 1) {
3554 bailoutsDisabled_ = true;
3555 }
3556 }
3557
3558 static bool DoesMaskMatchRange(int32_t mask, const Range& range) {
3559 // Check if range is positive, because the bitand operator in `(-3) & 0xff`
3560 // can't be eliminated.
3561 if (range.lower() >= 0) {
3562 MOZ_ASSERT(range.isInt32());
3563 // Check that the mask value has all bits set given the range upper bound.
3564 // Note that the upper bound does not have to be exactly the mask value. For
3565 // example, consider `x & 0xfff` where `x` is a uint8. That expression can
3566 // still be optimized to `x`.
3567 int bits = 1 + FloorLog2(range.upper());
3568 uint32_t maskNeeded = (bits == 32) ? 0xffffffff : (uint32_t(1) << bits) - 1;
3569 if ((mask & maskNeeded) == maskNeeded) {
3570 return true;
3571 }
3572 }
3573
3574 return false;
3575 }
3576
3577 void MBinaryBitwiseInstruction::collectRangeInfoPreTrunc() {
3578 Range lhsRange(lhs());
3579 Range rhsRange(rhs());
3580
3581 if (lhs()->isConstant() && lhs()->type() == MIRType::Int32 &&
3582 DoesMaskMatchRange(lhs()->toConstant()->toInt32(), rhsRange)) {
3583 maskMatchesRightRange = true;
3584 }
3585
3586 if (rhs()->isConstant() && rhs()->type() == MIRType::Int32 &&
3587 DoesMaskMatchRange(rhs()->toConstant()->toInt32(), lhsRange)) {
3588 maskMatchesLeftRange = true;
3589 }
3590 }
3591
3592 void MNaNToZero::collectRangeInfoPreTrunc() {
3593 Range inputRange(input());
3594
3595 if (!inputRange.canBeNaN()) {
3596 operandIsNeverNaN_ = true;
3597 }
3598 if (!inputRange.canBeNegativeZero()) {
3599 operandIsNeverNegativeZero_ = true;
3600 }
3601 }
3602
3603 bool RangeAnalysis::prepareForUCE(bool* shouldRemoveDeadCode) {
3604 *shouldRemoveDeadCode = false;
3605
3606 for (ReversePostorderIterator iter(graph_.rpoBegin());
3607 iter != graph_.rpoEnd(); iter++) {
3608 MBasicBlock* block = *iter;
3609
3610 if (!block->unreachable()) {
3611 continue;
3612 }
3613
3614 // Filter out unreachable fake entries.
3615 if (block->numPredecessors() == 0) {
3616 // Ignore fixup blocks added by the Value Numbering phase, in order
3617 // to keep the dominator tree as-is when we have OSR Block which are
3618 // no longer reachable from the main entry point of the graph.
3619 MOZ_ASSERT(graph_.osrBlock());
3620 continue;
3621 }
3622
3623 MControlInstruction* cond = block->getPredecessor(0)->lastIns();
3624 if (!cond->isTest()) {
3625 continue;
3626 }
3627
3628 // Replace the condition of the test control instruction by a constant
3629 // chosen based which of the successors has the unreachable flag which is
3630 // added by MBeta::computeRange on its own block.
3631 MTest* test = cond->toTest();
3632 MDefinition* condition = test->input();
3633
3634 // If the false-branch is unreachable, then the test condition must be true.
3635 // If the true-branch is unreachable, then the test condition must be false.
3636 MOZ_ASSERT(block == test->ifTrue() || block == test->ifFalse());
3637 bool value = block == test->ifFalse();
3638 MConstant* constant =
3639 MConstant::New(alloc().fallible(), BooleanValue(value));
3640 if (!constant) {
3641 return false;
3642 }
3643
3644 condition->setGuardRangeBailoutsUnchecked();
3645
3646 test->block()->insertBefore(test, constant);
3647
3648 test->replaceOperand(0, constant);
3649 JitSpew(JitSpew_Range,
3650 "Update condition of %u to reflect unreachable branches.",
3651 test->id());
3652
3653 *shouldRemoveDeadCode = true;
3654 }
3655
3656 return tryRemovingGuards();
3657 }
3658
3659 bool RangeAnalysis::tryRemovingGuards() {
3660 MDefinitionVector guards(alloc());
3661
3662 for (ReversePostorderIterator block = graph_.rpoBegin();
3663 block != graph_.rpoEnd(); block++) {
3664 if (mir->shouldCancel("RangeAnalysis tryRemovingGuards (block loop)")) {
3665 return false;
3666 }
3667
3668 for (MDefinitionIterator iter(*block); iter; iter++) {
3669 if (!iter->isGuardRangeBailouts()) {
3670 continue;
3671 }
3672
3673 iter->setInWorklist();
3674 if (!guards.append(*iter)) {
3675 return false;
3676 }
3677 }
3678 }
3679
3680 // Flag all fallible instructions which were indirectly used in the
3681 // computation of the condition, such that we do not ignore
3682 // bailout-paths which are used to shrink the input range of the
3683 // operands of the condition.
3684 for (size_t i = 0; i < guards.length(); i++) {
3685 if (mir->shouldCancel("RangeAnalysis tryRemovingGuards (guards loop)")) {
3686 return false;
3687 }
3688
3689 MDefinition* guard = guards[i];
3690
3691 // If this ins is a guard even without guardRangeBailouts,
3692 // there is no reason in trying to hoist the guardRangeBailouts check.
3693 guard->setNotGuardRangeBailouts();
3694 if (!DeadIfUnused(guard)) {
3695 guard->setGuardRangeBailouts();
3696 continue;
3697 }
3698 guard->setGuardRangeBailouts();
3699
3700 if (!guard->isPhi()) {
3701 if (!guard->range()) {
3702 continue;
3703 }
3704
3705 // Filter the range of the instruction based on its MIRType.
3706 Range typeFilteredRange(guard);
3707
3708 // If the output range is updated by adding the inner range,
3709 // then the MIRType act as an effectful filter. As we do not know if
3710 // this filtered Range might change or not the result of the
3711 // previous comparison, we have to keep this instruction as a guard
3712 // because it has to bailout in order to restrict the Range to its
3713 // MIRType.
3714 if (typeFilteredRange.update(guard->range())) {
3715 continue;
3716 }
3717 }
3718
3719 guard->setNotGuardRangeBailouts();
3720
3721 // Propagate the guard to its operands.
3722 for (size_t op = 0, e = guard->numOperands(); op < e; op++) {
3723 MDefinition* operand = guard->getOperand(op);
3724
3725 // Already marked.
3726 if (operand->isInWorklist()) {
3727 continue;
3728 }
3729
3730 MOZ_ASSERT(!operand->isGuardRangeBailouts());
3731
3732 operand->setInWorklist();
3733 operand->setGuardRangeBailouts();
3734 if (!guards.append(operand)) {
3735 return false;
3736 }
3737 }
3738 }
3739
3740 for (size_t i = 0; i < guards.length(); i++) {
3741 MDefinition* guard = guards[i];
3742 guard->setNotInWorklist();
3743 }
3744
3745 return true;
3746 }