Debian Codegraph @

js/src/jit/IonAnalysis.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/IonAnalysis.h"
8
9 #include "mozilla/HashFunctions.h"
10
11 #include <algorithm>
12 #include <utility> // for ::std::pair
13
14 #include "jit/AliasAnalysis.h"
15 #include "jit/CompileInfo.h"
16 #include "jit/DominatorTree.h"
17 #include "jit/MIRGenerator.h"
18 #include "jit/MIRGraph.h"
19 #include "util/CheckedArithmetic.h"
20
21 #include "vm/BytecodeUtil-inl.h"
22
23 using namespace js;
24 using namespace js::jit;
25
26 using mozilla::DebugOnly;
27
28 // Stack used by FlagPhiInputsAsImplicitlyUsed. It stores the Phi instruction
29 // pointer and the MUseIterator which should be visited next.
30 using MPhiUseIteratorStack =
31 Vector<std::pair<MPhi*, MUseIterator>, 16, SystemAllocPolicy>;
32
33 // Look for Phi uses with a depth-first search. If any uses are found the stack
34 // of MPhi instructions is returned in the |worklist| argument.
35 [[nodiscard]] static bool DepthFirstSearchUse(const MIRGenerator* mir,
36 MPhiUseIteratorStack& worklist,
37 MPhi* phi) {
38 // Push a Phi and the next use to iterate over in the worklist.
39 auto push = [&worklist](MPhi* phi, MUseIterator use) -> bool {
40 phi->setInWorklist();
41 return worklist.append(std::make_pair(phi, use));
42 };
43
44 #ifdef DEBUG
45 // Used to assert that when we have no uses, we at least visited all the
46 // transitive uses.
47 size_t refUseCount = phi->useCount();
48 size_t useCount = 0;
49 #endif
50 MOZ_ASSERT(worklist.empty());
51 if (!push(phi, phi->usesBegin())) {
52 return false;
53 }
54
55 while (!worklist.empty()) {
56 // Resume iterating over the last phi-use pair added by the next loop.
57 auto pair = worklist.popCopy();
58 MPhi* producer = pair.first;
59 MUseIterator use = pair.second;
60 MUseIterator end(producer->usesEnd());
61 producer->setNotInWorklist();
62
63 // Keep going down the tree of uses, skipping (continue)
64 // non-observable/unused cases and Phi which are already listed in the
65 // worklist. Stop (return) as soon as one use is found.
66 while (use != end) {
67 MNode* consumer = (*use)->consumer();
68 MUseIterator it = use;
69 use++;
70 #ifdef DEBUG
71 useCount++;
72 #endif
73 if (mir->shouldCancel("FlagPhiInputsAsImplicitlyUsed inner loop")) {
74 return false;
75 }
76
77 if (consumer->isResumePoint()) {
78 MResumePoint* rp = consumer->toResumePoint();
79 // Observable operands are similar to potential uses.
80 if (rp->isObservableOperand(*it)) {
81 return push(producer, use);
82 }
83 continue;
84 }
85
86 MDefinition* cdef = consumer->toDefinition();
87 if (!cdef->isPhi()) {
88 // The producer is explicitly used by a definition.
89 return push(producer, use);
90 }
91
92 MPhi* cphi = cdef->toPhi();
93 if (cphi->getUsageAnalysis() == PhiUsage::Used ||
94 cphi->isImplicitlyUsed()) {
95 // The information got cached on the Phi the last time it
96 // got visited, or when flagging operands of implicitly used
97 // instructions.
98 return push(producer, use);
99 }
100
101 if (cphi->isInWorklist() || cphi == producer) {
102 // We are already iterating over the uses of this Phi instruction which
103 // are part of a loop, instead of trying to handle loops, conservatively
104 // mark them as used.
105 return push(producer, use);
106 }
107
108 if (cphi->getUsageAnalysis() == PhiUsage::Unused) {
109 // The instruction already got visited and is known to have
110 // no uses. Skip it.
111 continue;
112 }
113
114 // We found another Phi instruction, move the use iterator to
115 // the next use push it to the worklist stack. Then, continue
116 // with a depth search.
117 if (!push(producer, use)) {
118 return false;
119 }
120 producer = cphi;
121 use = producer->usesBegin();
122 end = producer->usesEnd();
123 #ifdef DEBUG
124 refUseCount += producer->useCount();
125 #endif
126 }
127
128 // When unused, we cannot bubble up this information without iterating
129 // over the rest of the previous Phi instruction consumers.
130 MOZ_ASSERT(use == end);
131 producer->setUsageAnalysis(PhiUsage::Unused);
132 }
133
134 MOZ_ASSERT(useCount == refUseCount);
135 return true;
136 }
137
138 [[nodiscard]] static bool FlagPhiInputsAsImplicitlyUsed(
139 const MIRGenerator* mir, MBasicBlock* block, MBasicBlock* succ,
140 MPhiUseIteratorStack& worklist) {
141 // When removing an edge between 2 blocks, we might remove the ability of
142 // later phases to figure out that the uses of a Phi should be considered as
143 // a use of all its inputs. Thus we need to mark the Phi inputs as being
144 // implicitly used iff the phi has any uses.
145 //
146 //
147 // +--------------------+ +---------------------+
148 // |12 MFoo 6 | |32 MBar 5 |
149 // | | | |
150 // | ... | | ... |
151 // | | | |
152 // |25 MGoto Block 4 | |43 MGoto Block 4 |
153 // +--------------------+ +---------------------+
154 // | |
155 // | | |
156 // | | |
157 // | +-----X------------------------+
158 // | Edge |
159 // | Removed |
160 // | |
161 // | +------------v-----------+
162 // | |50 MPhi 12 32 |
163 // | | |
164 // | | ... |
165 // | | |
166 // | |70 MReturn 50 |
167 // | +------------------------+
168 // |
169 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
170 // |
171 // v
172 //
173 // ^ +--------------------+ +---------------------+
174 // /!\ |12 MConst opt-out | |32 MBar 5 |
175 // '---' | | | |
176 // | ... | | ... |
177 // |78 MBail | | |
178 // |80 MUnreachable | |43 MGoto Block 4 |
179 // +--------------------+ +---------------------+
180 // |
181 // |
182 // |
183 // +---------------+
184 // |
185 // |
186 // |
187 // +------------v-----------+
188 // |50 MPhi 32 |
189 // | |
190 // | ... |
191 // | |
192 // |70 MReturn 50 |
193 // +------------------------+
194 //
195 //
196 // If the inputs of the Phi are not flagged as implicitly used, then
197 // later compilation phase might optimize them out. The problem is that a
198 // bailout will use this value and give it back to baseline, which will then
199 // use the OptimizedOut magic value in a computation.
200 //
201 // Unfortunately, we cannot be too conservative about flagging Phi inputs as
202 // having implicit uses, as this would prevent many optimizations from being
203 // used. Thus, the following code is in charge of flagging Phi instructions
204 // as Unused or Used, and setting ImplicitlyUsed accordingly.
205 size_t predIndex = succ->getPredecessorIndex(block);
206 MPhiIterator end = succ->phisEnd();
207 MPhiIterator it = succ->phisBegin();
208 for (; it != end; it++) {
209 MPhi* phi = *it;
210
211 if (mir->shouldCancel("FlagPhiInputsAsImplicitlyUsed outer loop")) {
212 return false;
213 }
214
215 // We are looking to mark the Phi inputs which are used across the edge
216 // between the |block| and its successor |succ|.
217 MDefinition* def = phi->getOperand(predIndex);
218 if (def->isImplicitlyUsed()) {
219 continue;
220 }
221
222 // If the Phi is either Used or Unused, set the ImplicitlyUsed flag
223 // accordingly.
224 if (phi->getUsageAnalysis() == PhiUsage::Used || phi->isImplicitlyUsed()) {
225 def->setImplicitlyUsedUnchecked();
226 continue;
227 } else if (phi->getUsageAnalysis() == PhiUsage::Unused) {
228 continue;
229 }
230
231 // We do not know if the Phi was Used or Unused, iterate over all uses
232 // with a depth-search of uses. Returns the matching stack in the
233 // worklist as soon as one use is found.
234 MOZ_ASSERT(worklist.empty());
235 if (!DepthFirstSearchUse(mir, worklist, phi)) {
236 return false;
237 }
238
239 MOZ_ASSERT_IF(worklist.empty(),
240 phi->getUsageAnalysis() == PhiUsage::Unused);
241 if (!worklist.empty()) {
242 // One of the Phis is used, set Used flags on all the Phis which are
243 // in the use chain.
244 def->setImplicitlyUsedUnchecked();
245 do {
246 auto pair = worklist.popCopy();
247 MPhi* producer = pair.first;
248 producer->setUsageAnalysis(PhiUsage::Used);
249 producer->setNotInWorklist();
250 } while (!worklist.empty());
251 }
252 MOZ_ASSERT(phi->getUsageAnalysis() != PhiUsage::Unknown);
253 }
254
255 return true;
256 }
257
258 static MInstructionIterator FindFirstInstructionAfterBail(MBasicBlock* block) {
259 MOZ_ASSERT(block->alwaysBails());
260 for (MInstructionIterator it = block->begin(); it != block->end(); it++) {
261 MInstruction* ins = *it;
262 if (ins->isBail()) {
263 it++;
264 return it;
265 }
266 }
267 MOZ_CRASH("Expected MBail in alwaysBails block");
268 }
269
270 // Given an iterator pointing to the first removed instruction, mark
271 // the operands of each removed instruction as having implicit uses.
272 [[nodiscard]] static bool FlagOperandsAsImplicitlyUsedAfter(
273 const MIRGenerator* mir, MBasicBlock* block,
274 MInstructionIterator firstRemoved) {
275 MOZ_ASSERT(firstRemoved->block() == block);
276
277 const CompileInfo& info = block->info();
278
279 // Flag operands of removed instructions as having implicit uses.
280 MInstructionIterator end = block->end();
281 for (MInstructionIterator it = firstRemoved; it != end; it++) {
282 if (mir->shouldCancel("FlagOperandsAsImplicitlyUsedAfter (loop 1)")) {
283 return false;
284 }
285
286 MInstruction* ins = *it;
287 for (size_t i = 0, e = ins->numOperands(); i < e; i++) {
288 ins->getOperand(i)->setImplicitlyUsedUnchecked();
289 }
290
291 // Flag observable resume point operands as having implicit uses.
292 if (MResumePoint* rp = ins->resumePoint()) {
293 // Note: no need to iterate over the caller's of the resume point as
294 // this is the same as the entry resume point.
295 MOZ_ASSERT(&rp->block()->info() == &info);
296 for (size_t i = 0, e = rp->numOperands(); i < e; i++) {
297 if (info.isObservableSlot(i)) {
298 rp->getOperand(i)->setImplicitlyUsedUnchecked();
299 }
300 }
301 }
302 }
303
304 // Flag Phi inputs of the successors as having implicit uses.
305 MPhiUseIteratorStack worklist;
306 for (size_t i = 0, e = block->numSuccessors(); i < e; i++) {
307 if (mir->shouldCancel("FlagOperandsAsImplicitlyUsedAfter (loop 2)")) {
308 return false;
309 }
310
311 if (!FlagPhiInputsAsImplicitlyUsed(mir, block, block->getSuccessor(i),
312 worklist)) {
313 return false;
314 }
315 }
316
317 return true;
318 }
319
320 [[nodiscard]] static bool FlagEntryResumePointOperands(const MIRGenerator* mir,
321 MBasicBlock* block) {
322 // Flag observable operands of the entry resume point as having implicit uses.
323 MResumePoint* rp = block->entryResumePoint();
324 while (rp) {
325 if (mir->shouldCancel("FlagEntryResumePointOperands")) {
326 return false;
327 }
328
329 const CompileInfo& info = rp->block()->info();
330 for (size_t i = 0, e = rp->numOperands(); i < e; i++) {
331 if (info.isObservableSlot(i)) {
332 rp->getOperand(i)->setImplicitlyUsedUnchecked();
333 }
334 }
335
336 rp = rp->caller();
337 }
338
339 return true;
340 }
341
342 [[nodiscard]] static bool FlagAllOperandsAsImplicitlyUsed(
343 const MIRGenerator* mir, MBasicBlock* block) {
344 return FlagEntryResumePointOperands(mir, block) &&
345 FlagOperandsAsImplicitlyUsedAfter(mir, block, block->begin());
346 }
347
348 // WarpBuilder sets the alwaysBails flag on blocks that contain an
349 // unconditional bailout. We trim any instructions in those blocks
350 // after the first unconditional bailout, and remove any blocks that
351 // are only reachable through bailing blocks.
352 bool jit::PruneUnusedBranches(const MIRGenerator* mir, MIRGraph& graph) {
353 JitSpew(JitSpew_Prune, "Begin");
354
355 // Pruning is guided by unconditional bailouts. Wasm does not have bailouts.
356 MOZ_ASSERT(!mir->compilingWasm());
357
358 Vector<MBasicBlock*, 16, SystemAllocPolicy> worklist;
359 uint32_t numMarked = 0;
360 bool needsTrim = false;
361
362 auto markReachable = [&](MBasicBlock* block) -> bool {
363 block->mark();
364 numMarked++;
365 if (block->alwaysBails()) {
366 needsTrim = true;
367 }
368 return worklist.append(block);
369 };
370
371 // The entry block is always reachable.
372 if (!markReachable(graph.entryBlock())) {
373 return false;
374 }
375
376 // The OSR entry block is always reachable if it exists.
377 if (graph.osrBlock() && !markReachable(graph.osrBlock())) {
378 return false;
379 }
380
381 // Iteratively mark all reachable blocks.
382 while (!worklist.empty()) {
383 if (mir->shouldCancel("Prune unused branches (marking reachable)")) {
384 return false;
385 }
386 MBasicBlock* block = worklist.popCopy();
387
388 JitSpew(JitSpew_Prune, "Visit block %u:", block->id());
389 JitSpewIndent indent(JitSpew_Prune);
390
391 // If this block always bails, then it does not reach its successors.
392 if (block->alwaysBails()) {
393 continue;
394 }
395
396 for (size_t i = 0; i < block->numSuccessors(); i++) {
397 MBasicBlock* succ = block->getSuccessor(i);
398 if (succ->isMarked()) {
399 continue;
400 }
401 JitSpew(JitSpew_Prune, "Reaches block %u", succ->id());
402 if (!markReachable(succ)) {
403 return false;
404 }
405 }
406 }
407
408 if (!needsTrim && numMarked == graph.numBlocks()) {
409 // There is nothing to prune.
410 graph.unmarkBlocks();
411 return true;
412 }
413
414 JitSpew(JitSpew_Prune, "Remove unreachable instructions and blocks:");
415 JitSpewIndent indent(JitSpew_Prune);
416
417 // The operands of removed instructions may be needed in baseline
418 // after bailing out.
419 for (PostorderIterator it(graph.poBegin()); it != graph.poEnd();) {
420 if (mir->shouldCancel("Prune unused branches (marking operands)")) {
421 return false;
422 }
423
424 MBasicBlock* block = *it++;
425 if (!block->isMarked()) {
426 // If we are removing the block entirely, mark the operands of every
427 // instruction as being implicitly used.
428 if (!FlagAllOperandsAsImplicitlyUsed(mir, block)) {
429 return false;
430 }
431 } else if (block->alwaysBails()) {
432 // If we are only trimming instructions after a bail, only mark operands
433 // of removed instructions.
434 MInstructionIterator firstRemoved = FindFirstInstructionAfterBail(block);
435 if (!FlagOperandsAsImplicitlyUsedAfter(mir, block, firstRemoved)) {
436 return false;
437 }
438 }
439 }
440
441 // Remove the blocks in post-order such that consumers are visited before
442 // the predecessors, the only exception being the Phi nodes of loop headers.
443 for (PostorderIterator it(graph.poBegin()); it != graph.poEnd();) {
444 if (mir->shouldCancel("Prune unused branches (removal loop)")) {
445 return false;
446 }
447 if (!graph.alloc().ensureBallast()) {
448 return false;
449 }
450
451 MBasicBlock* block = *it++;
452 if (block->isMarked() && !block->alwaysBails()) {
453 continue;
454 }
455
456 // As we are going to replace/remove the last instruction, we first have
457 // to remove this block from the predecessor list of its successors.
458 size_t numSucc = block->numSuccessors();
459 for (uint32_t i = 0; i < numSucc; i++) {
460 MBasicBlock* succ = block->getSuccessor(i);
461 if (succ->isDead()) {
462 continue;
463 }
464
465 // Our dominators code expects all loop headers to have two predecessors.
466 // If we are removing the normal entry to a loop, but can still reach
467 // the loop header via OSR, we create a fake unreachable predecessor.
468 if (succ->isLoopHeader() && block != succ->backedge()) {
469 MOZ_ASSERT(graph.osrBlock());
470 if (!graph.alloc().ensureBallast()) {
471 return false;
472 }
473
474 MBasicBlock* fake = MBasicBlock::NewFakeLoopPredecessor(graph, succ);
475 if (!fake) {
476 return false;
477 }
478 // Mark the block to avoid removing it as unreachable.
479 fake->mark();
480
481 JitSpew(JitSpew_Prune,
482 "Header %u only reachable by OSR. Add fake predecessor %u",
483 succ->id(), fake->id());
484 }
485
486 JitSpew(JitSpew_Prune, "Remove block edge %u -> %u.", block->id(),
487 succ->id());
488 succ->removePredecessor(block);
489 }
490
491 if (!block->isMarked()) {
492 // Remove unreachable blocks from the CFG.
493 JitSpew(JitSpew_Prune, "Remove block %u.", block->id());
494 graph.removeBlock(block);
495 } else {
496 // Remove unreachable instructions after unconditional bailouts.
497 JitSpew(JitSpew_Prune, "Trim block %u.", block->id());
498
499 // Discard all instructions after the first MBail.
500 MInstructionIterator firstRemoved = FindFirstInstructionAfterBail(block);
501 block->discardAllInstructionsStartingAt(firstRemoved);
502
503 if (block->outerResumePoint()) {
504 block->clearOuterResumePoint();
505 }
506
507 block->end(MUnreachable::New(graph.alloc()));
508 }
509 }
510 graph.unmarkBlocks();
511
512 return true;
513 }
514
515 [[nodiscard]] static bool SplitCriticalEdgesForBlock(MIRGraph& graph,
516 MBasicBlock* block) {
517 if (block->numSuccessors() < 2) {
518 return true;
519 }
520 for (size_t i = 0; i < block->numSuccessors(); i++) {
521 MBasicBlock* target = block->getSuccessor(i);
522 if (target->numPredecessors() < 2) {
523 continue;
524 }
525
526 // Create a simple new block which contains a goto and which split the
527 // edge between block and target.
528 MBasicBlock* split = MBasicBlock::NewSplitEdge(graph, block, i, target);
529 if (!split) {
530 return false;
531 }
532 }
533 return true;
534 }
535
536 // A critical edge is an edge which is neither its successor's only predecessor
537 // nor its predecessor's only successor. Critical edges must be split to
538 // prevent copy-insertion and code motion from affecting other edges.
539 bool jit::SplitCriticalEdges(MIRGraph& graph) {
540 for (MBasicBlockIterator iter(graph.begin()); iter != graph.end(); iter++) {
541 MBasicBlock* block = *iter;
542 if (!SplitCriticalEdgesForBlock(graph, block)) {
543 return false;
544 }
545 }
546 return true;
547 }
548
549 bool jit::IsUint32Type(const MDefinition* def) {
550 if (def->isBeta()) {
551 def = def->getOperand(0);
552 }
553
554 if (def->type() != MIRType::Int32) {
555 return false;
556 }
557
558 return def->isUrsh() && def->getOperand(1)->isConstant() &&
559 def->getOperand(1)->toConstant()->type() == MIRType::Int32 &&
560 def->getOperand(1)->toConstant()->toInt32() == 0;
561 }
562
563 // Determine whether phiBlock/testBlock simply compute a phi and perform a
564 // test on it.
565 static bool BlockIsSingleTest(MBasicBlock* phiBlock, MBasicBlock* testBlock,
566 MPhi** pphi, MTest** ptest) {
567 *pphi = nullptr;
568 *ptest = nullptr;
569
570 if (phiBlock != testBlock) {
571 MOZ_RELEASE_ASSERT(phiBlock->lastIns()->isGoto());
572 MOZ_RELEASE_ASSERT(phiBlock->lastIns()->toGoto()->target() == testBlock);
573 MOZ_RELEASE_ASSERT(testBlock->numPredecessors() == 1);
574 if (!phiBlock->begin()->isGoto()) {
575 return false;
576 }
577 }
578
579 auto iter = testBlock->rbegin();
580 if (!iter->isTest()) {
581 return false;
582 }
583 MTest* test = iter->toTest();
584
585 // Unwrap boolean conversion performed through the '!!' idiom.
586 MInstruction* testOrNot = test;
587 bool hasOddNumberOfNots = false;
588 while (++iter != testBlock->rend()) {
589 if (iter->isNot()) {
590 // The MNot must only be used by |testOrNot|.
591 auto* notIns = iter->toNot();
592 if (testOrNot->getOperand(0) != notIns) {
593 return false;
594 }
595 if (!notIns->hasOneUse()) {
596 return false;
597 }
598
599 testOrNot = notIns;
600 hasOddNumberOfNots = !hasOddNumberOfNots;
601 } else {
602 // Fail if there are any other instructions than MNot.
603 return false;
604 }
605 }
606
607 // There's an odd number of MNot, so this can't be the '!!' idiom.
608 if (hasOddNumberOfNots) {
609 return false;
610 }
611
612 MOZ_ASSERT(testOrNot->isTest() || testOrNot->isNot());
613
614 MDefinition* testInput = testOrNot->getOperand(0);
615 if (!testInput->isPhi()) {
616 return false;
617 }
618 MPhi* phi = testInput->toPhi();
619 if (phi->block() != phiBlock) {
620 return false;
621 }
622
623 for (MUseIterator iter = phi->usesBegin(); iter != phi->usesEnd(); ++iter) {
624 MUse* use = *iter;
625 if (use->consumer() == testOrNot) {
626 continue;
627 }
628 if (use->consumer()->isResumePoint()) {
629 MBasicBlock* useBlock = use->consumer()->block();
630 if (useBlock == phiBlock || useBlock == testBlock) {
631 continue;
632 }
633 }
634 return false;
635 }
636
637 for (MPhiIterator iter = phiBlock->phisBegin(); iter != phiBlock->phisEnd();
638 ++iter) {
639 if (*iter != phi) {
640 return false;
641 }
642 }
643
644 if (phiBlock != testBlock && !testBlock->phisEmpty()) {
645 return false;
646 }
647
648 *pphi = phi;
649 *ptest = test;
650
651 return true;
652 }
653
654 // Determine if value is directly or indirectly the test input.
655 static bool IsTestInputMaybeToBool(MTest* test, MDefinition* value) {
656 auto* input = test->input();
657 bool hasEvenNumberOfNots = true;
658 while (true) {
659 // Only accept if there's an even number of MNot.
660 if (input == value && hasEvenNumberOfNots) {
661 return true;
662 }
663
664 // Unwrap boolean conversion performed through the '!!' idiom.
665 if (input->isNot()) {
666 input = input->toNot()->input();
667 hasEvenNumberOfNots = !hasEvenNumberOfNots;
668 continue;
669 }
670
671 return false;
672 }
673 }
674
675 // Change |block| so that it ends in a goto to the specific |target| block.
676 // |existingPred| is an existing predecessor of the block.
677 //
678 // |blockResult| is the value computed by |block|. This was a phi input but the
679 // caller has determined that |blockResult| matches the input of an earlier
680 // MTest instruction and we don't need to test it a second time. Mark it as
681 // implicitly-used because we're removing a use.
682 [[nodiscard]] static bool UpdateGotoSuccessor(TempAllocator& alloc,
683 MBasicBlock* block,
684 MDefinition* blockResult,
685 MBasicBlock* target,
686 MBasicBlock* existingPred) {
687 blockResult->setImplicitlyUsedUnchecked();
688
689 MInstruction* ins = block->lastIns();
690 MOZ_RELEASE_ASSERT(ins->isGoto());
691 ins->toGoto()->target()->removePredecessor(block);
692 block->discardLastIns();
693
694 MGoto* newGoto = MGoto::New(alloc, target);
695 block->end(newGoto);
696
697 return target->addPredecessorSameInputsAs(block, existingPred);
698 }
699
700 // Change block so that it ends in a test of the specified value, going to
701 // either ifTrue or ifFalse. existingPred is an existing predecessor of ifTrue
702 // or ifFalse with the same values incoming to ifTrue/ifFalse as block.
703 // existingPred is not required to be a predecessor of ifTrue/ifFalse if block
704 // already ends in a test going to that block on a true/false result.
705 [[nodiscard]] static bool UpdateTestSuccessors(
706 TempAllocator& alloc, MBasicBlock* block, MDefinition* value,
707 MBasicBlock* ifTrue, MBasicBlock* ifFalse, MBasicBlock* existingPred) {
708 MInstruction* ins = block->lastIns();
709 if (ins->isTest()) {
710 MTest* test = ins->toTest();
711 MOZ_RELEASE_ASSERT(test->input() == value);
712
713 if (ifTrue != test->ifTrue()) {
714 test->ifTrue()->removePredecessor(block);
715 if (!ifTrue->addPredecessorSameInputsAs(block, existingPred)) {
716 return false;
717 }
718 test->replaceSuccessor(MTest::TrueBranchIndex, ifTrue);
719 }
720
721 if (ifFalse != test->ifFalse()) {
722 test->ifFalse()->removePredecessor(block);
723 if (!ifFalse->addPredecessorSameInputsAs(block, existingPred)) {
724 return false;
725 }
726 test->replaceSuccessor(MTest::FalseBranchIndex, ifFalse);
727 }
728
729 return true;
730 }
731
732 MOZ_RELEASE_ASSERT(ins->isGoto());
733 ins->toGoto()->target()->removePredecessor(block);
734 block->discardLastIns();
735
736 MTest* test = MTest::New(alloc, value, ifTrue, ifFalse);
737 block->end(test);
738
739 if (!ifTrue->addPredecessorSameInputsAs(block, existingPred)) {
740 return false;
741 }
742 if (!ifFalse->addPredecessorSameInputsAs(block, existingPred)) {
743 return false;
744 }
745 return true;
746 }
747
748 /*
749 * Look for a diamond pattern:
750 *
751 * initialBlock
752 * / \
753 * trueBranch falseBranch
754 * \ /
755 * phiBlock
756 * |
757 * testBlock
758 */
759 static bool IsDiamondPattern(MBasicBlock* initialBlock) {
760 MInstruction* ins = initialBlock->lastIns();
761 if (!ins->isTest()) {
762 return false;
763 }
764 MTest* initialTest = ins->toTest();
765
766 MBasicBlock* trueBranch = initialTest->ifTrue();
767 if (trueBranch->numPredecessors() != 1 || !trueBranch->lastIns()->isGoto()) {
768 return false;
769 }
770
771 MBasicBlock* falseBranch = initialTest->ifFalse();
772 if (falseBranch->numPredecessors() != 1 ||
773 !falseBranch->lastIns()->isGoto()) {
774 return false;
775 }
776
777 MBasicBlock* phiBlock = trueBranch->lastIns()->toGoto()->target();
778 if (phiBlock != falseBranch->lastIns()->toGoto()->target()) {
779 return false;
780 }
781 if (phiBlock->numPredecessors() != 2) {
782 return false;
783 }
784 return true;
785 }
786
787 [[nodiscard]] static bool MaybeFoldDiamondConditionBlock(
788 MIRGraph& graph, MBasicBlock* initialBlock) {
789 MOZ_ASSERT(IsDiamondPattern(initialBlock));
790
791 // Optimize the MIR graph to improve the code generated for conditional
792 // operations. A test like 'if (a ? b : c)' normally requires four blocks,
793 // with a phi for the intermediate value. This can be improved to use three
794 // blocks with no phi value.
795
796 /*
797 * Look for a diamond pattern:
798 *
799 * initialBlock
800 * / \
801 * trueBranch falseBranch
802 * \ /
803 * phiBlock
804 * |
805 * testBlock
806 *
807 * Where phiBlock contains a single phi combining values pushed onto the
808 * stack by trueBranch and falseBranch, and testBlock contains a test on
809 * that phi. phiBlock and testBlock may be the same block; generated code
810 * will use different blocks if the (?:) op is in an inlined function.
811 */
812
813 MTest* initialTest = initialBlock->lastIns()->toTest();
814
815 MBasicBlock* trueBranch = initialTest->ifTrue();
816 MBasicBlock* falseBranch = initialTest->ifFalse();
817 if (initialBlock->isLoopBackedge() || trueBranch->isLoopBackedge() ||
818 falseBranch->isLoopBackedge()) {
819 return true;
820 }
821
822 MBasicBlock* phiBlock = trueBranch->lastIns()->toGoto()->target();
823 MBasicBlock* testBlock = phiBlock;
824 if (testBlock->lastIns()->isGoto()) {
825 if (testBlock->isLoopBackedge()) {
826 return true;
827 }
828 testBlock = testBlock->lastIns()->toGoto()->target();
829 if (testBlock->numPredecessors() != 1) {
830 return true;
831 }
832 }
833
834 MPhi* phi;
835 MTest* finalTest;
836 if (!BlockIsSingleTest(phiBlock, testBlock, &phi, &finalTest)) {
837 return true;
838 }
839
840 MOZ_RELEASE_ASSERT(phi->numOperands() == 2);
841
842 // Make sure the test block does not have any outgoing loop backedges.
843 if (!SplitCriticalEdgesForBlock(graph, testBlock)) {
844 return false;
845 }
846
847 MDefinition* trueResult =
848 phi->getOperand(phiBlock->indexForPredecessor(trueBranch));
849 MDefinition* falseResult =
850 phi->getOperand(phiBlock->indexForPredecessor(falseBranch));
851
852 // OK, we found the desired pattern, now transform the graph.
853
854 // Remove the phi from phiBlock.
855 phiBlock->discardPhi(*phiBlock->phisBegin());
856
857 // Change the end of the block to a test that jumps directly to successors of
858 // testBlock, rather than to testBlock itself.
859
860 if (IsTestInputMaybeToBool(initialTest, trueResult)) {
861 if (!UpdateGotoSuccessor(graph.alloc(), trueBranch, trueResult,
862 finalTest->ifTrue(), testBlock)) {
863 return false;
864 }
865 } else {
866 if (!UpdateTestSuccessors(graph.alloc(), trueBranch, trueResult,
867 finalTest->ifTrue(), finalTest->ifFalse(),
868 testBlock)) {
869 return false;
870 }
871 }
872
873 if (IsTestInputMaybeToBool(initialTest, falseResult)) {
874 if (!UpdateGotoSuccessor(graph.alloc(), falseBranch, falseResult,
875 finalTest->ifFalse(), testBlock)) {
876 return false;
877 }
878 } else {
879 if (!UpdateTestSuccessors(graph.alloc(), falseBranch, falseResult,
880 finalTest->ifTrue(), finalTest->ifFalse(),
881 testBlock)) {
882 return false;
883 }
884 }
885
886 // Remove phiBlock, if different from testBlock.
887 if (phiBlock != testBlock) {
888 testBlock->removePredecessor(phiBlock);
889 graph.removeBlock(phiBlock);
890 }
891
892 // Remove testBlock itself.
893 finalTest->ifTrue()->removePredecessor(testBlock);
894 finalTest->ifFalse()->removePredecessor(testBlock);
895 graph.removeBlock(testBlock);
896
897 return true;
898 }
899
900 /*
901 * Look for a triangle pattern:
902 *
903 * initialBlock
904 * / \
905 * trueBranch |
906 * \ /
907 * phiBlock+falseBranch
908 * |
909 * testBlock
910 *
911 * Or:
912 *
913 * initialBlock
914 * / \
915 * | falseBranch
916 * \ /
917 * phiBlock+trueBranch
918 * |
919 * testBlock
920 */
921 static bool IsTrianglePattern(MBasicBlock* initialBlock) {
922 MInstruction* ins = initialBlock->lastIns();
923 if (!ins->isTest()) {
924 return false;
925 }
926 MTest* initialTest = ins->toTest();
927
928 MBasicBlock* trueBranch = initialTest->ifTrue();
929 MBasicBlock* falseBranch = initialTest->ifFalse();
930
931 if (trueBranch->lastIns()->isGoto() &&
932 trueBranch->lastIns()->toGoto()->target() == falseBranch) {
933 if (trueBranch->numPredecessors() != 1) {
934 return false;
935 }
936 if (falseBranch->numPredecessors() != 2) {
937 return false;
938 }
939 return true;
940 }
941
942 if (falseBranch->lastIns()->isGoto() &&
943 falseBranch->lastIns()->toGoto()->target() == trueBranch) {
944 if (trueBranch->numPredecessors() != 2) {
945 return false;
946 }
947 if (falseBranch->numPredecessors() != 1) {
948 return false;
949 }
950 return true;
951 }
952
953 return false;
954 }
955
956 [[nodiscard]] static bool MaybeFoldTriangleConditionBlock(
957 MIRGraph& graph, MBasicBlock* initialBlock) {
958 MOZ_ASSERT(IsTrianglePattern(initialBlock));
959
960 // Optimize the MIR graph to improve the code generated for boolean
961 // operations. A test like 'if (a && b)' normally requires three blocks, with
962 // a phi for the intermediate value. This can be improved to use no phi value.
963
964 /*
965 * Look for a triangle pattern:
966 *
967 * initialBlock
968 * / \
969 * trueBranch |
970 * \ /
971 * phiBlock+falseBranch
972 * |
973 * testBlock
974 *
975 * Or:
976 *
977 * initialBlock
978 * / \
979 * | falseBranch
980 * \ /
981 * phiBlock+trueBranch
982 * |
983 * testBlock
984 *
985 * Where phiBlock contains a single phi combining values pushed onto the stack
986 * by trueBranch and falseBranch, and testBlock contains a test on that phi.
987 * phiBlock and testBlock may be the same block; generated code will use
988 * different blocks if the (&&) op is in an inlined function.
989 */
990
991 MTest* initialTest = initialBlock->lastIns()->toTest();
992
993 MBasicBlock* trueBranch = initialTest->ifTrue();
994 MBasicBlock* falseBranch = initialTest->ifFalse();
995 if (initialBlock->isLoopBackedge() || trueBranch->isLoopBackedge() ||
996 falseBranch->isLoopBackedge()) {
997 return true;
998 }
999
1000 MBasicBlock* phiBlock;
1001 if (trueBranch->lastIns()->isGoto() &&
1002 trueBranch->lastIns()->toGoto()->target() == falseBranch) {
1003 phiBlock = falseBranch;
1004 } else {
1005 MOZ_ASSERT(falseBranch->lastIns()->toGoto()->target() == trueBranch);
1006 phiBlock = trueBranch;
1007 }
1008
1009 MBasicBlock* testBlock = phiBlock;
1010 if (testBlock->lastIns()->isGoto()) {
1011 MOZ_RELEASE_ASSERT(!testBlock->isLoopBackedge());
1012
1013 testBlock = testBlock->lastIns()->toGoto()->target();
1014 if (testBlock->numPredecessors() != 1) {
1015 return true;
1016 }
1017 }
1018
1019 MPhi* phi;
1020 MTest* finalTest;
1021 if (!BlockIsSingleTest(phiBlock, testBlock, &phi, &finalTest)) {
1022 return true;
1023 }
1024
1025 MOZ_RELEASE_ASSERT(phi->numOperands() == 2);
1026
1027 // If the phi-operand doesn't match the initial input, we can't fold the test.
1028 auto* phiInputForInitialBlock =
1029 phi->getOperand(phiBlock->indexForPredecessor(initialBlock));
1030 if (!IsTestInputMaybeToBool(initialTest, phiInputForInitialBlock)) {
1031 return true;
1032 }
1033
1034 // Make sure the test block does not have any outgoing loop backedges.
1035 if (!SplitCriticalEdgesForBlock(graph, testBlock)) {
1036 return false;
1037 }
1038
1039 MDefinition* trueResult;
1040 MDefinition* falseResult;
1041 if (phiBlock == trueBranch) {
1042 trueResult = phi->getOperand(phiBlock->indexForPredecessor(initialBlock));
1043 falseResult = phi->getOperand(phiBlock->indexForPredecessor(falseBranch));
1044 } else {
1045 trueResult = phi->getOperand(phiBlock->indexForPredecessor(trueBranch));
1046 falseResult = phi->getOperand(phiBlock->indexForPredecessor(initialBlock));
1047 }
1048
1049 // OK, we found the desired pattern, now transform the graph.
1050
1051 // Remove the phi from phiBlock.
1052 phiBlock->discardPhi(*phiBlock->phisBegin());
1053
1054 // Change the end of the block to a test that jumps directly to successors of
1055 // testBlock, rather than to testBlock itself.
1056
1057 if (phiBlock == trueBranch) {
1058 if (!UpdateTestSuccessors(graph.alloc(), initialBlock, initialTest->input(),
1059 finalTest->ifTrue(), initialTest->ifFalse(),
1060 testBlock)) {
1061 return false;
1062 }
1063 } else if (IsTestInputMaybeToBool(initialTest, trueResult)) {
1064 if (!UpdateGotoSuccessor(graph.alloc(), trueBranch, trueResult,
1065 finalTest->ifTrue(), testBlock)) {
1066 return false;
1067 }
1068 } else {
1069 if (!UpdateTestSuccessors(graph.alloc(), trueBranch, trueResult,
1070 finalTest->ifTrue(), finalTest->ifFalse(),
1071 testBlock)) {
1072 return false;
1073 }
1074 }
1075
1076 if (phiBlock == falseBranch) {
1077 if (!UpdateTestSuccessors(graph.alloc(), initialBlock, initialTest->input(),
1078 initialTest->ifTrue(), finalTest->ifFalse(),
1079 testBlock)) {
1080 return false;
1081 }
1082 } else if (IsTestInputMaybeToBool(initialTest, falseResult)) {
1083 if (!UpdateGotoSuccessor(graph.alloc(), falseBranch, falseResult,
1084 finalTest->ifFalse(), testBlock)) {
1085 return false;
1086 }
1087 } else {
1088 if (!UpdateTestSuccessors(graph.alloc(), falseBranch, falseResult,
1089 finalTest->ifTrue(), finalTest->ifFalse(),
1090 testBlock)) {
1091 return false;
1092 }
1093 }
1094
1095 // Remove phiBlock, if different from testBlock.
1096 if (phiBlock != testBlock) {
1097 testBlock->removePredecessor(phiBlock);
1098 graph.removeBlock(phiBlock);
1099 }
1100
1101 // Remove testBlock itself.
1102 finalTest->ifTrue()->removePredecessor(testBlock);
1103 finalTest->ifFalse()->removePredecessor(testBlock);
1104 graph.removeBlock(testBlock);
1105
1106 return true;
1107 }
1108
1109 [[nodiscard]] static bool MaybeFoldConditionBlock(MIRGraph& graph,
1110 MBasicBlock* initialBlock) {
1111 if (IsDiamondPattern(initialBlock)) {
1112 return MaybeFoldDiamondConditionBlock(graph, initialBlock);
1113 }
1114 if (IsTrianglePattern(initialBlock)) {
1115 return MaybeFoldTriangleConditionBlock(graph, initialBlock);
1116 }
1117 return true;
1118 }
1119
1120 [[nodiscard]] static bool MaybeFoldTestBlock(MIRGraph& graph,
1121 MBasicBlock* initialBlock) {
1122 // Handle test expressions on more than two inputs. For example
1123 // |if ((x > 10) && (y > 20) && (z > 30)) { ... }|, which results in the below
1124 // pattern.
1125 //
1126 // Look for the pattern:
1127 // ┌─────────────────┐
1128 // 1 │ 1 compare │
1129 // ┌─────┤ 2 test compare1 │
1130 // │ └──────┬──────────┘
1131 // │ │0
1132 // ┌───────▼─────────┐ │
1133 // │ 3 compare │ │
1134 // │ 4 test compare3 │ └──────────┐
1135 // └──┬──────────┬───┘ │
1136 // 1│ │0 │
1137 // ┌──────────▼──────┐ │ │
1138 // │ 5 compare │ └─────────┐ │
1139 // │ 6 goto │ │ │
1140 // └───────┬─────────┘ │ │
1141 // │ │ │
1142 // │ ┌──────────────────▼───────▼───────┐
1143 // └───►│ 9 phi compare1 compare3 compare5 │
1144 // │10 goto │
1145 // └────────────────┬─────────────────┘
1146 // │
1147 // ┌────────▼────────┐
1148 // │11 test phi9 │
1149 // └─────┬─────┬─────┘
1150 // 1│ │0
1151 // ┌────────────┐ │ │ ┌─────────────┐
1152 // │ TrueBranch │◄────┘ └─────►│ FalseBranch │
1153 // └────────────┘ └─────────────┘
1154 //
1155 // And transform it to:
1156 //
1157 // ┌─────────────────┐
1158 // 1 │ 1 compare │
1159 // ┌───┤ 2 test compare1 │
1160 // │ └──────────┬──────┘
1161 // │ │0
1162 // ┌───────▼─────────┐ │
1163 // │ 3 compare │ │
1164 // │ 4 test compare3 │ │
1165 // └──┬─────────┬────┘ │
1166 // 1│ │0 │
1167 // ┌──────────▼──────┐ │ │
1168 // │ 5 compare │ └──────┐ │
1169 // │ 6 test compare5 │ │ │
1170 // └────┬────────┬───┘ │ │
1171 // 1│ │0 │ │
1172 // ┌─────▼──────┐ │ ┌───▼──▼──────┐
1173 // │ TrueBranch │ └─────────► FalseBranch │
1174 // └────────────┘ └─────────────┘
1175
1176 auto* ins = initialBlock->lastIns();
1177 if (!ins->isTest()) {
1178 return true;
1179 }
1180 auto* initialTest = ins->toTest();
1181
1182 MBasicBlock* trueBranch = initialTest->ifTrue();
1183 MBasicBlock* falseBranch = initialTest->ifFalse();
1184
1185 // MaybeFoldConditionBlock handles the case for two operands.
1186 MBasicBlock* phiBlock;
1187 if (trueBranch->numPredecessors() > 2) {
1188 phiBlock = trueBranch;
1189 } else if (falseBranch->numPredecessors() > 2) {
1190 phiBlock = falseBranch;
1191 } else {
1192 return true;
1193 }
1194
1195 MBasicBlock* testBlock = phiBlock;
1196 if (testBlock->lastIns()->isGoto()) {
1197 if (testBlock->isLoopBackedge()) {
1198 return true;
1199 }
1200 testBlock = testBlock->lastIns()->toGoto()->target();
1201 if (testBlock->numPredecessors() != 1) {
1202 return true;
1203 }
1204 }
1205
1206 MOZ_RELEASE_ASSERT(!phiBlock->isLoopBackedge());
1207
1208 MPhi* phi = nullptr;
1209 MTest* finalTest = nullptr;
1210 if (!BlockIsSingleTest(phiBlock, testBlock, &phi, &finalTest)) {
1211 return true;
1212 }
1213
1214 MOZ_RELEASE_ASSERT(phiBlock->numPredecessors() == phi->numOperands());
1215
1216 // If the phi-operand doesn't match the initial input, we can't fold the test.
1217 auto* phiInputForInitialBlock =
1218 phi->getOperand(phiBlock->indexForPredecessor(initialBlock));
1219 if (!IsTestInputMaybeToBool(initialTest, phiInputForInitialBlock)) {
1220 return true;
1221 }
1222
1223 MBasicBlock* newTestBlock = nullptr;
1224 MDefinition* newTestInput = nullptr;
1225
1226 // The block of each phi operand must either end with a test instruction on
1227 // that phi operand or it's the sole block which ends with a goto instruction.
1228 for (size_t i = 0; i < phiBlock->numPredecessors(); i++) {
1229 auto* pred = phiBlock->getPredecessor(i);
1230 auto* operand = phi->getOperand(i);
1231
1232 // Each predecessor must end with either a test or goto instruction.
1233 auto* lastIns = pred->lastIns();
1234 if (lastIns->isGoto() && !newTestBlock) {
1235 newTestBlock = pred;
1236 newTestInput = operand;
1237 } else if (lastIns->isTest()) {
1238 if (!IsTestInputMaybeToBool(lastIns->toTest(), operand)) {
1239 return true;
1240 }
1241 } else {
1242 return true;
1243 }
1244
1245 MOZ_RELEASE_ASSERT(!pred->isLoopBackedge());
1246 }
1247
1248 // Ensure we found the single goto block.
1249 if (!newTestBlock) {
1250 return true;
1251 }
1252
1253 // Make sure the test block does not have any outgoing loop backedges.
1254 if (!SplitCriticalEdgesForBlock(graph, testBlock)) {
1255 return false;
1256 }
1257
1258 // OK, we found the desired pattern, now transform the graph.
1259
1260 // Remove the phi from phiBlock.
1261 phiBlock->discardPhi(*phiBlock->phisBegin());
1262
1263 // Create the new test instruction.
1264 if (!UpdateTestSuccessors(graph.alloc(), newTestBlock, newTestInput,
1265 finalTest->ifTrue(), finalTest->ifFalse(),
1266 testBlock)) {
1267 return false;
1268 }
1269
1270 // Update all test instructions to point to the final target.
1271 while (phiBlock->numPredecessors()) {
1272 size_t oldNumPred = phiBlock->numPredecessors();
1273
1274 auto* pred = phiBlock->getPredecessor(0);
1275 auto* test = pred->lastIns()->toTest();
1276 if (test->ifTrue() == phiBlock) {
1277 if (!UpdateTestSuccessors(graph.alloc(), pred, test->input(),
1278 finalTest->ifTrue(), test->ifFalse(),
1279 testBlock)) {
1280 return false;
1281 }
1282 } else {
1283 MOZ_RELEASE_ASSERT(test->ifFalse() == phiBlock);
1284 if (!UpdateTestSuccessors(graph.alloc(), pred, test->input(),
1285 test->ifTrue(), finalTest->ifFalse(),
1286 testBlock)) {
1287 return false;
1288 }
1289 }
1290
1291 // Ensure we've made progress.
1292 MOZ_RELEASE_ASSERT(phiBlock->numPredecessors() + 1 == oldNumPred);
1293 }
1294
1295 // Remove phiBlock, if different from testBlock.
1296 if (phiBlock != testBlock) {
1297 testBlock->removePredecessor(phiBlock);
1298 graph.removeBlock(phiBlock);
1299 }
1300
1301 // Remove testBlock itself.
1302 finalTest->ifTrue()->removePredecessor(testBlock);
1303 finalTest->ifFalse()->removePredecessor(testBlock);
1304 graph.removeBlock(testBlock);
1305
1306 return true;
1307 }
1308
1309 bool jit::FoldTests(MIRGraph& graph) {
1310 for (PostorderIterator block(graph.poBegin()); block != graph.poEnd();
1311 block++) {
1312 if (!MaybeFoldConditionBlock(graph, *block)) {
1313 return false;
1314 }
1315 if (!MaybeFoldTestBlock(graph, *block)) {
1316 return false;
1317 }
1318 }
1319 return true;
1320 }
1321
1322 bool jit::FoldEmptyBlocks(MIRGraph& graph, bool* changed) {
1323 *changed = false;
1324
1325 for (MBasicBlockIterator iter(graph.begin()); iter != graph.end();) {
1326 MBasicBlock* block = *iter;
1327 iter++;
1328
1329 if (block->numPredecessors() != 1 || block->numSuccessors() != 1) {
1330 continue;
1331 }
1332
1333 if (!block->phisEmpty()) {
1334 continue;
1335 }
1336
1337 if (block->outerResumePoint()) {
1338 continue;
1339 }
1340
1341 if (*block->begin() != *block->rbegin()) {
1342 continue;
1343 }
1344
1345 MBasicBlock* succ = block->getSuccessor(0);
1346 MBasicBlock* pred = block->getPredecessor(0);
1347
1348 if (succ->numPredecessors() != 1) {
1349 continue;
1350 }
1351
1352 size_t pos = pred->getSuccessorIndex(block);
1353 pred->lastIns()->replaceSuccessor(pos, succ);
1354
1355 graph.removeBlock(block);
1356
1357 if (!succ->addPredecessorSameInputsAs(pred, block)) {
1358 return false;
1359 }
1360 succ->removePredecessor(block);
1361
1362 *changed = true;
1363 }
1364 return true;
1365 }
1366
1367 static void EliminateTriviallyDeadResumePointOperands(MIRGraph& graph,
1368 MResumePoint* rp) {
1369 // If we will pop the top of the stack immediately after resuming,
1370 // then don't preserve the top value in the resume point.
1371 if (rp->mode() != ResumeMode::ResumeAt) {
1372 return;
1373 }
1374
1375 jsbytecode* pc = rp->pc();
1376 if (JSOp(*pc) == JSOp::JumpTarget) {
1377 pc += JSOpLength_JumpTarget;
1378 }
1379 if (JSOp(*pc) != JSOp::Pop) {
1380 return;
1381 }
1382
1383 size_t top = rp->stackDepth() - 1;
1384 MOZ_ASSERT(!rp->isObservableOperand(top));
1385
1386 MDefinition* def = rp->getOperand(top);
1387 if (def->isConstant()) {
1388 return;
1389 }
1390
1391 MConstant* constant = rp->block()->optimizedOutConstant(graph.alloc());
1392 rp->replaceOperand(top, constant);
1393 }
1394
1395 // Operands to a resume point which are dead at the point of the resume can be
1396 // replaced with a magic value. This pass only replaces resume points which are
1397 // trivially dead.
1398 //
1399 // This is intended to ensure that extra resume points within a basic block
1400 // will not artificially extend the lifetimes of any SSA values. This could
1401 // otherwise occur if the new resume point captured a value which is created
1402 // between the old and new resume point and is dead at the new resume point.
1403 bool jit::EliminateTriviallyDeadResumePointOperands(const MIRGenerator* mir,
1404 MIRGraph& graph) {
1405 for (auto* block : graph) {
1406 if (MResumePoint* rp = block->entryResumePoint()) {
1407 if (!graph.alloc().ensureBallast()) {
1408 return false;
1409 }
1410 ::EliminateTriviallyDeadResumePointOperands(graph, rp);
1411 }
1412 }
1413 return true;
1414 }
1415
1416 // Operands to a resume point which are dead at the point of the resume can be
1417 // replaced with a magic value. This analysis supports limited detection of
1418 // dead operands, pruning those which are defined in the resume point's basic
1419 // block and have no uses outside the block or at points later than the resume
1420 // point.
1421 //
1422 // This is intended to ensure that extra resume points within a basic block
1423 // will not artificially extend the lifetimes of any SSA values. This could
1424 // otherwise occur if the new resume point captured a value which is created
1425 // between the old and new resume point and is dead at the new resume point.
1426 bool jit::EliminateDeadResumePointOperands(const MIRGenerator* mir,
1427 MIRGraph& graph) {
1428 // If we are compiling try blocks, locals and arguments may be observable
1429 // from catch or finally blocks (which Ion does not compile). For now just
1430 // disable the pass in this case.
1431 if (graph.hasTryBlock()) {
1432 return true;
1433 }
1434
1435 for (PostorderIterator block = graph.poBegin(); block != graph.poEnd();
1436 block++) {
1437 if (mir->shouldCancel("Eliminate Dead Resume Point Operands (main loop)")) {
1438 return false;
1439 }
1440
1441 if (MResumePoint* rp = block->entryResumePoint()) {
1442 if (!graph.alloc().ensureBallast()) {
1443 return false;
1444 }
1445 ::EliminateTriviallyDeadResumePointOperands(graph, rp);
1446 }
1447
1448 // The logic below can get confused on infinite loops.
1449 if (block->isLoopHeader() && block->backedge() == *block) {
1450 continue;
1451 }
1452
1453 for (MInstructionIterator ins = block->begin(); ins != block->end();
1454 ins++) {
1455 if (MResumePoint* rp = ins->resumePoint()) {
1456 if (!graph.alloc().ensureBallast()) {
1457 return false;
1458 }
1459 ::EliminateTriviallyDeadResumePointOperands(graph, rp);
1460 }
1461
1462 // No benefit to replacing constant operands with other constants.
1463 if (ins->isConstant()) {
1464 continue;
1465 }
1466
1467 // Scanning uses does not give us sufficient information to tell
1468 // where instructions that are involved in box/unbox operations or
1469 // parameter passing might be live. Rewriting uses of these terms
1470 // in resume points may affect the interpreter's behavior. Rather
1471 // than doing a more sophisticated analysis, just ignore these.
1472 if (ins->isUnbox() || ins->isParameter() || ins->isBoxNonStrictThis()) {
1473 continue;
1474 }
1475
1476 // Early intermediate values captured by resume points, such as
1477 // ArrayState and its allocation, may be legitimately dead in Ion code,
1478 // but are still needed if we bail out. They can recover on bailout.
1479 if (ins->isRecoveredOnBailout()) {
1480 MOZ_ASSERT(ins->canRecoverOnBailout());
1481 continue;
1482 }
1483
1484 // If the instruction's behavior has been constant folded into a
1485 // separate instruction, we can't determine precisely where the
1486 // instruction becomes dead and can't eliminate its uses.
1487 if (ins->isImplicitlyUsed()) {
1488 continue;
1489 }
1490
1491 // Check if this instruction's result is only used within the
1492 // current block, and keep track of its last use in a definition
1493 // (not resume point). This requires the instructions in the block
1494 // to be numbered, ensured by running this immediately after alias
1495 // analysis.
1496 uint32_t maxDefinition = 0;
1497 for (MUseIterator uses(ins->usesBegin()); uses != ins->usesEnd();
1498 uses++) {
1499 MNode* consumer = uses->consumer();
1500 if (consumer->isResumePoint()) {
1501 // If the instruction's is captured by one of the resume point, then
1502 // it might be observed indirectly while the frame is live on the
1503 // stack, so it has to be computed.
1504 MResumePoint* resume = consumer->toResumePoint();
1505 if (resume->isObservableOperand(*uses)) {
1506 maxDefinition = UINT32_MAX;
1507 break;
1508 }
1509 continue;
1510 }
1511
1512 MDefinition* def = consumer->toDefinition();
1513 if (def->block() != *block || def->isBox() || def->isPhi()) {
1514 maxDefinition = UINT32_MAX;
1515 break;
1516 }
1517 maxDefinition = std::max(maxDefinition, def->id());
1518 }
1519 if (maxDefinition == UINT32_MAX) {
1520 continue;
1521 }
1522
1523 // Walk the uses a second time, removing any in resume points after
1524 // the last use in a definition.
1525 for (MUseIterator uses(ins->usesBegin()); uses != ins->usesEnd();) {
1526 MUse* use = *uses++;
1527 if (use->consumer()->isDefinition()) {
1528 continue;
1529 }
1530 MResumePoint* mrp = use->consumer()->toResumePoint();
1531 if (mrp->block() != *block || !mrp->instruction() ||
1532 mrp->instruction() == *ins ||
1533 mrp->instruction()->id() <= maxDefinition) {
1534 continue;
1535 }
1536
1537 if (!graph.alloc().ensureBallast()) {
1538 return false;
1539 }
1540
1541 // Store an optimized out magic value in place of all dead
1542 // resume point operands. Making any such substitution can in
1543 // general alter the interpreter's behavior, even though the
1544 // code is dead, as the interpreter will still execute opcodes
1545 // whose effects cannot be observed. If the magic value value
1546 // were to flow to, say, a dead property access the
1547 // interpreter could throw an exception; we avoid this problem
1548 // by removing dead operands before removing dead code.
1549 MConstant* constant =
1550 MConstant::New(graph.alloc(), MagicValue(JS_OPTIMIZED_OUT));
1551 block->insertBefore(*(block->begin()), constant);
1552 use->replaceProducer(constant);
1553 }
1554 }
1555 }
1556
1557 return true;
1558 }
1559
1560 // Test whether |def| would be needed if it had no uses.
1561 bool js::jit::DeadIfUnused(const MDefinition* def) {
1562 // Effectful instructions of course cannot be removed.
1563 if (def->isEffectful()) {
1564 return false;
1565 }
1566
1567 // Never eliminate guard instructions.
1568 if (def->isGuard()) {
1569 return false;
1570 }
1571
1572 // Required to be preserved, as the type guard related to this instruction
1573 // is part of the semantics of a transformation.
1574 if (def->isGuardRangeBailouts()) {
1575 return false;
1576 }
1577
1578 // Control instructions have no uses, but also shouldn't be optimized out
1579 if (def->isControlInstruction()) {
1580 return false;
1581 }
1582
1583 // Used when lowering to generate the corresponding snapshots and aggregate
1584 // the list of recover instructions to be repeated.
1585 if (def->isInstruction() && def->toInstruction()->resumePoint()) {
1586 return false;
1587 }
1588
1589 return true;
1590 }
1591
1592 // Similar to DeadIfUnused(), but additionally allows effectful instructions.
1593 bool js::jit::DeadIfUnusedAllowEffectful(const MDefinition* def) {
1594 // Never eliminate guard instructions.
1595 if (def->isGuard()) {
1596 return false;
1597 }
1598
1599 // Required to be preserved, as the type guard related to this instruction
1600 // is part of the semantics of a transformation.
1601 if (def->isGuardRangeBailouts()) {
1602 return false;
1603 }
1604
1605 // Control instructions have no uses, but also shouldn't be optimized out
1606 if (def->isControlInstruction()) {
1607 return false;
1608 }
1609
1610 // Used when lowering to generate the corresponding snapshots and aggregate
1611 // the list of recover instructions to be repeated.
1612 if (def->isInstruction() && def->toInstruction()->resumePoint()) {
1613 // All effectful instructions must have a resume point attached. We're
1614 // allowing effectful instructions here, so we have to ignore any resume
1615 // points if we want to consider effectful instructions as dead.
1616 if (!def->isEffectful()) {
1617 return false;
1618 }
1619 }
1620
1621 return true;
1622 }
1623
1624 // Test whether |def| may be safely discarded, due to being dead or due to being
1625 // located in a basic block which has itself been marked for discarding.
1626 bool js::jit::IsDiscardable(const MDefinition* def) {
1627 return !def->hasUses() && (DeadIfUnused(def) || def->block()->isMarked());
1628 }
1629
1630 // Similar to IsDiscardable(), but additionally allows effectful instructions.
1631 bool js::jit::IsDiscardableAllowEffectful(const MDefinition* def) {
1632 return !def->hasUses() &&
1633 (DeadIfUnusedAllowEffectful(def) || def->block()->isMarked());
1634 }
1635
1636 // Instructions are useless if they are unused and have no side effects.
1637 // This pass eliminates useless instructions.
1638 // The graph itself is unchanged.
1639 bool jit::EliminateDeadCode(const MIRGenerator* mir, MIRGraph& graph) {
1640 // Traverse in postorder so that we hit uses before definitions.
1641 // Traverse instruction list backwards for the same reason.
1642 for (PostorderIterator block = graph.poBegin(); block != graph.poEnd();
1643 block++) {
1644 if (mir->shouldCancel("Eliminate Dead Code (main loop)")) {
1645 return false;
1646 }
1647
1648 // Remove unused instructions.
1649 for (MInstructionReverseIterator iter = block->rbegin();
1650 iter != block->rend();) {
1651 MInstruction* inst = *iter++;
1652 if (js::jit::IsDiscardable(inst)) {
1653 block->discard(inst);
1654 }
1655 }
1656 }
1657
1658 return true;
1659 }
1660
1661 static inline bool IsPhiObservable(MPhi* phi, Observability observe) {
1662 // If the phi has uses which are not reflected in SSA, then behavior in the
1663 // interpreter may be affected by removing the phi.
1664 if (phi->isImplicitlyUsed()) {
1665 return true;
1666 }
1667
1668 // Check for uses of this phi node outside of other phi nodes.
1669 // Note that, initially, we skip reading resume points, which we
1670 // don't count as actual uses. If the only uses are resume points,
1671 // then the SSA name is never consumed by the program. However,
1672 // after optimizations have been performed, it's possible that the
1673 // actual uses in the program have been (incorrectly) optimized
1674 // away, so we must be more conservative and consider resume
1675 // points as well.
1676 for (MUseIterator iter(phi->usesBegin()); iter != phi->usesEnd(); iter++) {
1677 MNode* consumer = iter->consumer();
1678 if (consumer->isResumePoint()) {
1679 MResumePoint* resume = consumer->toResumePoint();
1680 if (observe == ConservativeObservability) {
1681 return true;
1682 }
1683 if (resume->isObservableOperand(*iter)) {
1684 return true;
1685 }
1686 } else {
1687 MDefinition* def = consumer->toDefinition();
1688 if (!def->isPhi()) {
1689 return true;
1690 }
1691 }
1692 }
1693
1694 return false;
1695 }
1696
1697 // Handles cases like:
1698 // x is phi(a, x) --> a
1699 // x is phi(a, a) --> a
1700 static inline MDefinition* IsPhiRedundant(MPhi* phi) {
1701 MDefinition* first = phi->operandIfRedundant();
1702 if (first == nullptr) {
1703 return nullptr;
1704 }
1705
1706 // Propagate the ImplicitlyUsed flag if |phi| is replaced with another phi.
1707 if (phi->isImplicitlyUsed()) {
1708 first->setImplicitlyUsedUnchecked();
1709 }
1710
1711 return first;
1712 }
1713
1714 bool jit::EliminatePhis(const MIRGenerator* mir, MIRGraph& graph,
1715 Observability observe) {
1716 // Eliminates redundant or unobservable phis from the graph. A
1717 // redundant phi is something like b = phi(a, a) or b = phi(a, b),
1718 // both of which can be replaced with a. An unobservable phi is
1719 // one that whose value is never used in the program.
1720 //
1721 // Note that we must be careful not to eliminate phis representing
1722 // values that the interpreter will require later. When the graph
1723 // is first constructed, we can be more aggressive, because there
1724 // is a greater correspondence between the CFG and the bytecode.
1725 // After optimizations such as GVN have been performed, however,
1726 // the bytecode and CFG may not correspond as closely to one
1727 // another. In that case, we must be more conservative. The flag
1728 // |conservativeObservability| is used to indicate that eliminate
1729 // phis is being run after some optimizations have been performed,
1730 // and thus we should use more conservative rules about
1731 // observability. The particular danger is that we can optimize
1732 // away uses of a phi because we think they are not executable,
1733 // but the foundation for that assumption is false TI information
1734 // that will eventually be invalidated. Therefore, if
1735 // |conservativeObservability| is set, we will consider any use
1736 // from a resume point to be observable. Otherwise, we demand a
1737 // use from an actual instruction.
1738
1739 Vector<MPhi*, 16, SystemAllocPolicy> worklist;
1740
1741 // Add all observable phis to a worklist. We use the "in worklist" bit to
1742 // mean "this phi is live".
1743 for (PostorderIterator block = graph.poBegin(); block != graph.poEnd();
1744 block++) {
1745 MPhiIterator iter = block->phisBegin();
1746 while (iter != block->phisEnd()) {
1747 MPhi* phi = *iter++;
1748
1749 if (mir->shouldCancel("Eliminate Phis (populate loop)")) {
1750 return false;
1751 }
1752
1753 // Flag all as unused, only observable phis would be marked as used
1754 // when processed by the work list.
1755 phi->setUnused();
1756
1757 // If the phi is redundant, remove it here.
1758 if (MDefinition* redundant = IsPhiRedundant(phi)) {
1759 phi->justReplaceAllUsesWith(redundant);
1760 block->discardPhi(phi);
1761 continue;
1762 }
1763
1764 // Enqueue observable Phis.
1765 if (IsPhiObservable(phi, observe)) {
1766 phi->setInWorklist();
1767 if (!worklist.append(phi)) {
1768 return false;
1769 }
1770 }
1771 }
1772 }
1773
1774 // Iteratively mark all phis reachable from live phis.
1775 while (!worklist.empty()) {
1776 if (mir->shouldCancel("Eliminate Phis (worklist)")) {
1777 return false;
1778 }
1779
1780 MPhi* phi = worklist.popCopy();
1781 MOZ_ASSERT(phi->isUnused());
1782 phi->setNotInWorklist();
1783
1784 // The removal of Phis can produce newly redundant phis.
1785 if (MDefinition* redundant = IsPhiRedundant(phi)) {
1786 // Add to the worklist the used phis which are impacted.
1787 for (MUseDefIterator it(phi); it; it++) {
1788 if (it.def()->isPhi()) {
1789 MPhi* use = it.def()->toPhi();
1790 if (!use->isUnused()) {
1791 use->setUnusedUnchecked();
1792 use->setInWorklist();
1793 if (!worklist.append(use)) {
1794 return false;
1795 }
1796 }
1797 }
1798 }
1799 phi->justReplaceAllUsesWith(redundant);
1800 } else {
1801 // Otherwise flag them as used.
1802 phi->setNotUnused();
1803 }
1804
1805 // The current phi is/was used, so all its operands are used.
1806 for (size_t i = 0, e = phi->numOperands(); i < e; i++) {
1807 MDefinition* in = phi->getOperand(i);
1808 if (!in->isPhi() || !in->isUnused() || in->isInWorklist()) {
1809 continue;
1810 }
1811 in->setInWorklist();
1812 if (!worklist.append(in->toPhi())) {
1813 return false;
1814 }
1815 }
1816 }
1817
1818 // Sweep dead phis.
1819 for (PostorderIterator block = graph.poBegin(); block != graph.poEnd();
1820 block++) {
1821 if (mir->shouldCancel("Eliminate Phis (sweep dead phis)")) {
1822 return false;
1823 }
1824
1825 MPhiIterator iter = block->phisBegin();
1826 while (iter != block->phisEnd()) {
1827 MPhi* phi = *iter++;
1828 if (phi->isUnused()) {
1829 if (!phi->optimizeOutAllUses(graph.alloc())) {
1830 return false;
1831 }
1832 block->discardPhi(phi);
1833 }
1834 }
1835 }
1836
1837 return true;
1838 }
1839
1840 namespace {
1841
1842 // The type analysis algorithm inserts conversions and box/unbox instructions
1843 // to make the IR graph well-typed for future passes.
1844 //
1845 // Phi adjustment: If a phi's inputs are all the same type, the phi is
1846 // specialized to return that type.
1847 //
1848 // Input adjustment: Each input is asked to apply conversion operations to its
1849 // inputs. This may include Box, Unbox, or other instruction-specific type
1850 // conversion operations.
1851 //
1852 class TypeAnalyzer {
1853 const MIRGenerator* mir;
1854 MIRGraph& graph;
1855 Vector<MPhi*, 0, SystemAllocPolicy> phiWorklist_;
1856
1857 TempAllocator& alloc() const { return graph.alloc(); }
1858
1859 bool addPhiToWorklist(MPhi* phi) {
1860 if (phi->isInWorklist()) {
1861 return true;
1862 }
1863 if (!phiWorklist_.append(phi)) {
1864 return false;
1865 }
1866 phi->setInWorklist();
1867 return true;
1868 }
1869 MPhi* popPhi() {
1870 MPhi* phi = phiWorklist_.popCopy();
1871 phi->setNotInWorklist();
1872 return phi;
1873 }
1874
1875 [[nodiscard]] bool propagateAllPhiSpecializations();
1876
1877 bool respecialize(MPhi* phi, MIRType type);
1878 bool propagateSpecialization(MPhi* phi);
1879 bool specializePhis();
1880 bool specializeOsrOnlyPhis();
1881 void replaceRedundantPhi(MPhi* phi);
1882 bool adjustPhiInputs(MPhi* phi);
1883 bool adjustInputs(MDefinition* def);
1884 bool insertConversions();
1885
1886 bool checkFloatCoherency();
1887 bool graphContainsFloat32();
1888 bool markPhiConsumers();
1889 bool markPhiProducers();
1890 bool specializeValidFloatOps();
1891 bool tryEmitFloatOperations();
1892 bool propagateUnbox();
1893
1894 bool shouldSpecializeOsrPhis() const;
1895 MIRType guessPhiType(MPhi* phi) const;
1896
1897 public:
1898 TypeAnalyzer(const MIRGenerator* mir, MIRGraph& graph)
1899 : mir(mir), graph(graph) {}
1900
1901 bool analyze();
1902 };
1903
1904 } /* anonymous namespace */
1905
1906 bool TypeAnalyzer::shouldSpecializeOsrPhis() const {
1907 // [SMDOC] OSR Phi Type Specialization
1908 //
1909 // Without special handling for OSR phis, we end up with unspecialized phis
1910 // (MIRType::Value) in the loop (pre)header and other blocks, resulting in
1911 // unnecessary boxing and unboxing in the loop body.
1912 //
1913 // To fix this, phi type specialization needs special code to deal with the
1914 // OSR entry block. Recall that OSR results in the following basic block
1915 // structure:
1916 //
1917 // +------------------+ +-----------------+
1918 // | Code before loop | | OSR entry block |
1919 // +------------------+ +-----------------+
1920 // | |
1921 // | |
1922 // | +---------------+ |
1923 // +---------> | OSR preheader | <---------+
1924 // +---------------+
1925 // |
1926 // V
1927 // +---------------+
1928 // | Loop header |<-----+
1929 // +---------------+ |
1930 // | |
1931 // ... |
1932 // | |
1933 // +---------------+ |
1934 // | Loop backedge |------+
1935 // +---------------+
1936 //
1937 // OSR phi specialization happens in three steps:
1938 //
1939 // (1) Specialize phis but ignore MOsrValue phi inputs. In other words,
1940 // pretend the OSR entry block doesn't exist. See guessPhiType.
1941 //
1942 // (2) Once phi specialization is done, look at the types of loop header phis
1943 // and add these types to the corresponding preheader phis. This way, the
1944 // types of the preheader phis are based on the code before the loop and
1945 // the code in the loop body. These are exactly the types we expect for
1946 // the OSR Values. See the last part of TypeAnalyzer::specializePhis.
1947 //
1948 // (3) For type-specialized preheader phis, add guard/unbox instructions to
1949 // the OSR entry block to guard the incoming Value indeed has this type.
1950 // This happens in:
1951 //
1952 // * TypeAnalyzer::adjustPhiInputs: adds a fallible unbox for values that
1953 // can be unboxed.
1954 //
1955 // * TypeAnalyzer::replaceRedundantPhi: adds a type guard for values that
1956 // can't be unboxed (null/undefined/magic Values).
1957 if (!graph.osrBlock()) {
1958 return false;
1959 }
1960
1961 return !mir->outerInfo().hadSpeculativePhiBailout();
1962 }
1963
1964 // Try to specialize this phi based on its non-cyclic inputs.
1965 MIRType TypeAnalyzer::guessPhiType(MPhi* phi) const {
1966 #ifdef DEBUG
1967 // Check that different magic constants aren't flowing together. Ignore
1968 // JS_OPTIMIZED_OUT, since an operand could be legitimately optimized
1969 // away.
1970 MIRType magicType = MIRType::None;
1971 for (size_t i = 0; i < phi->numOperands(); i++) {
1972 MDefinition* in = phi->getOperand(i);
1973 if (in->type() == MIRType::MagicHole ||
1974 in->type() == MIRType::MagicIsConstructing) {
1975 if (magicType == MIRType::None) {
1976 magicType = in->type();
1977 }
1978 MOZ_ASSERT(magicType == in->type());
1979 }
1980 }
1981 #endif
1982
1983 MIRType type = MIRType::None;
1984 bool convertibleToFloat32 = false;
1985 bool hasOSRValueInput = false;
1986 DebugOnly<bool> hasSpecializableInput = false;
1987 for (size_t i = 0, e = phi->numOperands(); i < e; i++) {
1988 MDefinition* in = phi->getOperand(i);
1989 if (in->isPhi()) {
1990 hasSpecializableInput = true;
1991 if (!in->toPhi()->triedToSpecialize()) {
1992 continue;
1993 }
1994 if (in->type() == MIRType::None) {
1995 // The operand is a phi we tried to specialize, but we were
1996 // unable to guess its type. propagateSpecialization will
1997 // propagate the type to this phi when it becomes known.
1998 continue;
1999 }
2000 }
2001
2002 // See shouldSpecializeOsrPhis comment. This is the first step mentioned
2003 // there.
2004 if (shouldSpecializeOsrPhis() && in->isOsrValue()) {
2005 hasOSRValueInput = true;
2006 hasSpecializableInput = true;
2007 continue;
2008 }
2009
2010 if (type == MIRType::None) {
2011 type = in->type();
2012 if (in->canProduceFloat32() &&
2013 !mir->outerInfo().hadSpeculativePhiBailout()) {
2014 convertibleToFloat32 = true;
2015 }
2016 continue;
2017 }
2018
2019 if (type == in->type()) {
2020 convertibleToFloat32 = convertibleToFloat32 && in->canProduceFloat32();
2021 } else {
2022 if (convertibleToFloat32 && in->type() == MIRType::Float32) {
2023 // If we only saw definitions that can be converted into Float32 before
2024 // and encounter a Float32 value, promote previous values to Float32
2025 type = MIRType::Float32;
2026 } else if (IsTypeRepresentableAsDouble(type) &&
2027 IsTypeRepresentableAsDouble(in->type())) {
2028 // Specialize phis with int32 and double operands as double.
2029 type = MIRType::Double;
2030 convertibleToFloat32 = convertibleToFloat32 && in->canProduceFloat32();
2031 } else {
2032 return MIRType::Value;
2033 }
2034 }
2035 }
2036
2037 if (hasOSRValueInput && type == MIRType::Float32) {
2038 // TODO(post-Warp): simplify float32 handling in this function or (better)
2039 // make the float32 analysis a stand-alone optimization pass instead of
2040 // complicating type analysis. See bug 1655773.
2041 type = MIRType::Double;
2042 }
2043
2044 MOZ_ASSERT_IF(type == MIRType::None, hasSpecializableInput);
2045 return type;
2046 }
2047
2048 bool TypeAnalyzer::respecialize(MPhi* phi, MIRType type) {
2049 if (phi->type() == type) {
2050 return true;
2051 }
2052 phi->specialize(type);
2053 return addPhiToWorklist(phi);
2054 }
2055
2056 bool TypeAnalyzer::propagateSpecialization(MPhi* phi) {
2057 MOZ_ASSERT(phi->type() != MIRType::None);
2058
2059 // Verify that this specialization matches any phis depending on it.
2060 for (MUseDefIterator iter(phi); iter; iter++) {
2061 if (!iter.def()->isPhi()) {
2062 continue;
2063 }
2064 MPhi* use = iter.def()->toPhi();
2065 if (!use->triedToSpecialize()) {
2066 continue;
2067 }
2068 if (use->type() == MIRType::None) {
2069 // We tried to specialize this phi, but were unable to guess its
2070 // type. Now that we know the type of one of its operands, we can
2071 // specialize it. If it can't be specialized as float32, specialize
2072 // as double.
2073 MIRType type = phi->type();
2074 if (type == MIRType::Float32 && !use->canProduceFloat32()) {
2075 type = MIRType::Double;
2076 }
2077 if (!respecialize(use, type)) {
2078 return false;
2079 }
2080 continue;
2081 }
2082 if (use->type() != phi->type()) {
2083 // Specialize phis with int32 that can be converted to float and float
2084 // operands as floats.
2085 if ((use->type() == MIRType::Int32 && use->canProduceFloat32() &&
2086 phi->type() == MIRType::Float32) ||
2087 (phi->type() == MIRType::Int32 && phi->canProduceFloat32() &&
2088 use->type() == MIRType::Float32)) {
2089 if (!respecialize(use, MIRType::Float32)) {
2090 return false;
2091 }
2092 continue;
2093 }
2094
2095 // Specialize phis with int32 and double operands as double.
2096 if (IsTypeRepresentableAsDouble(use->type()) &&
2097 IsTypeRepresentableAsDouble(phi->type())) {
2098 if (!respecialize(use, MIRType::Double)) {
2099 return false;
2100 }
2101 continue;
2102 }
2103
2104 // This phi in our use chain can now no longer be specialized.
2105 if (!respecialize(use, MIRType::Value)) {
2106 return false;
2107 }
2108 }
2109 }
2110
2111 return true;
2112 }
2113
2114 bool TypeAnalyzer::propagateAllPhiSpecializations() {
2115 while (!phiWorklist_.empty()) {
2116 if (mir->shouldCancel("Specialize Phis (worklist)")) {
2117 return false;
2118 }
2119
2120 MPhi* phi = popPhi();
2121 if (!propagateSpecialization(phi)) {
2122 return false;
2123 }
2124 }
2125
2126 return true;
2127 }
2128
2129 // If branch pruning removes the path from the entry block to the OSR
2130 // preheader, we may have phis (or chains of phis) with no operands
2131 // other than OsrValues. These phis will still have MIRType::None.
2132 // Since we don't have any information about them, we specialize them
2133 // as MIRType::Value.
2134 bool TypeAnalyzer::specializeOsrOnlyPhis() {
2135 MOZ_ASSERT(graph.osrBlock());
2136 MOZ_ASSERT(graph.osrPreHeaderBlock()->numPredecessors() == 1);
2137
2138 for (PostorderIterator block(graph.poBegin()); block != graph.poEnd();
2139 block++) {
2140 if (mir->shouldCancel("Specialize osr-only phis (main loop)")) {
2141 return false;
2142 }
2143
2144 for (MPhiIterator phi(block->phisBegin()); phi != block->phisEnd(); phi++) {
2145 if (mir->shouldCancel("Specialize osr-only phis (inner loop)")) {
2146 return false;
2147 }
2148
2149 if (phi->type() == MIRType::None) {
2150 phi->specialize(MIRType::Value);
2151 }
2152 }
2153 }
2154 return true;
2155 }
2156
2157 bool TypeAnalyzer::specializePhis() {
2158 for (PostorderIterator block(graph.poBegin()); block != graph.poEnd();
2159 block++) {
2160 if (mir->shouldCancel("Specialize Phis (main loop)")) {
2161 return false;
2162 }
2163
2164 for (MPhiIterator phi(block->phisBegin()); phi != block->phisEnd(); phi++) {
2165 if (mir->shouldCancel("Specialize Phis (inner loop)")) {
2166 return false;
2167 }
2168
2169 MIRType type = guessPhiType(*phi);
2170 phi->specialize(type);
2171 if (type == MIRType::None) {
2172 // We tried to guess the type but failed because all operands are
2173 // phis we still have to visit. Set the triedToSpecialize flag but
2174 // don't propagate the type to other phis, propagateSpecialization
2175 // will do that once we know the type of one of the operands.
2176 continue;
2177 }
2178 if (!propagateSpecialization(*phi)) {
2179 return false;
2180 }
2181 }
2182 }
2183
2184 if (!propagateAllPhiSpecializations()) {
2185 return false;
2186 }
2187
2188 if (shouldSpecializeOsrPhis()) {
2189 // See shouldSpecializeOsrPhis comment. This is the second step, propagating
2190 // loop header phi types to preheader phis.
2191 MBasicBlock* preHeader = graph.osrPreHeaderBlock();
2192 MBasicBlock* header = preHeader->getSingleSuccessor();
2193
2194 if (preHeader->numPredecessors() == 1) {
2195 MOZ_ASSERT(preHeader->getPredecessor(0) == graph.osrBlock());
2196 // Branch pruning has removed the path from the entry block
2197 // to the preheader. Specialize any phis with no non-osr inputs.
2198 if (!specializeOsrOnlyPhis()) {
2199 return false;
2200 }
2201 } else if (header->isLoopHeader()) {
2202 for (MPhiIterator phi(header->phisBegin()); phi != header->phisEnd();
2203 phi++) {
2204 MPhi* preHeaderPhi = phi->getOperand(0)->toPhi();
2205 MOZ_ASSERT(preHeaderPhi->block() == preHeader);
2206
2207 if (preHeaderPhi->type() == MIRType::Value) {
2208 // Already includes everything.
2209 continue;
2210 }
2211
2212 MIRType loopType = phi->type();
2213 if (!respecialize(preHeaderPhi, loopType)) {
2214 return false;
2215 }
2216 }
2217 if (!propagateAllPhiSpecializations()) {
2218 return false;
2219 }
2220 } else {
2221 // Edge case: there is no backedge in this loop. This can happen
2222 // if the header is a 'pending' loop header when control flow in
2223 // the loop body is terminated unconditionally, or if a block
2224 // that dominates the backedge unconditionally bails out. In
2225 // this case the header only has the preheader as predecessor
2226 // and we don't need to do anything.
2227 MOZ_ASSERT(header->numPredecessors() == 1);
2228 }
2229 }
2230
2231 MOZ_ASSERT(phiWorklist_.empty());
2232 return true;
2233 }
2234
2235 bool TypeAnalyzer::adjustPhiInputs(MPhi* phi) {
2236 MIRType phiType = phi->type();
2237 MOZ_ASSERT(phiType != MIRType::None);
2238
2239 // If we specialized a type that's not Value, there are 3 cases:
2240 // 1. Every input is of that type.
2241 // 2. Every observed input is of that type (i.e., some inputs haven't been
2242 // executed yet).
2243 // 3. Inputs were numbers, and was specialized to floating point type.
2244 if (phiType != MIRType::Value) {
2245 for (size_t i = 0, e = phi->numOperands(); i < e; i++) {
2246 MDefinition* in = phi->getOperand(i);
2247 if (in->type() == phiType) {
2248 continue;
2249 }
2250
2251 if (in->isBox() && in->toBox()->input()->type() == phiType) {
2252 phi->replaceOperand(i, in->toBox()->input());
2253 continue;
2254 }
2255
2256 if (!alloc().ensureBallast()) {
2257 return false;
2258 }
2259
2260 MBasicBlock* predecessor = phi->block()->getPredecessor(i);
2261
2262 MInstruction* replacement;
2263 if (IsFloatingPointType(phiType) &&
2264 IsTypeRepresentableAsDouble(in->type())) {
2265 // Convert number operands to |phiType|.
2266 if (phiType == MIRType::Double) {
2267 replacement = MToDouble::New(alloc(), in);
2268 } else {
2269 MOZ_ASSERT(phiType == MIRType::Float32);
2270 replacement = MToFloat32::New(alloc(), in);
2271 }
2272 } else {
2273 // If we know this branch will fail to convert to phiType, insert a box
2274 // that'll immediately fail in the fallible unbox below.
2275 if (in->type() != MIRType::Value) {
2276 auto* box = MBox::New(alloc(), in);
2277 predecessor->insertAtEnd(box);
2278 in = box;
2279 }
2280
2281 // Be optimistic and insert unboxes when the operand is a value.
2282 if (phiType == MIRType::Float32) {
2283 // Float32 is unboxed as Double, then converted.
2284 auto* unbox =
2285 MUnbox::New(alloc(), in, MIRType::Double, MUnbox::Fallible);
2286 unbox->setBailoutKind(BailoutKind::SpeculativePhi);
2287 predecessor->insertAtEnd(unbox);
2288 replacement = MToFloat32::New(alloc(), unbox);
2289 } else {
2290 replacement = MUnbox::New(alloc(), in, phiType, MUnbox::Fallible);
2291 replacement->setBailoutKind(BailoutKind::SpeculativePhi);
2292 }
2293 }
2294 MOZ_ASSERT(replacement->type() == phiType);
2295
2296 predecessor->insertAtEnd(replacement);
2297 phi->replaceOperand(i, replacement);
2298 }
2299
2300 return true;
2301 }
2302
2303 // Box every typed input.
2304 for (size_t i = 0, e = phi->numOperands(); i < e; i++) {
2305 MDefinition* in = phi->getOperand(i);
2306 if (in->type() == MIRType::Value) {
2307 continue;
2308 }
2309
2310 // The input is being explicitly unboxed, so sneak past and grab the
2311 // original box. Don't bother optimizing if magic values are involved.
2312 if (in->isUnbox()) {
2313 MDefinition* unboxInput = in->toUnbox()->input();
2314 if (!IsMagicType(unboxInput->type()) && phi->typeIncludes(unboxInput)) {
2315 in = in->toUnbox()->input();
2316 }
2317 }
2318
2319 if (in->type() != MIRType::Value) {
2320 if (!alloc().ensureBallast()) {
2321 return false;
2322 }
2323
2324 MBasicBlock* pred = phi->block()->getPredecessor(i);
2325 in = BoxAt(alloc(), pred->lastIns(), in);
2326 }
2327
2328 phi->replaceOperand(i, in);
2329 }
2330
2331 return true;
2332 }
2333
2334 bool TypeAnalyzer::adjustInputs(MDefinition* def) {
2335 // Definitions such as MPhi have no type policy.
2336 if (!def->isInstruction()) {
2337 return true;
2338 }
2339
2340 MInstruction* ins = def->toInstruction();
2341 const TypePolicy* policy = ins->typePolicy();
2342 if (policy && !policy->adjustInputs(alloc(), ins)) {
2343 return false;
2344 }
2345 return true;
2346 }
2347
2348 void TypeAnalyzer::replaceRedundantPhi(MPhi* phi) {
2349 MBasicBlock* block = phi->block();
2350 js::Value v;
2351 switch (phi->type()) {
2352 case MIRType::Undefined:
2353 v = UndefinedValue();
2354 break;
2355 case MIRType::Null:
2356 v = NullValue();
2357 break;
2358 case MIRType::MagicOptimizedOut:
2359 v = MagicValue(JS_OPTIMIZED_OUT);
2360 break;
2361 case MIRType::MagicUninitializedLexical:
2362 v = MagicValue(JS_UNINITIALIZED_LEXICAL);
2363 break;
2364 case MIRType::MagicIsConstructing:
2365 v = MagicValue(JS_IS_CONSTRUCTING);
2366 break;
2367 case MIRType::MagicHole:
2368 default:
2369 MOZ_CRASH("unexpected type");
2370 }
2371 MConstant* c = MConstant::New(alloc(), v);
2372 // The instruction pass will insert the box
2373 block->insertBefore(*(block->begin()), c);
2374 phi->justReplaceAllUsesWith(c);
2375
2376 if (shouldSpecializeOsrPhis()) {
2377 // See shouldSpecializeOsrPhis comment. This is part of the third step,
2378 // guard the incoming MOsrValue is of this type.
2379 for (uint32_t i = 0; i < phi->numOperands(); i++) {
2380 MDefinition* def = phi->getOperand(i);
2381 if (def->type() != phi->type()) {
2382 MOZ_ASSERT(def->isOsrValue() || def->isPhi());
2383 MOZ_ASSERT(def->type() == MIRType::Value);
2384 MGuardValue* guard = MGuardValue::New(alloc(), def, v);
2385 guard->setBailoutKind(BailoutKind::SpeculativePhi);
2386 def->block()->insertBefore(def->block()->lastIns(), guard);
2387 }
2388 }
2389 }
2390 }
2391
2392 bool TypeAnalyzer::insertConversions() {
2393 // Instructions are processed in reverse postorder: all uses are defs are
2394 // seen before uses. This ensures that output adjustment (which may rewrite
2395 // inputs of uses) does not conflict with input adjustment.
2396 for (ReversePostorderIterator block(graph.rpoBegin());
2397 block != graph.rpoEnd(); block++) {
2398 if (mir->shouldCancel("Insert Conversions")) {
2399 return false;
2400 }
2401
2402 for (MPhiIterator iter(block->phisBegin()), end(block->phisEnd());
2403 iter != end;) {
2404 MPhi* phi = *iter++;
2405 if (IsNullOrUndefined(phi->type()) || IsMagicType(phi->type())) {
2406 // We can replace this phi with a constant.
2407 if (!alloc().ensureBallast()) {
2408 return false;
2409 }
2410 replaceRedundantPhi(phi);
2411 block->discardPhi(phi);
2412 } else {
2413 if (!adjustPhiInputs(phi)) {
2414 return false;
2415 }
2416 }
2417 }
2418
2419 // AdjustInputs can add/remove/mutate instructions before and after the
2420 // current instruction. Only increment the iterator after it is finished.
2421 for (MInstructionIterator iter(block->begin()); iter != block->end();
2422 iter++) {
2423 if (!alloc().ensureBallast()) {
2424 return false;
2425 }
2426
2427 if (!adjustInputs(*iter)) {
2428 return false;
2429 }
2430 }
2431 }
2432 return true;
2433 }
2434
2435 /* clang-format off */
2436 //
2437 // This function tries to emit Float32 specialized operations whenever it's possible.
2438 // MIR nodes are flagged as:
2439 // - Producers, when they can create Float32 that might need to be coerced into a Double.
2440 // Loads in Float32 arrays and conversions to Float32 are producers.
2441 // - Consumers, when they can have Float32 as inputs and validate a legal use of a Float32.
2442 // Stores in Float32 arrays and conversions to Float32 are consumers.
2443 // - Float32 commutative, when using the Float32 instruction instead of the Double instruction
2444 // does not result in a compound loss of precision. This is the case for +, -, /, * with 2
2445 // operands, for instance. However, an addition with 3 operands is not commutative anymore,
2446 // so an intermediate coercion is needed.
2447 // Except for phis, all these flags are known after Ion building, so they cannot change during
2448 // the process.
2449 //
2450 // The idea behind the algorithm is easy: whenever we can prove that a commutative operation
2451 // has only producers as inputs and consumers as uses, we can specialize the operation as a
2452 // float32 operation. Otherwise, we have to convert all float32 inputs to doubles. Even
2453 // if a lot of conversions are produced, GVN will take care of eliminating the redundant ones.
2454 //
2455 // Phis have a special status. Phis need to be flagged as producers or consumers as they can
2456 // be inputs or outputs of commutative instructions. Fortunately, producers and consumers
2457 // properties are such that we can deduce the property using all non phis inputs first (which form
2458 // an initial phi graph) and then propagate all properties from one phi to another using a
2459 // fixed point algorithm. The algorithm is ensured to terminate as each iteration has less or as
2460 // many flagged phis as the previous iteration (so the worst steady state case is all phis being
2461 // flagged as false).
2462 //
2463 // In a nutshell, the algorithm applies three passes:
2464 // 1 - Determine which phis are consumers. Each phi gets an initial value by making a global AND on
2465 // all its non-phi inputs. Then each phi propagates its value to other phis. If after propagation,
2466 // the flag value changed, we have to reapply the algorithm on all phi operands, as a phi is a
2467 // consumer if all of its uses are consumers.
2468 // 2 - Determine which phis are producers. It's the same algorithm, except that we have to reapply
2469 // the algorithm on all phi uses, as a phi is a producer if all of its operands are producers.
2470 // 3 - Go through all commutative operations and ensure their inputs are all producers and their
2471 // uses are all consumers.
2472 //
2473 /* clang-format on */
2474 bool TypeAnalyzer::markPhiConsumers() {
2475 MOZ_ASSERT(phiWorklist_.empty());
2476
2477 // Iterate in postorder so worklist is initialized to RPO.
2478 for (PostorderIterator block(graph.poBegin()); block != graph.poEnd();
2479 ++block) {
2480 if (mir->shouldCancel(
2481 "Ensure Float32 commutativity - Consumer Phis - Initial state")) {
2482 return false;
2483 }
2484
2485 for (MPhiIterator phi(block->phisBegin()); phi != block->phisEnd(); ++phi) {
2486 MOZ_ASSERT(!phi->isInWorklist());
2487 bool canConsumeFloat32 = !phi->isImplicitlyUsed();
2488 for (MUseDefIterator use(*phi); canConsumeFloat32 && use; use++) {
2489 MDefinition* usedef = use.def();
2490 canConsumeFloat32 &=
2491 usedef->isPhi() || usedef->canConsumeFloat32(use.use());
2492 }
2493 phi->setCanConsumeFloat32(canConsumeFloat32);
2494 if (canConsumeFloat32 && !addPhiToWorklist(*phi)) {
2495 return false;
2496 }
2497 }
2498 }
2499
2500 while (!phiWorklist_.empty()) {
2501 if (mir->shouldCancel(
2502 "Ensure Float32 commutativity - Consumer Phis - Fixed point")) {
2503 return false;
2504 }
2505
2506 MPhi* phi = popPhi();
2507 MOZ_ASSERT(phi->canConsumeFloat32(nullptr /* unused */));
2508
2509 bool validConsumer = true;
2510 for (MUseDefIterator use(phi); use; use++) {
2511 MDefinition* def = use.def();
2512 if (def->isPhi() && !def->canConsumeFloat32(use.use())) {
2513 validConsumer = false;
2514 break;
2515 }
2516 }
2517
2518 if (validConsumer) {
2519 continue;
2520 }
2521
2522 // Propagate invalidated phis
2523 phi->setCanConsumeFloat32(false);
2524 for (size_t i = 0, e = phi->numOperands(); i < e; ++i) {
2525 MDefinition* input = phi->getOperand(i);
2526 if (input->isPhi() && !input->isInWorklist() &&
2527 input->canConsumeFloat32(nullptr /* unused */)) {
2528 if (!addPhiToWorklist(input->toPhi())) {
2529 return false;
2530 }
2531 }
2532 }
2533 }
2534 return true;
2535 }
2536
2537 bool TypeAnalyzer::markPhiProducers() {
2538 MOZ_ASSERT(phiWorklist_.empty());
2539
2540 // Iterate in reverse postorder so worklist is initialized to PO.
2541 for (ReversePostorderIterator block(graph.rpoBegin());
2542 block != graph.rpoEnd(); ++block) {
2543 if (mir->shouldCancel(
2544 "Ensure Float32 commutativity - Producer Phis - initial state")) {
2545 return false;
2546 }
2547
2548 for (MPhiIterator phi(block->phisBegin()); phi != block->phisEnd(); ++phi) {
2549 MOZ_ASSERT(!phi->isInWorklist());
2550 bool canProduceFloat32 = true;
2551 for (size_t i = 0, e = phi->numOperands(); canProduceFloat32 && i < e;
2552 ++i) {
2553 MDefinition* input = phi->getOperand(i);
2554 canProduceFloat32 &= input->isPhi() || input->canProduceFloat32();
2555 }
2556 phi->setCanProduceFloat32(canProduceFloat32);
2557 if (canProduceFloat32 && !addPhiToWorklist(*phi)) {
2558 return false;
2559 }
2560 }
2561 }
2562
2563 while (!phiWorklist_.empty()) {
2564 if (mir->shouldCancel(
2565 "Ensure Float32 commutativity - Producer Phis - Fixed point")) {
2566 return false;
2567 }
2568
2569 MPhi* phi = popPhi();
2570 MOZ_ASSERT(phi->canProduceFloat32());
2571
2572 bool validProducer = true;
2573 for (size_t i = 0, e = phi->numOperands(); i < e; ++i) {
2574 MDefinition* input = phi->getOperand(i);
2575 if (input->isPhi() && !input->canProduceFloat32()) {
2576 validProducer = false;
2577 break;
2578 }
2579 }
2580
2581 if (validProducer) {
2582 continue;
2583 }
2584
2585 // Propagate invalidated phis
2586 phi->setCanProduceFloat32(false);
2587 for (MUseDefIterator use(phi); use; use++) {
2588 MDefinition* def = use.def();
2589 if (def->isPhi() && !def->isInWorklist() && def->canProduceFloat32()) {
2590 if (!addPhiToWorklist(def->toPhi())) {
2591 return false;
2592 }
2593 }
2594 }
2595 }
2596 return true;
2597 }
2598
2599 bool TypeAnalyzer::specializeValidFloatOps() {
2600 for (ReversePostorderIterator block(graph.rpoBegin());
2601 block != graph.rpoEnd(); ++block) {
2602 if (mir->shouldCancel("Ensure Float32 commutativity - Instructions")) {
2603 return false;
2604 }
2605
2606 for (MInstructionIterator ins(block->begin()); ins != block->end(); ++ins) {
2607 if (!ins->isFloat32Commutative()) {
2608 continue;
2609 }
2610
2611 if (ins->type() == MIRType::Float32) {
2612 continue;
2613 }
2614
2615 if (!alloc().ensureBallast()) {
2616 return false;
2617 }
2618
2619 // This call will try to specialize the instruction iff all uses are
2620 // consumers and all inputs are producers.
2621 ins->trySpecializeFloat32(alloc());
2622 }
2623 }
2624 return true;
2625 }
2626
2627 bool TypeAnalyzer::graphContainsFloat32() {
2628 for (ReversePostorderIterator block(graph.rpoBegin());
2629 block != graph.rpoEnd(); ++block) {
2630 for (MDefinitionIterator def(*block); def; def++) {
2631 if (mir->shouldCancel(
2632 "Ensure Float32 commutativity - Graph contains Float32")) {
2633 return false;
2634 }
2635
2636 if (def->type() == MIRType::Float32) {
2637 return true;
2638 }
2639 }
2640 }
2641 return false;
2642 }
2643
2644 bool TypeAnalyzer::tryEmitFloatOperations() {
2645 // Asm.js uses the ahead of time type checks to specialize operations, no need
2646 // to check them again at this point.
2647 if (mir->compilingWasm()) {
2648 return true;
2649 }
2650
2651 // Check ahead of time that there is at least one definition typed as Float32,
2652 // otherwise we don't need this pass.
2653 if (!graphContainsFloat32()) {
2654 return true;
2655 }
2656
2657 // WarpBuilder skips over code that can't be reached except through
2658 // a catch block. Locals and arguments may be observable in such
2659 // code after bailing out, so we can't rely on seeing all uses.
2660 if (graph.hasTryBlock()) {
2661 return true;
2662 }
2663
2664 if (!markPhiConsumers()) {
2665 return false;
2666 }
2667 if (!markPhiProducers()) {
2668 return false;
2669 }
2670 if (!specializeValidFloatOps()) {
2671 return false;
2672 }
2673 return true;
2674 }
2675
2676 bool TypeAnalyzer::checkFloatCoherency() {
2677 #ifdef DEBUG
2678 // Asserts that all Float32 instructions are flowing into Float32 consumers or
2679 // specialized operations
2680 for (ReversePostorderIterator block(graph.rpoBegin());
2681 block != graph.rpoEnd(); ++block) {
2682 if (mir->shouldCancel("Check Float32 coherency")) {
2683 return false;
2684 }
2685
2686 for (MDefinitionIterator def(*block); def; def++) {
2687 if (def->type() != MIRType::Float32) {
2688 continue;
2689 }
2690
2691 for (MUseDefIterator use(*def); use; use++) {
2692 MDefinition* consumer = use.def();
2693 MOZ_ASSERT(consumer->isConsistentFloat32Use(use.use()));
2694 }
2695 }
2696 }
2697 #endif
2698 return true;
2699 }
2700
2701 static bool HappensBefore(const MDefinition* earlier,
2702 const MDefinition* later) {
2703 MOZ_ASSERT(earlier->block() == later->block());
2704
2705 for (auto* ins : *earlier->block()) {
2706 if (ins == earlier) {
2707 return true;
2708 }
2709 if (ins == later) {
2710 return false;
2711 }
2712 }
2713 MOZ_CRASH("earlier and later are instructions in the block");
2714 }
2715
2716 // Propagate type information from dominating unbox instructions.
2717 //
2718 // This optimization applies for example for self-hosted String.prototype
2719 // functions.
2720 //
2721 // Example:
2722 // ```
2723 // String.prototype.id = function() {
2724 // // Strict mode to avoid ToObject on primitive this-values.
2725 // "use strict";
2726 //
2727 // // Template string to apply ToString on the this-value.
2728 // return `${this}`;
2729 // };
2730 //
2731 // function f(s) {
2732 // // Assume |s| is a string value.
2733 // return s.id();
2734 // }
2735 // ```
2736 //
2737 // Compiles into: (Graph after Scalar Replacement)
2738 //
2739 // ┌───────────────────────────────────────────────────────────────────────────┐
2740 // │ Block 0 │
2741 // │ resumepoint 1 0 2 2 │
2742 // │ 0 parameter THIS_SLOT Value │
2743 // │ 1 parameter 0 Value │
2744 // │ 2 constant undefined Undefined │
2745 // │ 3 start │
2746 // │ 4 checkoverrecursed │
2747 // │ 5 unbox parameter1 to String (fallible) String │
2748 // │ 6 constant object 1d908053e088 (String) Object │
2749 // │ 7 guardshape constant6:Object Object │
2750 // │ 8 slots guardshape7:Object Slots │
2751 // │ 9 loaddynamicslot slots8:Slots (slot 53) Value │
2752 // │ 10 constant 0x0 Int32 │
2753 // │ 11 unbox loaddynamicslot9 to Object (fallible) Object │
2754 // │ 12 nurseryobject Object │
2755 // │ 13 guardspecificfunction unbox11:Object nurseryobject12:Object Object │
2756 // │ 14 goto block1 │
2757 // └──────────────────────────────────┬────────────────────────────────────────┘
2758 // │
2759 // ┌──────────────────────────────────▼────────────────────────────────────────┐
2760 // │ Block 1 │
2761 // │ ((0)) resumepoint 15 1 15 15 | 1 13 1 0 2 2 │
2762 // │ 15 constant undefined Undefined │
2763 // │ 16 tostring parameter1:Value String │
2764 // │ 18 goto block2 │
2765 // └──────────────────────────────────┬────────────────────────────────────────┘
2766 // │
2767 // ┌──────────────▼──────────────┐
2768 // │ Block 2 │
2769 // │ resumepoint 16 1 0 2 2 │
2770 // │ 19 return tostring16:String │
2771 // └─────────────────────────────┘
2772 //
2773 // The Unbox instruction is used as a type guard. The ToString instruction
2774 // doesn't use the type information from the preceding Unbox instruction and
2775 // therefore has to assume its operand can be any value.
2776 //
2777 // When instead propagating the type information from the preceding Unbox
2778 // instruction, this graph is constructed after the "Apply types" phase:
2779 //
2780 // ┌───────────────────────────────────────────────────────────────────────────┐
2781 // │ Block 0 │
2782 // │ resumepoint 1 0 2 2 │
2783 // │ 0 parameter THIS_SLOT Value │
2784 // │ 1 parameter 0 Value │
2785 // │ 2 constant undefined Undefined │
2786 // │ 3 start │
2787 // │ 4 checkoverrecursed │
2788 // │ 5 unbox parameter1 to String (fallible) String │
2789 // │ 6 constant object 1d908053e088 (String) Object │
2790 // │ 7 guardshape constant6:Object Object │
2791 // │ 8 slots guardshape7:Object Slots │
2792 // │ 9 loaddynamicslot slots8:Slots (slot 53) Value │
2793 // │ 10 constant 0x0 Int32 │
2794 // │ 11 unbox loaddynamicslot9 to Object (fallible) Object │
2795 // │ 12 nurseryobject Object │
2796 // │ 13 guardspecificfunction unbox11:Object nurseryobject12:Object Object │
2797 // │ 14 goto block1 │
2798 // └──────────────────────────────────┬────────────────────────────────────────┘
2799 // │
2800 // ┌──────────────────────────────────▼────────────────────────────────────────┐
2801 // │ Block 1 │
2802 // │ ((0)) resumepoint 15 1 15 15 | 1 13 1 0 2 2 │
2803 // │ 15 constant undefined Undefined │
2804 // │ 20 unbox parameter1 to String (fallible) String │
2805 // │ 16 tostring parameter1:Value String │
2806 // │ 18 goto block2 │
2807 // └──────────────────────────────────┬────────────────────────────────────────┘
2808 // │
2809 // ┌──────────────▼─────────────────────┐
2810 // │ Block 2 │
2811 // │ resumepoint 16 1 0 2 2 │
2812 // │ 21 box tostring16:String Value │
2813 // │ 19 return box21:Value │
2814 // └────────────────────────────────────┘
2815 //
2816 // GVN will later merge both Unbox instructions and fold away the ToString
2817 // instruction, so we get this final graph:
2818 //
2819 // ┌───────────────────────────────────────────────────────────────────────────┐
2820 // │ Block 0 │
2821 // │ resumepoint 1 0 2 2 │
2822 // │ 0 parameter THIS_SLOT Value │
2823 // │ 1 parameter 0 Value │
2824 // │ 2 constant undefined Undefined │
2825 // │ 3 start │
2826 // │ 4 checkoverrecursed │
2827 // │ 5 unbox parameter1 to String (fallible) String │
2828 // │ 6 constant object 1d908053e088 (String) Object │
2829 // │ 7 guardshape constant6:Object Object │
2830 // │ 8 slots guardshape7:Object Slots │
2831 // │ 22 loaddynamicslotandunbox slots8:Slots (slot 53) Object │
2832 // │ 11 nurseryobject Object │
2833 // │ 12 guardspecificfunction load22:Object nurseryobject11:Object Object │
2834 // │ 13 goto block1 │
2835 // └──────────────────────────────────┬────────────────────────────────────────┘
2836 // │
2837 // ┌──────────────────────────────────▼────────────────────────────────────────┐
2838 // │ Block 1 │
2839 // │ ((0)) resumepoint 2 1 2 2 | 1 12 1 0 2 2 │
2840 // │ 14 goto block2 │
2841 // └──────────────────────────────────┬────────────────────────────────────────┘
2842 // │
2843 // ┌──────────────▼─────────────────────┐
2844 // │ Block 2 │
2845 // │ resumepoint 5 1 0 2 2 │
2846 // │ 15 return parameter1:Value │
2847 // └────────────────────────────────────┘
2848 //
2849 bool TypeAnalyzer::propagateUnbox() {
2850 // Visit the blocks in post-order, so that the type information of the closest
2851 // unbox operation is used.
2852 for (PostorderIterator block(graph.poBegin()); block != graph.poEnd();
2853 block++) {
2854 if (mir->shouldCancel("Propagate Unbox")) {
2855 return false;
2856 }
2857
2858 // Iterate over all instructions to look for unbox instructions.
2859 for (MInstructionIterator iter(block->begin()); iter != block->end();
2860 iter++) {
2861 if (!iter->isUnbox()) {
2862 continue;
2863 }
2864
2865 auto* unbox = iter->toUnbox();
2866 auto* input = unbox->input();
2867
2868 // Ignore unbox operations on typed values.
2869 if (input->type() != MIRType::Value) {
2870 continue;
2871 }
2872
2873 // Ignore unbox to floating point types, because propagating boxed Int32
2874 // values as Double can lead to repeated bailouts when later instructions
2875 // expect Int32 inputs.
2876 if (IsFloatingPointType(unbox->type())) {
2877 continue;
2878 }
2879
2880 // Inspect other uses of |input| to propagate the unboxed type information
2881 // from |unbox|.
2882 for (auto uses = input->usesBegin(); uses != input->usesEnd();) {
2883 auto* use = *uses++;
2884
2885 // Ignore resume points.
2886 if (!use->consumer()->isDefinition()) {
2887 continue;
2888 }
2889 auto* def = use->consumer()->toDefinition();
2890
2891 // Ignore any unbox operations, including the current |unbox|.
2892 if (def->isUnbox()) {
2893 continue;
2894 }
2895
2896 // Ignore phi nodes, because we don't yet support them.
2897 if (def->isPhi()) {
2898 continue;
2899 }
2900
2901 // The unbox operation needs to happen before the other use, otherwise
2902 // we can't propagate the type information.
2903 if (unbox->block() == def->block()) {
2904 if (!HappensBefore(unbox, def)) {
2905 continue;
2906 }
2907 } else {
2908 if (!unbox->block()->dominates(def->block())) {
2909 continue;
2910 }
2911 }
2912
2913 // Replace the use with |unbox|, so that GVN knows about the actual
2914 // value type and can more easily fold unnecessary operations. If the
2915 // instruction actually needs a boxed input, the BoxPolicy type policy
2916 // will simply unwrap the unbox instruction.
2917 use->replaceProducer(unbox);
2918
2919 // The uses in the MIR graph no longer reflect the uses in the bytecode,
2920 // so we have to mark |input| as implicitly used.
2921 input->setImplicitlyUsedUnchecked();
2922 }
2923 }
2924 }
2925 return true;
2926 }
2927
2928 bool TypeAnalyzer::analyze() {
2929 if (!tryEmitFloatOperations()) {
2930 return false;
2931 }
2932 if (!specializePhis()) {
2933 return false;
2934 }
2935 if (!propagateUnbox()) {
2936 return false;
2937 }
2938 if (!insertConversions()) {
2939 return false;
2940 }
2941 if (!checkFloatCoherency()) {
2942 return false;
2943 }
2944 return true;
2945 }
2946
2947 bool jit::ApplyTypeInformation(const MIRGenerator* mir, MIRGraph& graph) {
2948 TypeAnalyzer analyzer(mir, graph);
2949
2950 if (!analyzer.analyze()) {
2951 return false;
2952 }
2953
2954 return true;
2955 }
2956
2957 void jit::RenumberBlocks(MIRGraph& graph) {
2958 size_t id = 0;
2959 for (ReversePostorderIterator block(graph.rpoBegin());
2960 block != graph.rpoEnd(); block++) {
2961 block->setId(id++);
2962 }
2963 }
2964
2965 // A utility for code which adds/deletes blocks. Renumber the remaining blocks,
2966 // recompute dominators, and optionally recompute AliasAnalysis dependencies.
2967 bool jit::AccountForCFGChanges(const MIRGenerator* mir, MIRGraph& graph,
2968 bool updateAliasAnalysis,
2969 bool underValueNumberer) {
2970 // Renumber the blocks and clear out the old dominator info.
2971 size_t id = 0;
2972 for (ReversePostorderIterator i(graph.rpoBegin()), e(graph.rpoEnd()); i != e;
2973 ++i) {
2974 i->clearDominatorInfo();
2975 i->setId(id++);
2976 }
2977
2978 // Recompute dominator info.
2979 if (!BuildDominatorTree(mir, graph)) {
2980 return false;
2981 }
2982
2983 // If needed, update alias analysis dependencies.
2984 if (updateAliasAnalysis) {
2985 if (!AliasAnalysis(mir, graph).analyze()) {
2986 return false;
2987 }
2988 }
2989
2990 AssertExtendedGraphCoherency(graph, underValueNumberer);
2991 return true;
2992 }
2993
2994 // Remove all blocks not marked with isMarked(). Unmark all remaining blocks.
2995 // Alias analysis dependencies may be invalid after calling this function.
2996 bool jit::RemoveUnmarkedBlocks(const MIRGenerator* mir, MIRGraph& graph,
2997 uint32_t numMarkedBlocks) {
2998 if (numMarkedBlocks == graph.numBlocks()) {
2999 // If all blocks are marked, no blocks need removal. Just clear the
3000 // marks. We'll still need to update the dominator tree below though,
3001 // since we may have removed edges even if we didn't remove any blocks.
3002 graph.unmarkBlocks();
3003 } else {
3004 // As we are going to remove edges and basic blocks, we have to mark
3005 // instructions which would be needed by baseline if we were to
3006 // bailout.
3007 for (PostorderIterator it(graph.poBegin()); it != graph.poEnd();) {
3008 MBasicBlock* block = *it++;
3009 if (block->isMarked()) {
3010 continue;
3011 }
3012
3013 if (!FlagAllOperandsAsImplicitlyUsed(mir, block)) {
3014 return false;
3015 }
3016 }
3017
3018 // Find unmarked blocks and remove them.
3019 for (ReversePostorderIterator iter(graph.rpoBegin());
3020 iter != graph.rpoEnd();) {
3021 MBasicBlock* block = *iter++;
3022
3023 if (block->isMarked()) {
3024 block->unmark();
3025 continue;
3026 }
3027
3028 // The block is unreachable. Clear out the loop header flag, as
3029 // we're doing the sweep of a mark-and-sweep here, so we no longer
3030 // need to worry about whether an unmarked block is a loop or not.
3031 if (block->isLoopHeader()) {
3032 block->clearLoopHeader();
3033 }
3034
3035 for (size_t i = 0, e = block->numSuccessors(); i != e; ++i) {
3036 block->getSuccessor(i)->removePredecessor(block);
3037 }
3038 graph.removeBlock(block);
3039 }
3040 }
3041
3042 // Renumber the blocks and update the dominator tree.
3043 return AccountForCFGChanges(mir, graph, /*updateAliasAnalysis=*/false);
3044 }
3045
3046 bool jit::BuildPhiReverseMapping(MIRGraph& graph) {
3047 // Build a mapping such that given a basic block, whose successor has one or
3048 // more phis, we can find our specific input to that phi. To make this fast
3049 // mapping work we rely on a specific property of our structured control
3050 // flow graph: For a block with phis, its predecessors each have only one
3051 // successor with phis. Consider each case:
3052 // * Blocks with less than two predecessors cannot have phis.
3053 // * Breaks. A break always has exactly one successor, and the break
3054 // catch block has exactly one predecessor for each break, as
3055 // well as a final predecessor for the actual loop exit.
3056 // * Continues. A continue always has exactly one successor, and the
3057 // continue catch block has exactly one predecessor for each
3058 // continue, as well as a final predecessor for the actual
3059 // loop continuation. The continue itself has exactly one
3060 // successor.
3061 // * An if. Each branch as exactly one predecessor.
3062 // * A switch. Each branch has exactly one predecessor.
3063 // * Loop tail. A new block is always created for the exit, and if a
3064 // break statement is present, the exit block will forward
3065 // directly to the break block.
3066 for (MBasicBlockIterator block(graph.begin()); block != graph.end();
3067 block++) {
3068 if (block->phisEmpty()) {
3069 continue;
3070 }
3071
3072 // Assert on the above.
3073 for (size_t j = 0; j < block->numPredecessors(); j++) {
3074 MBasicBlock* pred = block->getPredecessor(j);
3075
3076 #ifdef DEBUG
3077 size_t numSuccessorsWithPhis = 0;
3078 for (size_t k = 0; k < pred->numSuccessors(); k++) {
3079 MBasicBlock* successor = pred->getSuccessor(k);
3080 if (!successor->phisEmpty()) {
3081 numSuccessorsWithPhis++;
3082 }
3083 }
3084 MOZ_ASSERT(numSuccessorsWithPhis <= 1);
3085 #endif
3086
3087 pred->setSuccessorWithPhis(*block, j);
3088 }
3089 }
3090
3091 return true;
3092 }
3093
3094 #ifdef DEBUG
3095 static bool CheckSuccessorImpliesPredecessor(MBasicBlock* A, MBasicBlock* B) {
3096 // Assuming B = succ(A), verify A = pred(B).
3097 for (size_t i = 0; i < B->numPredecessors(); i++) {
3098 if (A == B->getPredecessor(i)) {
3099 return true;
3100 }
3101 }
3102 return false;
3103 }
3104
3105 static bool CheckPredecessorImpliesSuccessor(MBasicBlock* A, MBasicBlock* B) {
3106 // Assuming B = pred(A), verify A = succ(B).
3107 for (size_t i = 0; i < B->numSuccessors(); i++) {
3108 if (A == B->getSuccessor(i)) {
3109 return true;
3110 }
3111 }
3112 return false;
3113 }
3114
3115 // If you have issues with the usesBalance assertions, then define the macro
3116 // _DEBUG_CHECK_OPERANDS_USES_BALANCE to spew information on the error output.
3117 // This output can then be processed with the following awk script to filter and
3118 // highlight which checks are missing or if there is an unexpected operand /
3119 // use.
3120 //
3121 // define _DEBUG_CHECK_OPERANDS_USES_BALANCE 1
3122 /*
3123
3124 $ ./js 2>stderr.log
3125 $ gawk '
3126 /^==Check/ { context = ""; state = $2; }
3127 /^[a-z]/ { context = context "\n\t" $0; }
3128 /^==End/ {
3129 if (state == "Operand") {
3130 list[context] = list[context] - 1;
3131 } else if (state == "Use") {
3132 list[context] = list[context] + 1;
3133 }
3134 }
3135 END {
3136 for (ctx in list) {
3137 if (list[ctx] > 0) {
3138 print "Missing operand check", ctx, "\n"
3139 }
3140 if (list[ctx] < 0) {
3141 print "Missing use check", ctx, "\n"
3142 }
3143 };
3144 }' < stderr.log
3145
3146 */
3147
3148 static void CheckOperand(const MNode* consumer, const MUse* use,
3149 int32_t* usesBalance) {
3150 MOZ_ASSERT(use->hasProducer());
3151 MDefinition* producer = use->producer();
3152 MOZ_ASSERT(!producer->isDiscarded());
3153 MOZ_ASSERT(producer->block() != nullptr);
3154 MOZ_ASSERT(use->consumer() == consumer);
3155 # ifdef _DEBUG_CHECK_OPERANDS_USES_BALANCE
3156 Fprinter print(stderr);
3157 print.printf("==Check Operand\n");
3158 use->producer()->dump(print);
3159 print.printf(" index: %zu\n", use->consumer()->indexOf(use));
3160 use->consumer()->dump(print);
3161 print.printf("==End\n");
3162 # endif
3163 --*usesBalance;
3164 }
3165
3166 static void CheckUse(const MDefinition* producer, const MUse* use,
3167 int32_t* usesBalance) {
3168 MOZ_ASSERT(!use->consumer()->block()->isDead());
3169 MOZ_ASSERT_IF(use->consumer()->isDefinition(),
3170 !use->consumer()->toDefinition()->isDiscarded());
3171 MOZ_ASSERT(use->consumer()->block() != nullptr);
3172 MOZ_ASSERT(use->consumer()->getOperand(use->index()) == producer);
3173 # ifdef _DEBUG_CHECK_OPERANDS_USES_BALANCE
3174 Fprinter print(stderr);
3175 print.printf("==Check Use\n");
3176 use->producer()->dump(print);
3177 print.printf(" index: %zu\n", use->consumer()->indexOf(use));
3178 use->consumer()->dump(print);
3179 print.printf("==End\n");
3180 # endif
3181 ++*usesBalance;
3182 }
3183
3184 // To properly encode entry resume points, we have to ensure that all the
3185 // operands of the entry resume point are located before the safeInsertTop
3186 // location.
3187 static void AssertOperandsBeforeSafeInsertTop(MResumePoint* resume) {
3188 MBasicBlock* block = resume->block();
3189 if (block == block->graph().osrBlock()) {
3190 return;
3191 }
3192 MInstruction* stop = block->safeInsertTop();
3193 for (size_t i = 0, e = resume->numOperands(); i < e; ++i) {
3194 MDefinition* def = resume->getOperand(i);
3195 if (def->block() != block) {
3196 continue;
3197 }
3198 if (def->isPhi()) {
3199 continue;
3200 }
3201
3202 for (MInstructionIterator ins = block->begin(); true; ins++) {
3203 if (*ins == def) {
3204 break;
3205 }
3206 MOZ_ASSERT(
3207 *ins != stop,
3208 "Resume point operand located after the safeInsertTop location");
3209 }
3210 }
3211 }
3212 #endif // DEBUG
3213
3214 void jit::AssertBasicGraphCoherency(MIRGraph& graph, bool force) {
3215 #ifdef DEBUG
3216 if (!JitOptions.fullDebugChecks && !force) {
3217 return;
3218 }
3219
3220 MOZ_ASSERT(graph.entryBlock()->numPredecessors() == 0);
3221 MOZ_ASSERT(graph.entryBlock()->phisEmpty());
3222 MOZ_ASSERT(!graph.entryBlock()->unreachable());
3223
3224 if (MBasicBlock* osrBlock = graph.osrBlock()) {
3225 MOZ_ASSERT(osrBlock->numPredecessors() == 0);
3226 MOZ_ASSERT(osrBlock->phisEmpty());
3227 MOZ_ASSERT(osrBlock != graph.entryBlock());
3228 MOZ_ASSERT(!osrBlock->unreachable());
3229 }
3230
3231 if (MResumePoint* resumePoint = graph.entryResumePoint()) {
3232 MOZ_ASSERT(resumePoint->block() == graph.entryBlock());
3233 }
3234
3235 // Assert successor and predecessor list coherency.
3236 uint32_t count = 0;
3237 int32_t usesBalance = 0;
3238 for (MBasicBlockIterator block(graph.begin()); block != graph.end();
3239 block++) {
3240 count++;
3241
3242 MOZ_ASSERT(&block->graph() == &graph);
3243 MOZ_ASSERT(!block->isDead());
3244 MOZ_ASSERT_IF(block->outerResumePoint() != nullptr,
3245 block->entryResumePoint() != nullptr);
3246
3247 for (size_t i = 0; i < block->numSuccessors(); i++) {
3248 MOZ_ASSERT(
3249 CheckSuccessorImpliesPredecessor(*block, block->getSuccessor(i)));
3250 }
3251
3252 for (size_t i = 0; i < block->numPredecessors(); i++) {
3253 MOZ_ASSERT(
3254 CheckPredecessorImpliesSuccessor(*block, block->getPredecessor(i)));
3255 }
3256
3257 if (MResumePoint* resume = block->entryResumePoint()) {
3258 MOZ_ASSERT(!resume->instruction());
3259 MOZ_ASSERT(resume->block() == *block);
3260 AssertOperandsBeforeSafeInsertTop(resume);
3261 }
3262 if (MResumePoint* resume = block->outerResumePoint()) {
3263 MOZ_ASSERT(!resume->instruction());
3264 MOZ_ASSERT(resume->block() == *block);
3265 }
3266 for (MResumePointIterator iter(block->resumePointsBegin());
3267 iter != block->resumePointsEnd(); iter++) {
3268 // We cannot yet assert that is there is no instruction then this is
3269 // the entry resume point because we are still storing resume points
3270 // in the InlinePropertyTable.
3271 MOZ_ASSERT_IF(iter->instruction(),
3272 iter->instruction()->block() == *block);
3273 for (uint32_t i = 0, e = iter->numOperands(); i < e; i++) {
3274 CheckOperand(*iter, iter->getUseFor(i), &usesBalance);
3275 }
3276 }
3277 for (MPhiIterator phi(block->phisBegin()); phi != block->phisEnd(); phi++) {
3278 MOZ_ASSERT(phi->numOperands() == block->numPredecessors());
3279 MOZ_ASSERT(!phi->isRecoveredOnBailout());
3280 MOZ_ASSERT(phi->type() != MIRType::None);
3281 MOZ_ASSERT(phi->dependency() == nullptr);
3282 }
3283 for (MDefinitionIterator iter(*block); iter; iter++) {
3284 MOZ_ASSERT(iter->block() == *block);
3285 MOZ_ASSERT_IF(iter->hasUses(), iter->type() != MIRType::None);
3286 MOZ_ASSERT(!iter->isDiscarded());
3287 MOZ_ASSERT_IF(iter->isStart(),
3288 *block == graph.entryBlock() || *block == graph.osrBlock());
3289 MOZ_ASSERT_IF(iter->isParameter(),
3290 *block == graph.entryBlock() || *block == graph.osrBlock());
3291 MOZ_ASSERT_IF(iter->isOsrEntry(), *block == graph.osrBlock());
3292 MOZ_ASSERT_IF(iter->isOsrValue(), *block == graph.osrBlock());
3293
3294 // Assert that use chains are valid for this instruction.
3295 for (uint32_t i = 0, end = iter->numOperands(); i < end; i++) {
3296 CheckOperand(*iter, iter->getUseFor(i), &usesBalance);
3297 }
3298 for (MUseIterator use(iter->usesBegin()); use != iter->usesEnd(); use++) {
3299 CheckUse(*iter, *use, &usesBalance);
3300 }
3301
3302 if (iter->isInstruction()) {
3303 if (MResumePoint* resume = iter->toInstruction()->resumePoint()) {
3304 MOZ_ASSERT(resume->instruction() == *iter);
3305 MOZ_ASSERT(resume->block() == *block);
3306 MOZ_ASSERT(resume->block()->entryResumePoint() != nullptr);
3307 }
3308 }
3309
3310 if (iter->isRecoveredOnBailout()) {
3311 MOZ_ASSERT(!iter->hasLiveDefUses());
3312 }
3313 }
3314
3315 // The control instruction is not visited by the MDefinitionIterator.
3316 MControlInstruction* control = block->lastIns();
3317 MOZ_ASSERT(control->block() == *block);
3318 MOZ_ASSERT(!control->hasUses());
3319 MOZ_ASSERT(control->type() == MIRType::None);
3320 MOZ_ASSERT(!control->isDiscarded());
3321 MOZ_ASSERT(!control->isRecoveredOnBailout());
3322 MOZ_ASSERT(control->resumePoint() == nullptr);
3323 for (uint32_t i = 0, end = control->numOperands(); i < end; i++) {
3324 CheckOperand(control, control->getUseFor(i), &usesBalance);
3325 }
3326 for (size_t i = 0; i < control->numSuccessors(); i++) {
3327 MOZ_ASSERT(control->getSuccessor(i));
3328 }
3329 }
3330
3331 // In case issues, see the _DEBUG_CHECK_OPERANDS_USES_BALANCE macro above.
3332 MOZ_ASSERT(usesBalance <= 0, "More use checks than operand checks");
3333 MOZ_ASSERT(usesBalance >= 0, "More operand checks than use checks");
3334 MOZ_ASSERT(graph.numBlocks() == count);
3335 #endif
3336 }
3337
3338 #ifdef DEBUG
3339 static void AssertReversePostorder(MIRGraph& graph) {
3340 // Check that every block is visited after all its predecessors (except
3341 // backedges).
3342 for (ReversePostorderIterator iter(graph.rpoBegin()); iter != graph.rpoEnd();
3343 ++iter) {
3344 MBasicBlock* block = *iter;
3345 MOZ_ASSERT(!block->isMarked());
3346
3347 for (size_t i = 0; i < block->numPredecessors(); i++) {
3348 MBasicBlock* pred = block->getPredecessor(i);
3349 if (!pred->isMarked()) {
3350 MOZ_ASSERT(pred->isLoopBackedge());
3351 MOZ_ASSERT(block->backedge() == pred);
3352 }
3353 }
3354
3355 block->mark();
3356 }
3357
3358 graph.unmarkBlocks();
3359 }
3360 #endif
3361
3362 #ifdef DEBUG
3363 static void AssertDominatorTree(MIRGraph& graph) {
3364 // Check dominators.
3365
3366 MOZ_ASSERT(graph.entryBlock()->immediateDominator() == graph.entryBlock());
3367 if (MBasicBlock* osrBlock = graph.osrBlock()) {
3368 MOZ_ASSERT(osrBlock->immediateDominator() == osrBlock);
3369 } else {
3370 MOZ_ASSERT(graph.entryBlock()->numDominated() == graph.numBlocks());
3371 }
3372
3373 size_t i = graph.numBlocks();
3374 size_t totalNumDominated = 0;
3375 for (MBasicBlockIterator block(graph.begin()); block != graph.end();
3376 block++) {
3377 MOZ_ASSERT(block->dominates(*block));
3378
3379 MBasicBlock* idom = block->immediateDominator();
3380 MOZ_ASSERT(idom->dominates(*block));
3381 MOZ_ASSERT(idom == *block || idom->id() < block->id());
3382
3383 if (idom == *block) {
3384 totalNumDominated += block->numDominated();
3385 } else {
3386 bool foundInParent = false;
3387 for (size_t j = 0; j < idom->numImmediatelyDominatedBlocks(); j++) {
3388 if (idom->getImmediatelyDominatedBlock(j) == *block) {
3389 foundInParent = true;
3390 break;
3391 }
3392 }
3393 MOZ_ASSERT(foundInParent);
3394 }
3395
3396 size_t numDominated = 1;
3397 for (size_t j = 0; j < block->numImmediatelyDominatedBlocks(); j++) {
3398 MBasicBlock* dom = block->getImmediatelyDominatedBlock(j);
3399 MOZ_ASSERT(block->dominates(dom));
3400 MOZ_ASSERT(dom->id() > block->id());
3401 MOZ_ASSERT(dom->immediateDominator() == *block);
3402
3403 numDominated += dom->numDominated();
3404 }
3405 MOZ_ASSERT(block->numDominated() == numDominated);
3406 MOZ_ASSERT(block->numDominated() <= i);
3407 MOZ_ASSERT(block->numSuccessors() != 0 || block->numDominated() == 1);
3408 i--;
3409 }
3410 MOZ_ASSERT(i == 0);
3411 MOZ_ASSERT(totalNumDominated == graph.numBlocks());
3412 }
3413 #endif
3414
3415 void jit::AssertGraphCoherency(MIRGraph& graph, bool force) {
3416 #ifdef DEBUG
3417 if (!JitOptions.checkGraphConsistency) {
3418 return;
3419 }
3420 if (!JitOptions.fullDebugChecks && !force) {
3421 return;
3422 }
3423 AssertBasicGraphCoherency(graph, force);
3424 AssertReversePostorder(graph);
3425 #endif
3426 }
3427
3428 #ifdef DEBUG
3429 static bool IsResumableMIRType(MIRType type) {
3430 // see CodeGeneratorShared::encodeAllocation
3431 switch (type) {
3432 case MIRType::Undefined:
3433 case MIRType::Null:
3434 case MIRType::Boolean:
3435 case MIRType::Int32:
3436 case MIRType::Double:
3437 case MIRType::Float32:
3438 case MIRType::String:
3439 case MIRType::Symbol:
3440 case MIRType::BigInt:
3441 case MIRType::Object:
3442 case MIRType::Shape:
3443 case MIRType::MagicOptimizedOut:
3444 case MIRType::MagicUninitializedLexical:
3445 case MIRType::MagicIsConstructing:
3446 case MIRType::Value:
3447 case MIRType::Int64:
3448 case MIRType::IntPtr:
3449 return true;
3450
3451 case MIRType::Simd128:
3452 case MIRType::MagicHole:
3453 case MIRType::None:
3454 case MIRType::Slots:
3455 case MIRType::Elements:
3456 case MIRType::Pointer:
3457 case MIRType::WasmAnyRef:
3458 case MIRType::WasmArrayData:
3459 case MIRType::StackResults:
3460 return false;
3461 }
3462 MOZ_CRASH("Unknown MIRType.");
3463 }
3464
3465 static void AssertResumableOperands(MNode* node) {
3466 for (size_t i = 0, e = node->numOperands(); i < e; ++i) {
3467 MDefinition* op = node->getOperand(i);
3468 if (op->isRecoveredOnBailout()) {
3469 continue;
3470 }
3471 MOZ_ASSERT(IsResumableMIRType(op->type()),
3472 "Resume point cannot encode its operands");
3473 }
3474 }
3475
3476 static void AssertIfResumableInstruction(MDefinition* def) {
3477 if (!def->isRecoveredOnBailout()) {
3478 return;
3479 }
3480 AssertResumableOperands(def);
3481 }
3482
3483 static void AssertResumePointDominatedByOperands(MResumePoint* resume) {
3484 for (size_t i = 0, e = resume->numOperands(); i < e; ++i) {
3485 MDefinition* op = resume->getOperand(i);
3486 MOZ_ASSERT(op->block()->dominates(resume->block()),
3487 "Resume point is not dominated by its operands");
3488 }
3489 }
3490 #endif // DEBUG
3491
3492 // Checks the basic GraphCoherency but also other conditions that
3493 // do not hold immediately (such as the fact that critical edges
3494 // are split, or conditions related to wasm semantics)
3495 void jit::AssertExtendedGraphCoherency(MIRGraph& graph, bool underValueNumberer,
3496 bool force) {
3497 #ifdef DEBUG
3498 if (!JitOptions.checkGraphConsistency) {
3499 return;
3500 }
3501 if (!JitOptions.fullDebugChecks && !force) {
3502 return;
3503 }
3504
3505 AssertGraphCoherency(graph, force);
3506
3507 AssertDominatorTree(graph);
3508
3509 DebugOnly<uint32_t> idx = 0;
3510 for (MBasicBlockIterator block(graph.begin()); block != graph.end();
3511 block++) {
3512 MOZ_ASSERT(block->id() == idx);
3513 ++idx;
3514
3515 // No critical edges:
3516 if (block->numSuccessors() > 1) {
3517 for (size_t i = 0; i < block->numSuccessors(); i++) {
3518 MOZ_ASSERT(block->getSuccessor(i)->numPredecessors() == 1);
3519 }
3520 }
3521
3522 if (block->isLoopHeader()) {
3523 if (underValueNumberer && block->numPredecessors() == 3) {
3524 // Fixup block.
3525 MOZ_ASSERT(block->getPredecessor(1)->numPredecessors() == 0);
3526 MOZ_ASSERT(graph.osrBlock(),
3527 "Fixup blocks should only exists if we have an osr block.");
3528 } else {
3529 MOZ_ASSERT(block->numPredecessors() == 2);
3530 }
3531 MBasicBlock* backedge = block->backedge();
3532 MOZ_ASSERT(backedge->id() >= block->id());
3533 MOZ_ASSERT(backedge->numSuccessors() == 1);
3534 MOZ_ASSERT(backedge->getSuccessor(0) == *block);
3535 }
3536
3537 if (!block->phisEmpty()) {
3538 for (size_t i = 0; i < block->numPredecessors(); i++) {
3539 MBasicBlock* pred = block->getPredecessor(i);
3540 MOZ_ASSERT(pred->successorWithPhis() == *block);
3541 MOZ_ASSERT(pred->positionInPhiSuccessor() == i);
3542 }
3543 }
3544
3545 uint32_t successorWithPhis = 0;
3546 for (size_t i = 0; i < block->numSuccessors(); i++) {
3547 if (!block->getSuccessor(i)->phisEmpty()) {
3548 successorWithPhis++;
3549 }
3550 }
3551
3552 MOZ_ASSERT(successorWithPhis <= 1);
3553 MOZ_ASSERT((successorWithPhis != 0) ==
3554 (block->successorWithPhis() != nullptr));
3555
3556 // Verify that phi operands dominate the corresponding CFG predecessor
3557 // edges.
3558 for (MPhiIterator iter(block->phisBegin()), end(block->phisEnd());
3559 iter != end; ++iter) {
3560 MPhi* phi = *iter;
3561 for (size_t i = 0, e = phi->numOperands(); i < e; ++i) {
3562 MOZ_ASSERT(
3563 phi->getOperand(i)->block()->dominates(block->getPredecessor(i)),
3564 "Phi input is not dominated by its operand");
3565 }
3566 }
3567
3568 // Verify that instructions are dominated by their operands.
3569 for (MInstructionIterator iter(block->begin()), end(block->end());
3570 iter != end; ++iter) {
3571 MInstruction* ins = *iter;
3572 for (size_t i = 0, e = ins->numOperands(); i < e; ++i) {
3573 MDefinition* op = ins->getOperand(i);
3574 MBasicBlock* opBlock = op->block();
3575 MOZ_ASSERT(opBlock->dominates(*block),
3576 "Instruction is not dominated by its operands");
3577
3578 // If the operand is an instruction in the same block, check
3579 // that it comes first.
3580 if (opBlock == *block && !op->isPhi()) {
3581 MInstructionIterator opIter = block->begin(op->toInstruction());
3582 do {
3583 ++opIter;
3584 MOZ_ASSERT(opIter != block->end(),
3585 "Operand in same block as instruction does not precede");
3586 } while (*opIter != ins);
3587 }
3588 }
3589 AssertIfResumableInstruction(ins);
3590 if (MResumePoint* resume = ins->resumePoint()) {
3591 AssertResumePointDominatedByOperands(resume);
3592 AssertResumableOperands(resume);
3593 }
3594 }
3595
3596 // Verify that the block resume points are dominated by their operands.
3597 if (MResumePoint* resume = block->entryResumePoint()) {
3598 AssertResumePointDominatedByOperands(resume);
3599 AssertResumableOperands(resume);
3600 }
3601 if (MResumePoint* resume = block->outerResumePoint()) {
3602 AssertResumePointDominatedByOperands(resume);
3603 AssertResumableOperands(resume);
3604 }
3605
3606 // Verify that any nodes with a wasm ref type have MIRType WasmAnyRef.
3607 for (MDefinitionIterator def(*block); def; def++) {
3608 MOZ_ASSERT_IF(def->wasmRefType().isSome(),
3609 def->type() == MIRType::WasmAnyRef);
3610 }
3611 }
3612 #endif
3613 }
3614
3615 struct BoundsCheckInfo {
3616 MBoundsCheck* check;
3617 uint32_t validEnd;
3618 };
3619
3620 using BoundsCheckMap =
3621 HashMap<uint32_t, BoundsCheckInfo, DefaultHasher<uint32_t>, JitAllocPolicy>;
3622
3623 // Compute a hash for bounds checks which ignores constant offsets in the index.
3624 static HashNumber BoundsCheckHashIgnoreOffset(MBoundsCheck* check) {
3625 SimpleLinearSum indexSum = ExtractLinearSum(check->index());
3626 uintptr_t index = indexSum.term ? uintptr_t(indexSum.term) : 0;
3627 uintptr_t length = uintptr_t(check->length());
3628 return index ^ length;
3629 }
3630
3631 static MBoundsCheck* FindDominatingBoundsCheck(BoundsCheckMap& checks,
3632 MBoundsCheck* check,
3633 size_t index) {
3634 // Since we are traversing the dominator tree in pre-order, when we
3635 // are looking at the |index|-th block, the next numDominated() blocks
3636 // we traverse are precisely the set of blocks that are dominated.
3637 //
3638 // So, this value is visible in all blocks if:
3639 // index <= index + ins->block->numDominated()
3640 // and becomes invalid after that.
3641 HashNumber hash = BoundsCheckHashIgnoreOffset(check);
3642 BoundsCheckMap::Ptr p = checks.lookup(hash);
3643 if (!p || index >= p->value().validEnd) {
3644 // We didn't find a dominating bounds check.
3645 BoundsCheckInfo info;
3646 info.check = check;
3647 info.validEnd = index + check->block()->numDominated();
3648
3649 if (!checks.put(hash, info)) return nullptr;
3650
3651 return check;
3652 }
3653
3654 return p->value().check;
3655 }
3656
3657 static MathSpace ExtractMathSpace(MDefinition* ins) {
3658 MOZ_ASSERT(ins->isAdd() || ins->isSub());
3659 MBinaryArithInstruction* arith = nullptr;
3660 if (ins->isAdd()) {
3661 arith = ins->toAdd();
3662 } else {
3663 arith = ins->toSub();
3664 }
3665 switch (arith->truncateKind()) {
3666 case TruncateKind::NoTruncate:
3667 case TruncateKind::TruncateAfterBailouts:
3668 // TruncateAfterBailouts is considered as infinite space because the
3669 // LinearSum will effectively remove the bailout check.
3670 return MathSpace::Infinite;
3671 case TruncateKind::IndirectTruncate:
3672 case TruncateKind::Truncate:
3673 return MathSpace::Modulo;
3674 }
3675 MOZ_CRASH("Unknown TruncateKind");
3676 }
3677
3678 static bool MonotoneAdd(int32_t lhs, int32_t rhs) {
3679 return (lhs >= 0 && rhs >= 0) || (lhs <= 0 && rhs <= 0);
3680 }
3681
3682 static bool MonotoneSub(int32_t lhs, int32_t rhs) {
3683 return (lhs >= 0 && rhs <= 0) || (lhs <= 0 && rhs >= 0);
3684 }
3685
3686 // Extract a linear sum from ins, if possible (otherwise giving the
3687 // sum 'ins + 0').
3688 SimpleLinearSum jit::ExtractLinearSum(MDefinition* ins, MathSpace space,
3689 int32_t recursionDepth) {
3690 const int32_t SAFE_RECURSION_LIMIT = 100;
3691 if (recursionDepth > SAFE_RECURSION_LIMIT) {
3692 return SimpleLinearSum(ins, 0);
3693 }
3694
3695 // Unwrap Int32ToIntPtr. This instruction only changes the representation
3696 // (int32_t to intptr_t) without affecting the value.
3697 if (ins->isInt32ToIntPtr()) {
3698 ins = ins->toInt32ToIntPtr()->input();
3699 }
3700
3701 if (ins->isBeta()) {
3702 ins = ins->getOperand(0);
3703 }
3704
3705 MOZ_ASSERT(!ins->isInt32ToIntPtr());
3706
3707 if (ins->type() != MIRType::Int32) {
3708 return SimpleLinearSum(ins, 0);
3709 }
3710
3711 if (ins->isConstant()) {
3712 return SimpleLinearSum(nullptr, ins->toConstant()->toInt32());
3713 }
3714
3715 if (!ins->isAdd() && !ins->isSub()) {
3716 return SimpleLinearSum(ins, 0);
3717 }
3718
3719 // Only allow math which are in the same space.
3720 MathSpace insSpace = ExtractMathSpace(ins);
3721 if (space == MathSpace::Unknown) {
3722 space = insSpace;
3723 } else if (space != insSpace) {
3724 return SimpleLinearSum(ins, 0);
3725 }
3726 MOZ_ASSERT(space == MathSpace::Modulo || space == MathSpace::Infinite);
3727
3728 if (space == MathSpace::Modulo) {
3729 return SimpleLinearSum(ins, 0);
3730 }
3731
3732 MDefinition* lhs = ins->getOperand(0);
3733 MDefinition* rhs = ins->getOperand(1);
3734 if (lhs->type() != MIRType::Int32 || rhs->type() != MIRType::Int32) {
3735 return SimpleLinearSum(ins, 0);
3736 }
3737
3738 // Extract linear sums of each operand.
3739 SimpleLinearSum lsum = ExtractLinearSum(lhs, space, recursionDepth + 1);
3740 SimpleLinearSum rsum = ExtractLinearSum(rhs, space, recursionDepth + 1);
3741
3742 // LinearSum only considers a single term operand, if both sides have
3743 // terms, then ignore extracted linear sums.
3744 if (lsum.term && rsum.term) {
3745 return SimpleLinearSum(ins, 0);
3746 }
3747
3748 // Check if this is of the form <SUM> + n or n + <SUM>.
3749 if (ins->isAdd()) {
3750 int32_t constant;
3751 if (space == MathSpace::Modulo) {
3752 constant = uint32_t(lsum.constant) + uint32_t(rsum.constant);
3753 } else if (!SafeAdd(lsum.constant, rsum.constant, &constant) ||
3754 !MonotoneAdd(lsum.constant, rsum.constant)) {
3755 return SimpleLinearSum(ins, 0);
3756 }
3757 return SimpleLinearSum(lsum.term ? lsum.term : rsum.term, constant);
3758 }
3759
3760 MOZ_ASSERT(ins->isSub());
3761 // Check if this is of the form <SUM> - n.
3762 if (lsum.term) {
3763 int32_t constant;
3764 if (space == MathSpace::Modulo) {
3765 constant = uint32_t(lsum.constant) - uint32_t(rsum.constant);
3766 } else if (!SafeSub(lsum.constant, rsum.constant, &constant) ||
3767 !MonotoneSub(lsum.constant, rsum.constant)) {
3768 return SimpleLinearSum(ins, 0);
3769 }
3770 return SimpleLinearSum(lsum.term, constant);
3771 }
3772
3773 // Ignore any of the form n - <SUM>.
3774 return SimpleLinearSum(ins, 0);
3775 }
3776
3777 // Extract a linear inequality holding when a boolean test goes in the
3778 // specified direction, of the form 'lhs + lhsN <= rhs' (or >=).
3779 bool jit::ExtractLinearInequality(const MTest* test, BranchDirection direction,
3780 SimpleLinearSum* plhs, MDefinition** prhs,
3781 bool* plessEqual) {
3782 if (!test->getOperand(0)->isCompare()) {
3783 return false;
3784 }
3785
3786 MCompare* compare = test->getOperand(0)->toCompare();
3787
3788 MDefinition* lhs = compare->getOperand(0);
3789 MDefinition* rhs = compare->getOperand(1);
3790
3791 // TODO: optimize Compare_UInt32
3792 if (!compare->isInt32Comparison()) {
3793 return false;
3794 }
3795
3796 MOZ_ASSERT(lhs->type() == MIRType::Int32);
3797 MOZ_ASSERT(rhs->type() == MIRType::Int32);
3798
3799 JSOp jsop = compare->jsop();
3800 if (direction == FALSE_BRANCH) {
3801 jsop = NegateCompareOp(jsop);
3802 }
3803
3804 SimpleLinearSum lsum = ExtractLinearSum(lhs);
3805 SimpleLinearSum rsum = ExtractLinearSum(rhs);
3806
3807 if (!SafeSub(lsum.constant, rsum.constant, &lsum.constant)) {
3808 return false;
3809 }
3810
3811 // Normalize operations to use <= or >=.
3812 switch (jsop) {
3813 case JSOp::Le:
3814 *plessEqual = true;
3815 break;
3816 case JSOp::Lt:
3817 /* x < y ==> x + 1 <= y */
3818 if (!SafeAdd(lsum.constant, 1, &lsum.constant)) {
3819 return false;
3820 }
3821 *plessEqual = true;
3822 break;
3823 case JSOp::Ge:
3824 *plessEqual = false;
3825 break;
3826 case JSOp::Gt:
3827 /* x > y ==> x - 1 >= y */
3828 if (!SafeSub(lsum.constant, 1, &lsum.constant)) {
3829 return false;
3830 }
3831 *plessEqual = false;
3832 break;
3833 default:
3834 return false;
3835 }
3836
3837 *plhs = lsum;
3838 *prhs = rsum.term;
3839
3840 return true;
3841 }
3842
3843 static bool TryEliminateBoundsCheck(BoundsCheckMap& checks, size_t blockIndex,
3844 MBoundsCheck* dominated, bool* eliminated) {
3845 MOZ_ASSERT(!*eliminated);
3846
3847 // Replace all uses of the bounds check with the actual index.
3848 // This is (a) necessary, because we can coalesce two different
3849 // bounds checks and would otherwise use the wrong index and
3850 // (b) helps register allocation. Note that this is safe since
3851 // no other pass after bounds check elimination moves instructions.
3852 dominated->replaceAllUsesWith(dominated->index());
3853
3854 if (!dominated->isMovable()) {
3855 return true;
3856 }
3857
3858 if (!dominated->fallible()) {
3859 return true;
3860 }
3861
3862 MBoundsCheck* dominating =
3863 FindDominatingBoundsCheck(checks, dominated, blockIndex);
3864 if (!dominating) {
3865 return false;
3866 }
3867
3868 if (dominating == dominated) {
3869 // We didn't find a dominating bounds check.
3870 return true;
3871 }
3872
3873 // We found two bounds checks with the same hash number, but we still have
3874 // to make sure the lengths and index terms are equal.
3875 if (dominating->length() != dominated->length()) {
3876 return true;
3877 }
3878
3879 SimpleLinearSum sumA = ExtractLinearSum(dominating->index());
3880 SimpleLinearSum sumB = ExtractLinearSum(dominated->index());
3881
3882 // Both terms should be nullptr or the same definition.
3883 if (sumA.term != sumB.term) {
3884 return true;
3885 }
3886
3887 // This bounds check is redundant.
3888 *eliminated = true;
3889
3890 // Normalize the ranges according to the constant offsets in the two indexes.
3891 int32_t minimumA, maximumA, minimumB, maximumB;
3892 if (!SafeAdd(sumA.constant, dominating->minimum(), &minimumA) ||
3893 !SafeAdd(sumA.constant, dominating->maximum(), &maximumA) ||
3894 !SafeAdd(sumB.constant, dominated->minimum(), &minimumB) ||
3895 !SafeAdd(sumB.constant, dominated->maximum(), &maximumB)) {
3896 return false;
3897 }
3898
3899 // Update the dominating check to cover both ranges, denormalizing the
3900 // result per the constant offset in the index.
3901 int32_t newMinimum, newMaximum;
3902 if (!SafeSub(std::min(minimumA, minimumB), sumA.constant, &newMinimum) ||
3903 !SafeSub(std::max(maximumA, maximumB), sumA.constant, &newMaximum)) {
3904 return false;
3905 }
3906
3907 dominating->setMinimum(newMinimum);
3908 dominating->setMaximum(newMaximum);
3909 dominating->setBailoutKind(BailoutKind::HoistBoundsCheck);
3910
3911 return true;
3912 }
3913
3914 // Eliminate checks which are redundant given each other or other instructions.
3915 //
3916 // A bounds check is considered redundant if it's dominated by another bounds
3917 // check with the same length and the indexes differ by only a constant amount.
3918 // In this case we eliminate the redundant bounds check and update the other one
3919 // to cover the ranges of both checks.
3920 //
3921 // Bounds checks are added to a hash map and since the hash function ignores
3922 // differences in constant offset, this offers a fast way to find redundant
3923 // checks.
3924 bool jit::EliminateRedundantChecks(MIRGraph& graph) {
3925 BoundsCheckMap checks(graph.alloc());
3926
3927 // Stack for pre-order CFG traversal.
3928 Vector<MBasicBlock*, 1, JitAllocPolicy> worklist(graph.alloc());
3929
3930 // The index of the current block in the CFG traversal.
3931 size_t index = 0;
3932
3933 // Add all self-dominating blocks to the worklist.
3934 // This includes all roots. Order does not matter.
3935 for (MBasicBlockIterator i(graph.begin()); i != graph.end(); i++) {
3936 MBasicBlock* block = *i;
3937 if (block->immediateDominator() == block) {
3938 if (!worklist.append(block)) {
3939 return false;
3940 }
3941 }
3942 }
3943
3944 // Starting from each self-dominating block, traverse the CFG in pre-order.
3945 while (!worklist.empty()) {
3946 MBasicBlock* block = worklist.popCopy();
3947
3948 // Add all immediate dominators to the front of the worklist.
3949 if (!worklist.append(block->immediatelyDominatedBlocksBegin(),
3950 block->immediatelyDominatedBlocksEnd())) {
3951 return false;
3952 }
3953
3954 for (MDefinitionIterator iter(block); iter;) {
3955 MDefinition* def = *iter++;
3956
3957 if (!def->isBoundsCheck()) {
3958 continue;
3959 }
3960 auto* boundsCheck = def->toBoundsCheck();
3961
3962 bool eliminated = false;
3963 if (!TryEliminateBoundsCheck(checks, index, boundsCheck, &eliminated)) {
3964 return false;
3965 }
3966
3967 if (eliminated) {
3968 block->discard(boundsCheck);
3969 }
3970 }
3971 index++;
3972 }
3973
3974 MOZ_ASSERT(index == graph.numBlocks());
3975
3976 return true;
3977 }
3978
3979 static bool ShapeGuardIsRedundant(MGuardShape* guard,
3980 const MDefinition* storeObject,
3981 const Shape* storeShape) {
3982 const MDefinition* guardObject = guard->object()->skipObjectGuards();
3983 if (guardObject != storeObject) {
3984 JitSpew(JitSpew_RedundantShapeGuards, "SKIP: different objects (%d vs %d)",
3985 guardObject->id(), storeObject->id());
3986 return false;
3987 }
3988
3989 const Shape* guardShape = guard->shape();
3990 if (guardShape != storeShape) {
3991 JitSpew(JitSpew_RedundantShapeGuards, "SKIP: different shapes");
3992 return false;
3993 }
3994
3995 return true;
3996 }
3997
3998 // Eliminate shape guards which are redundant given other instructions.
3999 //
4000 // A shape guard is redundant if we can prove that the object being
4001 // guarded already has the correct shape. The conditions for doing so
4002 // are as follows:
4003 //
4004 // 1. We can see the most recent change to the shape of this object.
4005 // (This can be an AddAndStoreSlot, an AllocateAndStoreSlot, or the
4006 // creation of the object itself.
4007 // 2. That mutation dominates the shape guard.
4008 // 3. The shape that was assigned at that point matches the shape
4009 // we expect.
4010 //
4011 // If all of these conditions hold, then we can remove the shape guard.
4012 // In debug, we replace it with an AssertShape to help verify correctness.
4013 bool jit::EliminateRedundantShapeGuards(MIRGraph& graph) {
4014 JitSpew(JitSpew_RedundantShapeGuards, "Begin");
4015
4016 for (ReversePostorderIterator block = graph.rpoBegin();
4017 block != graph.rpoEnd(); block++) {
4018 for (MInstructionIterator insIter(block->begin());
4019 insIter != block->end();) {
4020 MInstruction* ins = *insIter;
4021 insIter++;
4022
4023 // Skip instructions that aren't shape guards.
4024 if (!ins->isGuardShape()) {
4025 continue;
4026 }
4027 MGuardShape* guard = ins->toGuardShape();
4028 MDefinition* lastStore = guard->dependency();
4029
4030 JitSpew(JitSpew_RedundantShapeGuards, "Visit shape guard %d",
4031 guard->id());
4032 JitSpewIndent spewIndent(JitSpew_RedundantShapeGuards);
4033
4034 if (lastStore->isDiscarded() || lastStore->block()->isDead() ||
4035 !lastStore->block()->dominates(guard->block())) {
4036 JitSpew(JitSpew_RedundantShapeGuards,
4037 "SKIP: ins %d does not dominate block %d", lastStore->id(),
4038 guard->block()->id());
4039 continue;
4040 }
4041
4042 if (lastStore->isAddAndStoreSlot()) {
4043 auto* add = lastStore->toAddAndStoreSlot();
4044 auto* addObject = add->object()->skipObjectGuards();
4045 if (!ShapeGuardIsRedundant(guard, addObject, add->shape())) {
4046 continue;
4047 }
4048 } else if (lastStore->isAllocateAndStoreSlot()) {
4049 auto* allocate = lastStore->toAllocateAndStoreSlot();
4050 auto* allocateObject = allocate->object()->skipObjectGuards();
4051 if (!ShapeGuardIsRedundant(guard, allocateObject, allocate->shape())) {
4052 continue;
4053 }
4054 } else if (lastStore->isStart()) {
4055 // The guard doesn't depend on any other instruction that is modifying
4056 // the object operand, so we check the object operand directly.
4057 auto* obj = guard->object()->skipObjectGuards();
4058
4059 const Shape* initialShape = nullptr;
4060 if (obj->isNewObject()) {
4061 auto* templateObject = obj->toNewObject()->templateObject();
4062 if (!templateObject) {
4063 JitSpew(JitSpew_RedundantShapeGuards, "SKIP: no template");
4064 continue;
4065 }
4066 initialShape = templateObject->shape();
4067 } else if (obj->isNewPlainObject()) {
4068 initialShape = obj->toNewPlainObject()->shape();
4069 } else {
4070 JitSpew(JitSpew_RedundantShapeGuards,
4071 "SKIP: not NewObject or NewPlainObject (%d)", obj->id());
4072 continue;
4073 }
4074 if (initialShape != guard->shape()) {
4075 JitSpew(JitSpew_RedundantShapeGuards, "SKIP: shapes don't match");
4076 continue;
4077 }
4078 } else {
4079 JitSpew(JitSpew_RedundantShapeGuards,
4080 "SKIP: Last store not supported (%d)", lastStore->id());
4081 continue;
4082 }
4083
4084 #ifdef DEBUG
4085 if (!graph.alloc().ensureBallast()) {
4086 return false;
4087 }
4088 auto* assert = MAssertShape::New(graph.alloc(), guard->object(),
4089 const_cast<Shape*>(guard->shape()));
4090 guard->block()->insertBefore(guard, assert);
4091 #endif
4092
4093 JitSpew(JitSpew_RedundantShapeGuards, "SUCCESS: Removing shape guard %d",
4094 guard->id());
4095 guard->replaceAllUsesWith(guard->input());
4096 guard->block()->discard(guard);
4097 }
4098 }
4099
4100 return true;
4101 }
4102
4103 [[nodiscard]] static bool TryEliminateGCBarriersForAllocation(
4104 TempAllocator& alloc, MInstruction* allocation) {
4105 MOZ_ASSERT(allocation->type() == MIRType::Object);
4106
4107 JitSpew(JitSpew_RedundantGCBarriers, "Analyzing allocation %s",
4108 allocation->opName());
4109
4110 MBasicBlock* block = allocation->block();
4111 MInstructionIterator insIter(block->begin(allocation));
4112
4113 // Skip `allocation`.
4114 MOZ_ASSERT(*insIter == allocation);
4115 insIter++;
4116
4117 // Try to optimize the other instructions in the block.
4118 while (insIter != block->end()) {
4119 MInstruction* ins = *insIter;
4120 insIter++;
4121 switch (ins->op()) {
4122 case MDefinition::Opcode::Constant:
4123 case MDefinition::Opcode::Box:
4124 case MDefinition::Opcode::Unbox:
4125 case MDefinition::Opcode::AssertCanElidePostWriteBarrier:
4126 // These instructions can't trigger GC or affect this analysis in other
4127 // ways.
4128 break;
4129 case MDefinition::Opcode::StoreFixedSlot: {
4130 auto* store = ins->toStoreFixedSlot();
4131 if (store->object() != allocation) {
4132 JitSpew(JitSpew_RedundantGCBarriers,
4133 "Stopped at StoreFixedSlot for other object");
4134 return true;
4135 }
4136 store->setNeedsBarrier(false);
4137 JitSpew(JitSpew_RedundantGCBarriers, "Elided StoreFixedSlot barrier");
4138 break;
4139 }
4140 case MDefinition::Opcode::PostWriteBarrier: {
4141 auto* barrier = ins->toPostWriteBarrier();
4142 if (barrier->object() != allocation) {
4143 JitSpew(JitSpew_RedundantGCBarriers,
4144 "Stopped at PostWriteBarrier for other object");
4145 return true;
4146 }
4147 #ifdef DEBUG
4148 if (!alloc.ensureBallast()) {
4149 return false;
4150 }
4151 MDefinition* value = barrier->value();
4152 if (value->type() != MIRType::Value) {
4153 value = MBox::New(alloc, value);
4154 block->insertBefore(barrier, value->toInstruction());
4155 }
4156 auto* assert =
4157 MAssertCanElidePostWriteBarrier::New(alloc, allocation, value);
4158 block->insertBefore(barrier, assert);
4159 #endif
4160 block->discard(barrier);
4161 JitSpew(JitSpew_RedundantGCBarriers, "Elided PostWriteBarrier");
4162 break;
4163 }
4164 default:
4165 JitSpew(JitSpew_RedundantGCBarriers,
4166 "Stopped at unsupported instruction %s", ins->opName());
4167 return true;
4168 }
4169 }
4170
4171 return true;
4172 }
4173
4174 bool jit::EliminateRedundantGCBarriers(MIRGraph& graph) {
4175 // Peephole optimization for the following pattern:
4176 //
4177 // 0: MNewCallObject
4178 // 1: MStoreFixedSlot(0, ...)
4179 // 2: MStoreFixedSlot(0, ...)
4180 // 3: MPostWriteBarrier(0, ...)
4181 //
4182 // If the instructions immediately following the allocation instruction can't
4183 // trigger GC and we are storing to the new object's slots, we can elide the
4184 // pre-barrier.
4185 //
4186 // We also eliminate the post barrier and (in debug builds) replace it with an
4187 // assertion.
4188 //
4189 // See also the similar optimizations in WarpBuilder::buildCallObject.
4190
4191 JitSpew(JitSpew_RedundantGCBarriers, "Begin");
4192
4193 for (ReversePostorderIterator block = graph.rpoBegin();
4194 block != graph.rpoEnd(); block++) {
4195 for (MInstructionIterator insIter(block->begin()); insIter != block->end();
4196 insIter++) {
4197 MInstruction* ins = *insIter;
4198 if (ins->isNewCallObject()) {
4199 MNewCallObject* allocation = ins->toNewCallObject();
4200 // We can only eliminate the post barrier if we know the call object
4201 // will be allocated in the nursery.
4202 if (allocation->initialHeap() == gc::Heap::Default) {
4203 if (!TryEliminateGCBarriersForAllocation(graph.alloc(), allocation)) {
4204 return false;
4205 }
4206 }
4207 }
4208 }
4209 }
4210
4211 return true;
4212 }
4213
4214 bool jit::MarkLoadsUsedAsPropertyKeys(MIRGraph& graph) {
4215 // When a string is used as a property key, or as the key for a Map or Set, we
4216 // require it to be atomized. To avoid repeatedly atomizing the same string,
4217 // this analysis looks for cases where we are loading a value from the slot of
4218 // an object (which includes access to global variables and global lexicals)
4219 // and using it as a property key, and marks those loads. During codegen,
4220 // marked loads will check whether the value loaded is a non-atomized string.
4221 // If it is, we will atomize the string and update the stored value, ensuring
4222 // that future loads from the same slot will not have to atomize again.
4223 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys, "Begin");
4224
4225 for (ReversePostorderIterator block = graph.rpoBegin();
4226 block != graph.rpoEnd(); block++) {
4227 for (MInstructionIterator insIter(block->begin());
4228 insIter != block->end();) {
4229 MInstruction* ins = *insIter;
4230 insIter++;
4231
4232 MDefinition* idVal = nullptr;
4233 if (ins->isGetPropertyCache()) {
4234 idVal = ins->toGetPropertyCache()->idval();
4235 } else if (ins->isHasOwnCache()) {
4236 idVal = ins->toHasOwnCache()->idval();
4237 } else if (ins->isSetPropertyCache()) {
4238 idVal = ins->toSetPropertyCache()->idval();
4239 } else if (ins->isGetPropSuperCache()) {
4240 idVal = ins->toGetPropSuperCache()->idval();
4241 } else if (ins->isMegamorphicLoadSlotByValue()) {
4242 idVal = ins->toMegamorphicLoadSlotByValue()->idVal();
4243 } else if (ins->isMegamorphicHasProp()) {
4244 idVal = ins->toMegamorphicHasProp()->idVal();
4245 } else if (ins->isMegamorphicSetElement()) {
4246 idVal = ins->toMegamorphicSetElement()->index();
4247 } else if (ins->isProxyGetByValue()) {
4248 idVal = ins->toProxyGetByValue()->idVal();
4249 } else if (ins->isProxyHasProp()) {
4250 idVal = ins->toProxyHasProp()->idVal();
4251 } else if (ins->isProxySetByValue()) {
4252 idVal = ins->toProxySetByValue()->idVal();
4253 } else if (ins->isIdToStringOrSymbol()) {
4254 idVal = ins->toIdToStringOrSymbol()->idVal();
4255 } else if (ins->isGuardSpecificAtom()) {
4256 idVal = ins->toGuardSpecificAtom()->input();
4257 } else if (ins->isToHashableString()) {
4258 idVal = ins->toToHashableString()->input();
4259 } else if (ins->isToHashableValue()) {
4260 idVal = ins->toToHashableValue()->input();
4261 } else if (ins->isMapObjectHasValueVMCall()) {
4262 idVal = ins->toMapObjectHasValueVMCall()->value();
4263 } else if (ins->isMapObjectGetValueVMCall()) {
4264 idVal = ins->toMapObjectGetValueVMCall()->value();
4265 } else if (ins->isSetObjectHasValueVMCall()) {
4266 idVal = ins->toSetObjectHasValueVMCall()->value();
4267 } else {
4268 continue;
4269 }
4270 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys,
4271 "Analyzing property access %s%d with idVal %s%d", ins->opName(),
4272 ins->id(), idVal->opName(), idVal->id());
4273
4274 // Skip intermediate nodes.
4275 do {
4276 if (idVal->isLexicalCheck()) {
4277 idVal = idVal->toLexicalCheck()->input();
4278 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys,
4279 "- Skipping lexical check. idVal is now %s%d",
4280 idVal->opName(), idVal->id());
4281 continue;
4282 }
4283 if (idVal->isUnbox() && idVal->type() == MIRType::String) {
4284 idVal = idVal->toUnbox()->input();
4285 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys,
4286 "- Skipping unbox. idVal is now %s%d", idVal->opName(),
4287 idVal->id());
4288 continue;
4289 }
4290 break;
4291 } while (true);
4292
4293 if (idVal->isLoadFixedSlot()) {
4294 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys,
4295 "- SUCCESS: Marking fixed slot");
4296 idVal->toLoadFixedSlot()->setUsedAsPropertyKey();
4297 } else if (idVal->isLoadDynamicSlot()) {
4298 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys,
4299 "- SUCCESS: Marking dynamic slot");
4300 idVal->toLoadDynamicSlot()->setUsedAsPropertyKey();
4301 } else {
4302 JitSpew(JitSpew_MarkLoadsUsedAsPropertyKeys, "- SKIP: %s not supported",
4303 idVal->opName());
4304 }
4305 }
4306 }
4307
4308 return true;
4309 }
4310
4311 // Updates the wasm ref type of a node and verifies that in this pass we only
4312 // narrow types, and never widen.
4313 static bool UpdateWasmRefType(MDefinition* def) {
4314 wasm::MaybeRefType newRefType = def->computeWasmRefType();
4315 bool changed = newRefType != def->wasmRefType();
4316
4317 // Ensure that we do not regress from Some to Nothing.
4318 MOZ_ASSERT(!(def->wasmRefType().isSome() && newRefType.isNothing()));
4319 // Ensure that the new ref type is a subtype of the previous one (i.e. we
4320 // only narrow ref types).
4321 MOZ_ASSERT_IF(def->wasmRefType().isSome(),
4322 wasm::RefType::isSubTypeOf(newRefType.value(),
4323 def->wasmRefType().value()));
4324
4325 def->setWasmRefType(newRefType);
4326 return changed;
4327 }
4328
4329 // Since wasm has a fairly rich type system enforced in validation, we can use
4330 // this type system within MIR to robustly track the types of ref values. This
4331 // allows us to make MIR-level optimizations such as eliding null checks or
4332 // omitting redundant casts.
4333 //
4334 // This analysis pass performs simple data flow analysis by assigning ref types
4335 // to each definition, then revisiting phis and their uses as necessary until
4336 // the types have narrowed to a fixed point.
4337 bool jit::TrackWasmRefTypes(MIRGraph& graph) {
4338 // The worklist tracks nodes whose types have changed and whose uses must
4339 // therefore be re-evaluated.
4340 Vector<MDefinition*, 16, SystemAllocPolicy> worklist;
4341
4342 // Assign an initial ref type to each definition. Reverse postorder ensures
4343 // that nodes are always visited before their uses, with the exception of loop
4344 // backedge phis.
4345 for (ReversePostorderIterator blockIter = graph.rpoBegin();
4346 blockIter != graph.rpoEnd(); blockIter++) {
4347 MBasicBlock* block = *blockIter;
4348 for (MDefinitionIterator def(block); def; def++) {
4349 // Set the initial type on all nodes. If a type is produced, then any
4350 // loop backedge phis that use this node must have been previously
4351 // visited, and must be updated and possibly added to the worklist. (Any
4352 // other uses of this node will be visited later in this first pass.)
4353
4354 if (def->type() != MIRType::WasmAnyRef) {
4355 continue;
4356 }
4357
4358 bool hasType = UpdateWasmRefType(*def);
4359 if (hasType) {
4360 for (MUseIterator use(def->usesBegin()); use != def->usesEnd(); use++) {
4361 MNode* consumer = use->consumer();
4362 if (!consumer->isDefinition() || !consumer->toDefinition()->isPhi()) {
4363 continue;
4364 }
4365 MPhi* phi = consumer->toDefinition()->toPhi();
4366 if (phi->block()->isLoopHeader() &&
4367 *def == phi->getLoopBackedgeOperand()) {
4368 bool changed = UpdateWasmRefType(phi);
4369 if (changed && !worklist.append(phi)) {
4370 return false;
4371 }
4372 } else {
4373 // Any other type of use must not have a ref type yet, because we
4374 // are yet to hit it in this forward pass.
4375 MOZ_ASSERT(consumer->toDefinition()->wasmRefType().isNothing());
4376 }
4377 }
4378 }
4379 }
4380 }
4381
4382 // Until the worklist is empty, update the uses of any worklist nodes and
4383 // track the ones whose types change.
4384 while (!worklist.empty()) {
4385 MDefinition* def = worklist.popCopy();
4386
4387 for (MUseIterator use(def->usesBegin()); use != def->usesEnd(); use++) {
4388 if (!use->consumer()->isDefinition()) {
4389 continue;
4390 }
4391 bool changed = UpdateWasmRefType(use->consumer()->toDefinition());
4392 if (changed && !worklist.append(use->consumer()->toDefinition())) {
4393 return false;
4394 }
4395 }
4396 }
4397
4398 return true;
4399 }
4400
4401 static bool NeedsKeepAlive(MInstruction* slotsOrElements, MInstruction* use) {
4402 MOZ_ASSERT(slotsOrElements->type() == MIRType::Elements ||
4403 slotsOrElements->type() == MIRType::Slots);
4404
4405 if (slotsOrElements->block() != use->block()) {
4406 return true;
4407 }
4408
4409 // Allocating a BigInt can GC, so we have to keep the object alive.
4410 if (use->type() == MIRType::BigInt) {
4411 return true;
4412 }
4413 if (use->isLoadTypedArrayElementHole() &&
4414 Scalar::isBigIntType(use->toLoadTypedArrayElementHole()->arrayType())) {
4415 return true;
4416 }
4417
4418 MBasicBlock* block = use->block();
4419 MInstructionIterator iter(block->begin(slotsOrElements));
4420 MOZ_ASSERT(*iter == slotsOrElements);
4421 ++iter;
4422
4423 while (true) {
4424 if (*iter == use) {
4425 return false;
4426 }
4427
4428 switch (iter->op()) {
4429 case MDefinition::Opcode::Nop:
4430 case MDefinition::Opcode::Constant:
4431 case MDefinition::Opcode::KeepAliveObject:
4432 case MDefinition::Opcode::Unbox:
4433 case MDefinition::Opcode::LoadDynamicSlot:
4434 case MDefinition::Opcode::StoreDynamicSlot:
4435 case MDefinition::Opcode::LoadFixedSlot:
4436 case MDefinition::Opcode::StoreFixedSlot:
4437 case MDefinition::Opcode::LoadElement:
4438 case MDefinition::Opcode::LoadElementAndUnbox:
4439 case MDefinition::Opcode::LoadElementHole:
4440 case MDefinition::Opcode::StoreElement:
4441 case MDefinition::Opcode::StoreHoleValueElement:
4442 case MDefinition::Opcode::InitializedLength:
4443 case MDefinition::Opcode::ArrayLength:
4444 case MDefinition::Opcode::BoundsCheck:
4445 case MDefinition::Opcode::GuardElementNotHole:
4446 case MDefinition::Opcode::InArray:
4447 case MDefinition::Opcode::SpectreMaskIndex:
4448 case MDefinition::Opcode::DebugEnterGCUnsafeRegion:
4449 case MDefinition::Opcode::DebugLeaveGCUnsafeRegion:
4450 iter++;
4451 break;
4452 default:
4453 return true;
4454 }
4455 }
4456
4457 MOZ_CRASH("Unreachable");
4458 }
4459
4460 bool jit::AddKeepAliveInstructions(MIRGraph& graph) {
4461 for (MBasicBlockIterator i(graph.begin()); i != graph.end(); i++) {
4462 MBasicBlock* block = *i;
4463
4464 for (MInstructionIterator insIter(block->begin()); insIter != block->end();
4465 insIter++) {
4466 MInstruction* ins = *insIter;
4467 if (ins->type() != MIRType::Elements && ins->type() != MIRType::Slots) {
4468 continue;
4469 }
4470
4471 MDefinition* ownerObject;
4472 switch (ins->op()) {
4473 case MDefinition::Opcode::Elements:
4474 case MDefinition::Opcode::ArrayBufferViewElements:
4475 MOZ_ASSERT(ins->numOperands() == 1);
4476 ownerObject = ins->getOperand(0);
4477 break;
4478 case MDefinition::Opcode::Slots:
4479 ownerObject = ins->toSlots()->object();
4480 break;
4481 default:
4482 MOZ_CRASH("Unexpected op");
4483 }
4484
4485 MOZ_ASSERT(ownerObject->type() == MIRType::Object);
4486
4487 if (ownerObject->isConstant()) {
4488 // Constants are kept alive by other pointers, for instance
4489 // ImmGCPtr in JIT code.
4490 continue;
4491 }
4492
4493 for (MUseDefIterator uses(ins); uses; uses++) {
4494 MInstruction* use = uses.def()->toInstruction();
4495
4496 if (use->isStoreElementHole()) {
4497 // StoreElementHole has an explicit object operand. If GVN
4498 // is disabled, we can get different unbox instructions with
4499 // the same object as input, so we check for that case.
4500 MOZ_ASSERT_IF(!use->toStoreElementHole()->object()->isUnbox() &&
4501 !ownerObject->isUnbox(),
4502 use->toStoreElementHole()->object() == ownerObject);
4503 continue;
4504 }
4505
4506 if (!NeedsKeepAlive(ins, use)) {
4507 #ifdef DEBUG
4508 // These two instructions don't start a GC unsafe region, because they
4509 // overwrite their elements register at the very start. This ensures
4510 // there's no invalidated elements value kept on the stack.
4511 if (use->isApplyArray() || use->isConstructArray()) {
4512 continue;
4513 }
4514
4515 if (!graph.alloc().ensureBallast()) {
4516 return false;
4517 }
4518
4519 // Enter a GC unsafe region while the elements/slots are on the stack.
4520 auto* enter = MDebugEnterGCUnsafeRegion::New(graph.alloc());
4521 use->block()->insertAfter(ins, enter);
4522
4523 // Leave the region after the use.
4524 auto* leave = MDebugLeaveGCUnsafeRegion::New(graph.alloc());
4525 use->block()->insertAfter(use, leave);
4526 #endif
4527 continue;
4528 }
4529
4530 if (!graph.alloc().ensureBallast()) {
4531 return false;
4532 }
4533 MKeepAliveObject* keepAlive =
4534 MKeepAliveObject::New(graph.alloc(), ownerObject);
4535 use->block()->insertAfter(use, keepAlive);
4536 }
4537 }
4538 }
4539
4540 return true;
4541 }
4542
4543 bool LinearSum::multiply(int32_t scale) {
4544 for (size_t i = 0; i < terms_.length(); i++) {
4545 if (!SafeMul(scale, terms_[i].scale, &terms_[i].scale)) {
4546 return false;
4547 }
4548 }
4549 return SafeMul(scale, constant_, &constant_);
4550 }
4551
4552 bool LinearSum::divide(uint32_t scale) {
4553 MOZ_ASSERT(scale > 0);
4554
4555 for (size_t i = 0; i < terms_.length(); i++) {
4556 if (terms_[i].scale % scale != 0) {
4557 return false;
4558 }
4559 }
4560 if (constant_ % scale != 0) {
4561 return false;
4562 }
4563
4564 for (size_t i = 0; i < terms_.length(); i++) {
4565 terms_[i].scale /= scale;
4566 }
4567 constant_ /= scale;
4568
4569 return true;
4570 }
4571
4572 bool LinearSum::add(const LinearSum& other, int32_t scale /* = 1 */) {
4573 for (size_t i = 0; i < other.terms_.length(); i++) {
4574 int32_t newScale = scale;
4575 if (!SafeMul(scale, other.terms_[i].scale, &newScale)) {
4576 return false;
4577 }
4578 if (!add(other.terms_[i].term, newScale)) {
4579 return false;
4580 }
4581 }
4582 int32_t newConstant = scale;
4583 if (!SafeMul(scale, other.constant_, &newConstant)) {
4584 return false;
4585 }
4586 return add(newConstant);
4587 }
4588
4589 bool LinearSum::add(SimpleLinearSum other, int32_t scale) {
4590 if (other.term && !add(other.term, scale)) {
4591 return false;
4592 }
4593
4594 int32_t constant;
4595 if (!SafeMul(other.constant, scale, &constant)) {
4596 return false;
4597 }
4598
4599 return add(constant);
4600 }
4601
4602 bool LinearSum::add(MDefinition* term, int32_t scale) {
4603 MOZ_ASSERT(term);
4604
4605 if (scale == 0) {
4606 return true;
4607 }
4608
4609 if (MConstant* termConst = term->maybeConstantValue()) {
4610 int32_t constant = termConst->toInt32();
4611 if (!SafeMul(constant, scale, &constant)) {
4612 return false;
4613 }
4614 return add(constant);
4615 }
4616
4617 for (size_t i = 0; i < terms_.length(); i++) {
4618 if (term == terms_[i].term) {
4619 if (!SafeAdd(scale, terms_[i].scale, &terms_[i].scale)) {
4620 return false;
4621 }
4622 if (terms_[i].scale == 0) {
4623 terms_[i] = terms_.back();
4624 terms_.popBack();
4625 }
4626 return true;
4627 }
4628 }
4629
4630 AutoEnterOOMUnsafeRegion oomUnsafe;
4631 if (!terms_.append(LinearTerm(term, scale))) {
4632 oomUnsafe.crash("LinearSum::add");
4633 }
4634
4635 return true;
4636 }
4637
4638 bool LinearSum::add(int32_t constant) {
4639 return SafeAdd(constant, constant_, &constant_);
4640 }
4641
4642 void LinearSum::dump(GenericPrinter& out) const {
4643 for (size_t i = 0; i < terms_.length(); i++) {
4644 int32_t scale = terms_[i].scale;
4645 int32_t id = terms_[i].term->id();
4646 MOZ_ASSERT(scale);
4647 if (scale > 0) {
4648 if (i) {
4649 out.printf("+");
4650 }
4651 if (scale == 1) {
4652 out.printf("#%d", id);
4653 } else {
4654 out.printf("%d*#%d", scale, id);
4655 }
4656 } else if (scale == -1) {
4657 out.printf("-#%d", id);
4658 } else {
4659 out.printf("%d*#%d", scale, id);
4660 }
4661 }
4662 if (constant_ > 0) {
4663 out.printf("+%d", constant_);
4664 } else if (constant_ < 0) {
4665 out.printf("%d", constant_);
4666 }
4667 }
4668
4669 void LinearSum::dump() const {
4670 Fprinter out(stderr);
4671 dump(out);
4672 out.finish();
4673 }
4674
4675 MDefinition* jit::ConvertLinearSum(TempAllocator& alloc, MBasicBlock* block,
4676 const LinearSum& sum,
4677 BailoutKind bailoutKind) {
4678 MDefinition* def = nullptr;
4679
4680 for (size_t i = 0; i < sum.numTerms(); i++) {
4681 LinearTerm term = sum.term(i);
4682 MOZ_ASSERT(!term.term->isConstant());
4683 if (term.scale == 1) {
4684 if (def) {
4685 def = MAdd::New(alloc, def, term.term, MIRType::Int32);
4686 def->setBailoutKind(bailoutKind);
4687 block->insertAtEnd(def->toInstruction());
4688 def->computeRange(alloc);
4689 } else {
4690 def = term.term;
4691 }
4692 } else if (term.scale == -1) {
4693 if (!def) {
4694 def = MConstant::New(alloc, Int32Value(0));
4695 block->insertAtEnd(def->toInstruction());
4696 def->computeRange(alloc);
4697 }
4698 def = MSub::New(alloc, def, term.term, MIRType::Int32);
4699 def->setBailoutKind(bailoutKind);
4700 block->insertAtEnd(def->toInstruction());
4701 def->computeRange(alloc);
4702 } else {
4703 MOZ_ASSERT(term.scale != 0);
4704 MConstant* factor = MConstant::New(alloc, Int32Value(term.scale));
4705 block->insertAtEnd(factor);
4706 MMul* mul = MMul::New(alloc, term.term, factor, MIRType::Int32);
4707 mul->setBailoutKind(bailoutKind);
4708 block->insertAtEnd(mul);
4709 mul->computeRange(alloc);
4710 if (def) {
4711 def = MAdd::New(alloc, def, mul, MIRType::Int32);
4712 def->setBailoutKind(bailoutKind);
4713 block->insertAtEnd(def->toInstruction());
4714 def->computeRange(alloc);
4715 } else {
4716 def = mul;
4717 }
4718 }
4719 }
4720
4721 if (!def) {
4722 def = MConstant::New(alloc, Int32Value(0));
4723 block->insertAtEnd(def->toInstruction());
4724 def->computeRange(alloc);
4725 }
4726
4727 return def;
4728 }
4729
4730 // Mark all the blocks that are in the loop with the given header.
4731 // Returns the number of blocks marked. Set *canOsr to true if the loop is
4732 // reachable from both the normal entry and the OSR entry.
4733 size_t jit::MarkLoopBlocks(MIRGraph& graph, const MBasicBlock* header,
4734 bool* canOsr) {
4735 #ifdef DEBUG
4736 for (ReversePostorderIterator i = graph.rpoBegin(), e = graph.rpoEnd();
4737 i != e; ++i) {
4738 MOZ_ASSERT(!i->isMarked(), "Some blocks already marked");
4739 }
4740 #endif
4741
4742 MBasicBlock* osrBlock = graph.osrBlock();
4743 *canOsr = false;
4744
4745 // The blocks are in RPO; start at the loop backedge, which marks the bottom
4746 // of the loop, and walk up until we get to the header. Loops may be
4747 // discontiguous, so we trace predecessors to determine which blocks are
4748 // actually part of the loop. The backedge is always part of the loop, and
4749 // so are its predecessors, transitively, up to the loop header or an OSR
4750 // entry.
4751 MBasicBlock* backedge = header->backedge();
4752 backedge->mark();
4753 size_t numMarked = 1;
4754 for (PostorderIterator i = graph.poBegin(backedge);; ++i) {
4755 MOZ_ASSERT(
4756 i != graph.poEnd(),
4757 "Reached the end of the graph while searching for the loop header");
4758 MBasicBlock* block = *i;
4759 // If we've reached the loop header, we're done.
4760 if (block == header) {
4761 break;
4762 }
4763 // A block not marked by the time we reach it is not in the loop.
4764 if (!block->isMarked()) {
4765 continue;
4766 }
4767
4768 // This block is in the loop; trace to its predecessors.
4769 for (size_t p = 0, e = block->numPredecessors(); p != e; ++p) {
4770 MBasicBlock* pred = block->getPredecessor(p);
4771 if (pred->isMarked()) {
4772 continue;
4773 }
4774
4775 // Blocks dominated by the OSR entry are not part of the loop
4776 // (unless they aren't reachable from the normal entry).
4777 if (osrBlock && pred != header && osrBlock->dominates(pred) &&
4778 !osrBlock->dominates(header)) {
4779 *canOsr = true;
4780 continue;
4781 }
4782
4783 MOZ_ASSERT(pred->id() >= header->id() && pred->id() <= backedge->id(),
4784 "Loop block not between loop header and loop backedge");
4785
4786 pred->mark();
4787 ++numMarked;
4788
4789 // A nested loop may not exit back to the enclosing loop at its
4790 // bottom. If we just marked its header, then the whole nested loop
4791 // is part of the enclosing loop.
4792 if (pred->isLoopHeader()) {
4793 MBasicBlock* innerBackedge = pred->backedge();
4794 if (!innerBackedge->isMarked()) {
4795 // Mark its backedge so that we add all of its blocks to the
4796 // outer loop as we walk upwards.
4797 innerBackedge->mark();
4798 ++numMarked;
4799
4800 // If the nested loop is not contiguous, we may have already
4801 // passed its backedge. If this happens, back up.
4802 if (innerBackedge->id() > block->id()) {
4803 i = graph.poBegin(innerBackedge);
4804 --i;
4805 }
4806 }
4807 }
4808 }
4809 }
4810
4811 // If there's no path connecting the header to the backedge, then this isn't
4812 // actually a loop. This can happen when the code starts with a loop but GVN
4813 // folds some branches away.
4814 if (!header->isMarked()) {
4815 jit::UnmarkLoopBlocks(graph, header);
4816 return 0;
4817 }
4818
4819 return numMarked;
4820 }
4821
4822 // Unmark all the blocks that are in the loop with the given header.
4823 void jit::UnmarkLoopBlocks(MIRGraph& graph, const MBasicBlock* header) {
4824 MBasicBlock* backedge = header->backedge();
4825 for (ReversePostorderIterator i = graph.rpoBegin(header);; ++i) {
4826 MOZ_ASSERT(i != graph.rpoEnd(),
4827 "Reached the end of the graph while searching for the backedge");
4828 MBasicBlock* block = *i;
4829 if (block->isMarked()) {
4830 block->unmark();
4831 if (block == backedge) {
4832 break;
4833 }
4834 }
4835 }
4836
4837 #ifdef DEBUG
4838 for (ReversePostorderIterator i = graph.rpoBegin(), e = graph.rpoEnd();
4839 i != e; ++i) {
4840 MOZ_ASSERT(!i->isMarked(), "Not all blocks got unmarked");
4841 }
4842 #endif
4843 }
4844
4845 bool jit::FoldLoadsWithUnbox(const MIRGenerator* mir, MIRGraph& graph) {
4846 // This pass folds MLoadFixedSlot, MLoadDynamicSlot, MLoadElement instructions
4847 // followed by MUnbox into a single instruction. For LoadElement this allows
4848 // us to fuse the hole check with the type check for the unbox.
4849
4850 for (MBasicBlockIterator block(graph.begin()); block != graph.end();
4851 block++) {
4852 if (mir->shouldCancel("FoldLoadsWithUnbox")) {
4853 return false;
4854 }
4855
4856 for (MInstructionIterator insIter(block->begin());
4857 insIter != block->end();) {
4858 MInstruction* ins = *insIter;
4859 insIter++;
4860
4861 // We're only interested in loads producing a Value.
4862 if (!ins->isLoadFixedSlot() && !ins->isLoadDynamicSlot() &&
4863 !ins->isLoadElement()) {
4864 continue;
4865 }
4866 if (ins->type() != MIRType::Value) {
4867 continue;
4868 }
4869
4870 MInstruction* load = ins;
4871
4872 // Ensure there's a single def-use (ignoring resume points) and it's an
4873 // unbox. Unwrap MLexicalCheck because it's redundant if we have a
4874 // fallible unbox (checked below).
4875 MDefinition* defUse = load->maybeSingleDefUse();
4876 if (!defUse) {
4877 continue;
4878 }
4879 MLexicalCheck* lexicalCheck = nullptr;
4880 if (defUse->isLexicalCheck()) {
4881 lexicalCheck = defUse->toLexicalCheck();
4882 defUse = lexicalCheck->maybeSingleDefUse();
4883 if (!defUse) {
4884 continue;
4885 }
4886 }
4887 if (!defUse->isUnbox()) {
4888 continue;
4889 }
4890
4891 // For now require the load and unbox to be in the same block. This isn't
4892 // strictly necessary but it's the common case and could prevent bailouts
4893 // when moving the unbox before a loop.
4894 MUnbox* unbox = defUse->toUnbox();
4895 if (unbox->block() != *block) {
4896 continue;
4897 }
4898 MOZ_ASSERT_IF(lexicalCheck, lexicalCheck->block() == *block);
4899
4900 MOZ_ASSERT(!IsMagicType(unbox->type()));
4901
4902 // If this is a LoadElement or if we have a lexical check between the load
4903 // and unbox, we only support folding the load with a fallible unbox so
4904 // that we can eliminate the MagicValue check.
4905 if ((load->isLoadElement() || lexicalCheck) && !unbox->fallible()) {
4906 continue;
4907 }
4908
4909 // Combine the load and unbox into a single MIR instruction.
4910 if (!graph.alloc().ensureBallast()) {
4911 return false;
4912 }
4913
4914 MIRType type = unbox->type();
4915 MUnbox::Mode mode = unbox->mode();
4916
4917 MInstruction* replacement;
4918 switch (load->op()) {
4919 case MDefinition::Opcode::LoadFixedSlot: {
4920 auto* loadIns = load->toLoadFixedSlot();
4921 replacement = MLoadFixedSlotAndUnbox::New(
4922 graph.alloc(), loadIns->object(), loadIns->slot(), mode, type,
4923 loadIns->usedAsPropertyKey());
4924 break;
4925 }
4926 case MDefinition::Opcode::LoadDynamicSlot: {
4927 auto* loadIns = load->toLoadDynamicSlot();
4928 replacement = MLoadDynamicSlotAndUnbox::New(
4929 graph.alloc(), loadIns->slots(), loadIns->slot(), mode, type,
4930 loadIns->usedAsPropertyKey());
4931 break;
4932 }
4933 case MDefinition::Opcode::LoadElement: {
4934 auto* loadIns = load->toLoadElement();
4935 MOZ_ASSERT(unbox->fallible());
4936 replacement = MLoadElementAndUnbox::New(
4937 graph.alloc(), loadIns->elements(), loadIns->index(), mode, type);
4938 break;
4939 }
4940 default:
4941 MOZ_CRASH("Unexpected instruction");
4942 }
4943 replacement->setBailoutKind(BailoutKind::UnboxFolding);
4944
4945 block->insertBefore(load, replacement);
4946 unbox->replaceAllUsesWith(replacement);
4947 if (lexicalCheck) {
4948 lexicalCheck->replaceAllUsesWith(replacement);
4949 }
4950 load->replaceAllUsesWith(replacement);
4951
4952 if (lexicalCheck && *insIter == lexicalCheck) {
4953 insIter++;
4954 }
4955 if (*insIter == unbox) {
4956 insIter++;
4957 }
4958 block->discard(unbox);
4959 if (lexicalCheck) {
4960 block->discard(lexicalCheck);
4961 }
4962 block->discard(load);
4963 }
4964 }
4965
4966 return true;
4967 }
4968
4969 // Reorder the blocks in the loop starting at the given header to be contiguous.
4970 static void MakeLoopContiguous(MIRGraph& graph, MBasicBlock* header,
4971 size_t numMarked) {
4972 MBasicBlock* backedge = header->backedge();
4973
4974 MOZ_ASSERT(header->isMarked(), "Loop header is not part of loop");
4975 MOZ_ASSERT(backedge->isMarked(), "Loop backedge is not part of loop");
4976
4977 // If there are any blocks between the loop header and the loop backedge
4978 // that are not part of the loop, prepare to move them to the end. We keep
4979 // them in order, which preserves RPO.
4980 ReversePostorderIterator insertIter = graph.rpoBegin(backedge);
4981 insertIter++;
4982 MBasicBlock* insertPt = *insertIter;
4983
4984 // Visit all the blocks from the loop header to the loop backedge.
4985 size_t headerId = header->id();
4986 size_t inLoopId = headerId;
4987 size_t notInLoopId = inLoopId + numMarked;
4988 ReversePostorderIterator i = graph.rpoBegin(header);
4989 for (;;) {
4990 MBasicBlock* block = *i++;
4991 MOZ_ASSERT(block->id() >= header->id() && block->id() <= backedge->id(),
4992 "Loop backedge should be last block in loop");
4993
4994 if (block->isMarked()) {
4995 // This block is in the loop.
4996 block->unmark();
4997 block->setId(inLoopId++);
4998 // If we've reached the loop backedge, we're done!
4999 if (block == backedge) {
5000 break;
5001 }
5002 } else {
5003 // This block is not in the loop. Move it to the end.
5004 graph.moveBlockBefore(insertPt, block);
5005 block->setId(notInLoopId++);
5006 }
5007 }
5008 MOZ_ASSERT(header->id() == headerId, "Loop header id changed");
5009 MOZ_ASSERT(inLoopId == headerId + numMarked,
5010 "Wrong number of blocks kept in loop");
5011 MOZ_ASSERT(notInLoopId == (insertIter != graph.rpoEnd() ? insertPt->id()
5012 : graph.numBlocks()),
5013 "Wrong number of blocks moved out of loop");
5014 }
5015
5016 // Reorder the blocks in the graph so that loops are contiguous.
5017 bool jit::MakeLoopsContiguous(MIRGraph& graph) {
5018 // Visit all loop headers (in any order).
5019 for (MBasicBlockIterator i(graph.begin()); i != graph.end(); i++) {
5020 MBasicBlock* header = *i;
5021 if (!header->isLoopHeader()) {
5022 continue;
5023 }
5024
5025 // Mark all blocks that are actually part of the loop.
5026 bool canOsr;
5027 size_t numMarked = MarkLoopBlocks(graph, header, &canOsr);
5028
5029 // If the loop isn't a loop, don't try to optimize it.
5030 if (numMarked == 0) {
5031 continue;
5032 }
5033
5034 // If there's an OSR block entering the loop in the middle, it's tricky,
5035 // so don't try to handle it, for now.
5036 if (canOsr) {
5037 UnmarkLoopBlocks(graph, header);
5038 continue;
5039 }
5040
5041 // Move all blocks between header and backedge that aren't marked to
5042 // the end of the loop, making the loop itself contiguous.
5043 MakeLoopContiguous(graph, header, numMarked);
5044 }
5045
5046 return true;
5047 }
5048
5049 static MDefinition* SkipUnbox(MDefinition* ins) {
5050 if (ins->isUnbox()) {
5051 return ins->toUnbox()->input();
5052 }
5053 return ins;
5054 }
5055
5056 bool jit::OptimizeIteratorIndices(const MIRGenerator* mir, MIRGraph& graph) {
5057 bool changed = false;
5058
5059 for (ReversePostorderIterator blockIter = graph.rpoBegin();
5060 blockIter != graph.rpoEnd();) {
5061 MBasicBlock* block = *blockIter++;
5062 for (MInstructionIterator insIter(block->begin());
5063 insIter != block->end();) {
5064 MInstruction* ins = *insIter;
5065 insIter++;
5066 if (!graph.alloc().ensureBallast()) {
5067 return false;
5068 }
5069
5070 MDefinition* receiver = nullptr;
5071 MDefinition* idVal = nullptr;
5072 MDefinition* setValue = nullptr;
5073 if (ins->isMegamorphicHasProp() &&
5074 ins->toMegamorphicHasProp()->hasOwn()) {
5075 receiver = ins->toMegamorphicHasProp()->object();
5076 idVal = ins->toMegamorphicHasProp()->idVal();
5077 } else if (ins->isHasOwnCache()) {
5078 receiver = ins->toHasOwnCache()->value();
5079 idVal = ins->toHasOwnCache()->idval();
5080 } else if (ins->isMegamorphicLoadSlotByValue()) {
5081 receiver = ins->toMegamorphicLoadSlotByValue()->object();
5082 idVal = ins->toMegamorphicLoadSlotByValue()->idVal();
5083 } else if (ins->isGetPropertyCache()) {
5084 receiver = ins->toGetPropertyCache()->value();
5085 idVal = ins->toGetPropertyCache()->idval();
5086 } else if (ins->isMegamorphicSetElement()) {
5087 receiver = ins->toMegamorphicSetElement()->object();
5088 idVal = ins->toMegamorphicSetElement()->index();
5089 setValue = ins->toMegamorphicSetElement()->value();
5090 } else if (ins->isSetPropertyCache()) {
5091 receiver = ins->toSetPropertyCache()->object();
5092 idVal = ins->toSetPropertyCache()->idval();
5093 setValue = ins->toSetPropertyCache()->value();
5094 }
5095
5096 if (!receiver) {
5097 continue;
5098 }
5099
5100 // Given the following structure (that occurs inside for-in loops):
5101 // obj: some object
5102 // iter: ObjectToIterator <obj>
5103 // iterNext: IteratorMore <iter>
5104 // access: HasProp/GetElem <obj> <iterNext>
5105 // If the iterator object has an indices array, we can speed up the
5106 // property access:
5107 // 1. If the property access is a HasProp looking for own properties,
5108 // then the result will always be true if the iterator has indices,
5109 // because we only populate the indices array for objects with no
5110 // enumerable properties on the prototype.
5111 // 2. If the property access is a GetProp, then we can use the contents
5112 // of the indices array to find the correct property faster than
5113 // the megamorphic cache.
5114 if (!idVal->isIteratorMore()) {
5115 continue;
5116 }
5117 auto* iterNext = idVal->toIteratorMore();
5118
5119 if (!iterNext->iterator()->isObjectToIterator()) {
5120 continue;
5121 }
5122
5123 MObjectToIterator* iter = iterNext->iterator()->toObjectToIterator();
5124 if (SkipUnbox(iter->object()) != SkipUnbox(receiver)) {
5125 continue;
5126 }
5127
5128 MInstruction* indicesCheck =
5129 MIteratorHasIndices::New(graph.alloc(), iter->object(), iter);
5130 MInstruction* replacement;
5131 if (ins->isHasOwnCache() || ins->isMegamorphicHasProp()) {
5132 MOZ_ASSERT(!setValue);
5133 replacement = MConstant::New(graph.alloc(), BooleanValue(true));
5134 } else if (ins->isMegamorphicLoadSlotByValue() ||
5135 ins->isGetPropertyCache()) {
5136 MOZ_ASSERT(!setValue);
5137 replacement =
5138 MLoadSlotByIteratorIndex::New(graph.alloc(), receiver, iter);
5139 } else {
5140 MOZ_ASSERT(ins->isMegamorphicSetElement() || ins->isSetPropertyCache());
5141 MOZ_ASSERT(setValue);
5142 replacement = MStoreSlotByIteratorIndex::New(graph.alloc(), receiver,
5143 iter, setValue);
5144 }
5145
5146 if (!block->wrapInstructionInFastpath(ins, replacement, indicesCheck)) {
5147 return false;
5148 }
5149
5150 iter->setWantsIndices(true);
5151 changed = true;
5152
5153 // Advance to join block.
5154 blockIter = graph.rpoBegin(block->getSuccessor(0)->getSuccessor(0));
5155 break;
5156 }
5157 }
5158 if (changed && !AccountForCFGChanges(mir, graph,
5159 /*updateAliasAnalysis=*/false)) {
5160 return false;
5161 }
5162
5163 return true;
5164 }
5165
5166 // =====================================================================
5167 //
5168 // Debug printing
5169
5170 void jit::DumpHashedPointer(GenericPrinter& out, const void* p) {
5171 #ifdef JS_JITSPEW
5172 if (!p) {
5173 out.printf("NULL");
5174 return;
5175 }
5176 char tab[27] = "abcdefghijklmnopqrstuvwxyz";
5177 MOZ_ASSERT(tab[26] == '\0');
5178 mozilla::HashNumber hash = mozilla::AddToHash(mozilla::HashNumber(0), p);
5179 hash %= (26 * 26 * 26 * 26 * 26);
5180 char buf[6];
5181 for (int i = 0; i <= 4; i++) {
5182 buf[i] = tab[hash % 26];
5183 hash /= 26;
5184 }
5185 buf[5] = '\0';
5186 out.printf("%s", buf);
5187 #endif
5188 }
5189
5190 void jit::DumpMIRDefinitionID(GenericPrinter& out, const MDefinition* def,
5191 bool showHashedPointers) {
5192 #ifdef JS_JITSPEW
5193 if (!def) {
5194 out.printf("(null)");
5195 return;
5196 }
5197 if (showHashedPointers) {
5198 DumpHashedPointer(out, def);
5199 out.printf(".");
5200 }
5201 out.printf("%u", def->id());
5202 #endif
5203 }
5204
5205 void jit::DumpMIRDefinition(GenericPrinter& out, const MDefinition* def,
5206 bool showHashedPointers) {
5207 #ifdef JS_JITSPEW
5208 DumpMIRDefinitionID(out, def, showHashedPointers);
5209 out.printf(" = %s.", StringFromMIRType(def->type()));
5210 if (def->isConstant()) {
5211 def->printOpcode(out);
5212 } else {
5213 MDefinition::PrintOpcodeName(out, def->op());
5214 }
5215
5216 // Get any extra bits of text that the MIR node wants to show us. Both the
5217 // vector and the strings added to it belong to this function, so both will
5218 // be automatically freed at exit.
5219 ExtrasCollector extras;
5220 def->getExtras(&extras);
5221 for (size_t i = 0; i < extras.count(); i++) {
5222 out.printf(" %s", extras.get(i).get());
5223 }
5224
5225 for (size_t i = 0; i < def->numOperands(); i++) {
5226 out.printf(" ");
5227 DumpMIRDefinitionID(out, def->getOperand(i), showHashedPointers);
5228 }
5229 #endif
5230 }
5231
5232 void jit::DumpMIRBlockID(GenericPrinter& out, const MBasicBlock* block,
5233 bool showHashedPointers) {
5234 #ifdef JS_JITSPEW
5235 if (!block) {
5236 out.printf("Block(null)");
5237 return;
5238 }
5239 out.printf("Block");
5240 if (showHashedPointers) {
5241 out.printf(".");
5242 DumpHashedPointer(out, block);
5243 out.printf(".");
5244 }
5245 out.printf("%u", block->id());
5246 #endif
5247 }
5248
5249 void jit::DumpMIRBlock(GenericPrinter& out, MBasicBlock* block,
5250 bool showHashedPointers) {
5251 #ifdef JS_JITSPEW
5252 out.printf(" ");
5253 DumpMIRBlockID(out, block, showHashedPointers);
5254 out.printf(" -- preds=[");
5255 for (uint32_t i = 0; i < block->numPredecessors(); i++) {
5256 MBasicBlock* pred = block->getPredecessor(i);
5257 out.printf("%s", i == 0 ? "" : ", ");
5258 DumpMIRBlockID(out, pred, showHashedPointers);
5259 }
5260 out.printf("] -- LD=%u -- K=%s -- s-w-phis=", block->loopDepth(),
5261 block->nameOfKind());
5262 if (block->successorWithPhis()) {
5263 DumpMIRBlockID(out, block->successorWithPhis(), showHashedPointers);
5264 out.printf(",#%u\n", block->positionInPhiSuccessor());
5265 } else {
5266 out.printf("(null)\n");
5267 }
5268 for (MPhiIterator iter(block->phisBegin()), end(block->phisEnd());
5269 iter != end; iter++) {
5270 out.printf(" ");
5271 jit::DumpMIRDefinition(out, *iter, showHashedPointers);
5272 out.printf("\n");
5273 }
5274 for (MInstructionIterator iter(block->begin()), end(block->end());
5275 iter != end; iter++) {
5276 out.printf(" ");
5277 DumpMIRDefinition(out, *iter, showHashedPointers);
5278 out.printf("\n");
5279 }
5280 #endif
5281 }
5282
5283 void jit::DumpMIRGraph(GenericPrinter& out, MIRGraph& graph,
5284 bool showHashedPointers) {
5285 #ifdef JS_JITSPEW
5286 for (ReversePostorderIterator block(graph.rpoBegin());
5287 block != graph.rpoEnd(); block++) {
5288 DumpMIRBlock(out, *block, showHashedPointers);
5289 }
5290 #endif
5291 }
5292
5293 void jit::DumpMIRExpressions(GenericPrinter& out, MIRGraph& graph,
5294 const CompileInfo& info, const char* phase,
5295 bool showHashedPointers) {
5296 #ifdef JS_JITSPEW
5297 if (!JitSpewEnabled(JitSpew_MIRExpressions)) {
5298 return;
5299 }
5300
5301 out.printf("===== %s =====\n", phase);
5302
5303 DumpMIRGraph(out, graph, showHashedPointers);
5304
5305 if (info.compilingWasm()) {
5306 out.printf("===== end wasm MIR dump =====\n");
5307 } else {
5308 out.printf("===== %s:%u =====\n", info.filename(), info.lineno());
5309 }
5310 #endif
5311 }