简体   繁体   中英

Javascript deoptimization

I'm not sure what's wrong in this code. Src is a Uint8Array object with a length bigger than 0.

function makeImageFromChannel(src) {
  var image = new Uint8Array(src.length * 4),
      i = 0,
      index = 0,
      value = 0;

  console.log(src.BYTES_PER_ELEMENT)
  console.log(src.map)

  for (i=0; i<src.length; i++) {
    value = src[i]|0;
    image[index]     = value;
    image[index + 1] = value;
    image[index + 2] = value;
    image[index + 3] = 255;
    index += 4;
  }

  return image;
}

var vars = new Uint8Array(23034);
for(var i=0; i<23034; i++) {
  vars[i] = (i % 254) + 1
}
makeImageFromChannel(vars);

Here's what I can read multiple times in the terminal when I run this command node --trace_deopt --allow-natives-syntax script.js .

[deoptimizing: begin 0x36125ec63a21 makeImageFromChannel @13]
  translating makeImageFromChannel => node=59, height=24
    0x7fff5fbfe798: [top + 64] <- 0x3feb15c04121 ; r8 0x3feb15c04121 <undefined>
    0x7fff5fbfe790: [top + 56] <- 0x2bc986d9ffc1 ; rdi 0x2bc986d9ffc1 <an Uint8Array>
    0x7fff5fbfe788: [top + 48] <- 0x2ea32af21c29 ; caller's pc
    0x7fff5fbfe780: [top + 40] <- 0x7fff5fbfe808 ; caller's fp
    0x7fff5fbfe778: [top + 32] <- 0x3feb15c414b1; context
    0x7fff5fbfe770: [top + 24] <- 0x36125ec63a21; function
    0x7fff5fbfe768: [top + 16] <- 0x2bc986c218d1 ; rdx 0x2bc986c218d1 <an Uint8Array>
    0x7fff5fbfe760: [top + 8] <- 135448 ; rbx (smi)
    0x7fff5fbfe758: [top + 0] <- 541792 ; rax (smi)
[deoptimizing: end 0x36125ec63a21 makeImageFromChannel => node=59, pc=0x2ea32af27c70, state=NO_REGISTERS, alignment=no padding, took 0.033 ms]
[removing optimized code for: makeImageFromChannel]

I'm not sure to understand how it found an undefined value in there.

For some reasons, V8 will deoptimized a function that access an array like this:

  for (i=0; i<src.length; i++) {
    value = src[i]|0;
    image[index]     = value;
    image[index + 1] = value;
    image[index + 2] = value;
    image[index + 3] = 255;
    index += 4;
  }

In order to make V8 not deoptimize this function, you can reorder the affectation in reverse order like this:

    image[index + 3] = 255;
    image[index + 2] = value;
    image[index + 1] = value;
    image[index] = value;

And V8 will be happy. This more or less sounds like a bug in the v8 engine than anything else. The engine should be able to detect that reordering these 4 lines doesn't have any effect on the result. Which means that v8 should be able to optimize the function even if the lines were in any order.

It's also unclear how spidermonkey optimize or not those lines.

I'll accept any answer than can explain better why V8 get deoptimized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM