gen-inlining-tests.py 15.4 KB
Newer Older
1
#!/usr/bin/env python
2 3 4 5 6

# Copyright 2016 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

7 8
# for py2/py3 compatibility
from __future__ import print_function
9 10 11 12 13 14 15

from collections import namedtuple
import textwrap
import sys

SHARD_FILENAME_TEMPLATE = "test/mjsunit/compiler/inline-exception-{shard}.js"
# Generates 2 files. Found by trial and error.
16
SHARD_SIZE = 97
17 18 19 20 21 22 23

PREAMBLE = """

// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

24
// Flags: --allow-natives-syntax --no-always-opt
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

// This test file was generated by tools/gen-inlining-tests.py .

// Global variables
var deopt = undefined; // either true or false
var counter = 0;

function resetState() {
  counter = 0;
}

function warmUp(f) {
  try {
    f();
  } catch (ex) {
    // ok
  }
  try {
    f();
  } catch (ex) {
    // ok
  }
}

function resetOptAndAssertResultEquals(expected, f) {
  warmUp(f);
  resetState();
  // %DebugPrint(f);
  eval("'dont optimize this function itself please, but do optimize f'");
  %OptimizeFunctionOnNextCall(f);
  assertEquals(expected, f());
}

function resetOptAndAssertThrowsWith(expected, f) {
  warmUp(f);
  resetState();
  // %DebugPrint(f);
  eval("'dont optimize this function itself please, but do optimize f'");
  %OptimizeFunctionOnNextCall(f);
  try {
    var result = f();
    fail("resetOptAndAssertThrowsWith",
        "exception: " + expected,
        "result: " + result);
  } catch (ex) {
    assertEquals(expected, ex);
  }
}

function increaseAndReturn15() {
  if (deopt) %DeoptimizeFunction(f);
  counter++;
  return 15;
}

function increaseAndThrow42() {
  if (deopt) %DeoptimizeFunction(f);
  counter++;
  throw 42;
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
function increaseAndReturn15_noopt_inner() {
  if (deopt) %DeoptimizeFunction(f);
  counter++;
  return 15;
}

%NeverOptimizeFunction(increaseAndReturn15_noopt_inner);

function increaseAndThrow42_noopt_inner() {
  if (deopt) %DeoptimizeFunction(f);
  counter++;
  throw 42;
}

%NeverOptimizeFunction(increaseAndThrow42_noopt_inner);

// Alternative 1

104 105 106 107 108 109 110 111
function returnOrThrow(doReturn) {
  if (doReturn) {
    return increaseAndReturn15();
  } else {
    return increaseAndThrow42();
  }
}

112 113 114 115 116 117 118 119 120 121 122
// Alternative 2

function increaseAndReturn15_calls_noopt() {
  return increaseAndReturn15_noopt_inner();
}

function increaseAndThrow42_calls_noopt() {
  return increaseAndThrow42_noopt_inner();
}

// Alternative 3.
123 124 125 126 127 128 129 130 131 132 133 134
// When passed either {increaseAndReturn15} or {increaseAndThrow42}, it acts
// as the other one.
function invertFunctionCall(f) {
  var result;
  try {
    result = f();
  } catch (ex) {
    return ex - 27;
  }
  throw result + 27;
}

135
// Alternative 4: constructor
136 137 138 139 140 141 142 143 144 145 146 147 148
function increaseAndStore15Constructor() {
  if (deopt) %DeoptimizeFunction(f);
  ++counter;
  this.x = 15;
}

function increaseAndThrow42Constructor() {
  if (deopt) %DeoptimizeFunction(f);
  ++counter;
  this.x = 42;
  throw this.x;
}

149
// Alternative 5: property
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
var magic = {};
Object.defineProperty(magic, 'prop', {
  get: function () {
    if (deopt) %DeoptimizeFunction(f);
    return 15 + 0 * ++counter;
  },

  set: function(x) {
    // argument should be 37
    if (deopt) %DeoptimizeFunction(f);
    counter -= 36 - x; // increments counter
    throw 42;
  }
})

// Generate type feedback.

167 168 169
assertEquals(15, increaseAndReturn15_calls_noopt());
assertThrowsEquals(function() { return increaseAndThrow42_noopt_inner() }, 42);

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
assertEquals(15, (new increaseAndStore15Constructor()).x);
assertThrowsEquals(function() {
        return (new increaseAndThrow42Constructor()).x;
    },
    42);

function runThisShard() {

""".strip()

def booltuples(n):
  """booltuples(2) yields 4 tuples: (False, False), (False, True),
  (True, False), (True, True)."""

  assert isinstance(n, int)
  if n <= 0:
    yield ()
  else:
    for initial in booltuples(n-1):
      yield initial + (False,)
      yield initial + (True,)

def fnname(flags):
    assert len(FLAGLETTERS) == len(flags)

    return "f_" + ''.join(
          FLAGLETTERS[i] if b else '_'
          for (i, b) in enumerate(flags))

NUM_TESTS_PRINTED = 0
NUM_TESTS_IN_SHARD = 0

def printtest(flags):
  """Print a test case. Takes a couple of boolean flags, on which the
  printed Javascript code depends."""

  assert all(isinstance(flag, bool) for flag in flags)

  # The alternative flags are in reverse order so that if we take all possible
  # tuples, ordered lexicographically from false to true, we get first the
  # default, then alternative 1, then 2, etc.
  (
212 213 214 215 216 217 218 219 220 221 222
    alternativeFn5,      # use alternative #5 for returning/throwing:
                         #   return/throw using property
    alternativeFn4,      # use alternative #4 for returning/throwing:
                         #   return/throw using constructor
    alternativeFn3,      # use alternative #3 for returning/throwing:
                         #   return/throw indirectly, based on function argument
    alternativeFn2,      # use alternative #2 for returning/throwing:
                         #   return/throw indirectly in unoptimized code,
                         #   no branching
    alternativeFn1,      # use alternative #1 for returning/throwing:
                         #   return/throw indirectly, based on boolean arg
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    tryThrows,           # in try block, call throwing function
    tryReturns,          # in try block, call returning function
    tryFirstReturns,     # in try block, returning goes before throwing
    tryResultToLocal,    # in try block, result goes to local variable
    doCatch,             # include catch block
    catchReturns,        # in catch block, return
    catchWithLocal,      # in catch block, modify or return the local variable
    catchThrows,         # in catch block, throw
    doFinally,           # include finally block
    finallyReturns,      # in finally block, return local variable
    finallyThrows,       # in finally block, throw
    endReturnLocal,      # at very end, return variable local
    deopt,               # deopt inside inlined function
  ) = flags

  # BASIC RULES

  # Only one alternative can be applied at any time.
241 242
  if (alternativeFn1 + alternativeFn2 + alternativeFn3 + alternativeFn4
      + alternativeFn5 > 1):
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    return

  # In try, return or throw, or both.
  if not (tryReturns or tryThrows): return

  # Either doCatch or doFinally.
  if not doCatch and not doFinally: return

  # Catch flags only make sense when catching
  if not doCatch and (catchReturns or catchWithLocal or catchThrows):
    return

  # Finally flags only make sense when finallying
  if not doFinally and (finallyReturns or finallyThrows):
    return

  # tryFirstReturns is only relevant when both tryReturns and tryThrows are
  # true.
  if tryFirstReturns and not (tryReturns and tryThrows): return

  # From the try and finally block, we can return or throw, but not both.
  if catchReturns and catchThrows: return
  if finallyReturns and finallyThrows: return

  # If at the end we return the local, we need to have touched it.
  if endReturnLocal and not (tryResultToLocal or catchWithLocal): return

  # PRUNING

  anyAlternative = any([alternativeFn1, alternativeFn2, alternativeFn3,
273 274 275
      alternativeFn4, alternativeFn5])
  specificAlternative = any([alternativeFn2, alternativeFn3])
  rareAlternative = not specificAlternative
276 277 278 279 280 281 282 283

  # If try returns and throws, then don't catchWithLocal, endReturnLocal, or
  # deopt, or do any alternative.
  if (tryReturns and tryThrows and
      (catchWithLocal or endReturnLocal or deopt or anyAlternative)):
    return
  # We don't do any alternative if we do a finally.
  if doFinally and anyAlternative: return
284
  # We only use the local variable if we do alternative #2 or #3.
285
  if ((tryResultToLocal or catchWithLocal or endReturnLocal) and
286
      not specificAlternative):
287 288 289 290
    return
  # We don't need to test deopting into a finally.
  if doFinally and deopt: return

291 292 293 294 295
  # We're only interested in alternative #2 if we have endReturnLocal, no
  # catchReturns, and no catchThrows, and deopt.
  if (alternativeFn2 and
      (not endReturnLocal or catchReturns or catchThrows or not deopt)):
    return
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315


  # Flag check succeeded.

  trueFlagNames = [name for (name, value) in flags._asdict().items() if value]
  flagsMsgLine = "  // Variant flags: [{}]".format(', '.join(trueFlagNames))
  write(textwrap.fill(flagsMsgLine, subsequent_indent='  //   '))
  write("")

  if not anyAlternative:
    fragments = {
      'increaseAndReturn15': 'increaseAndReturn15()',
      'increaseAndThrow42': 'increaseAndThrow42()',
    }
  elif alternativeFn1:
    fragments = {
      'increaseAndReturn15': 'returnOrThrow(true)',
      'increaseAndThrow42': 'returnOrThrow(false)',
    }
  elif alternativeFn2:
316 317 318 319 320
    fragments = {
      'increaseAndReturn15': 'increaseAndReturn15_calls_noopt()',
      'increaseAndThrow42': 'increaseAndThrow42_calls_noopt()',
    }
  elif alternativeFn3:
321 322 323 324
    fragments = {
      'increaseAndReturn15': 'invertFunctionCall(increaseAndThrow42)',
      'increaseAndThrow42': 'invertFunctionCall(increaseAndReturn15)',
    }
325
  elif alternativeFn4:
326 327 328 329 330
    fragments = {
      'increaseAndReturn15': '(new increaseAndStore15Constructor()).x',
      'increaseAndThrow42': '(new increaseAndThrow42Constructor()).x',
    }
  else:
331
    assert alternativeFn5
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    fragments = {
      'increaseAndReturn15': 'magic.prop /* returns 15 */',
      'increaseAndThrow42': '(magic.prop = 37 /* throws 42 */)',
    }

  # As we print code, we also maintain what the result should be. Variable
  # {result} can be one of three things:
  #
  # - None, indicating returning JS null
  # - ("return", n) with n an integer
  # - ("throw", n), with n an integer

  result = None
  # We also maintain what the counter should be at the end.
  # The counter is reset just before f is called.
  counter = 0

  write(    "  f = function {} () {{".format(fnname(flags)))
350
  write(    "    var local = 888;")
351
  write(    "    deopt = {};".format("true" if deopt else "false"))
352
  local = 888
353 354 355 356 357
  write(    "    try {")
  write(    "      counter++;")
  counter += 1
  resultTo = "local +=" if tryResultToLocal else "return"
  if tryReturns and not (tryThrows and not tryFirstReturns):
358
    write(  "      {} 4 + {increaseAndReturn15};".format(resultTo, **fragments))
359 360 361
    if result == None:
      counter += 1
      if tryResultToLocal:
362
        local += 19
363
      else:
364
        result = ("return", 19)
365
  if tryThrows:
366
    write(  "      {} 4 + {increaseAndThrow42};".format(resultTo, **fragments))
367 368 369 370
    if result == None:
      counter += 1
      result = ("throw", 42)
  if tryReturns and tryThrows and not tryFirstReturns:
371
    write(  "      {} 4 + {increaseAndReturn15};".format(resultTo, **fragments))
372 373 374
    if result == None:
      counter += 1
      if tryResultToLocal:
375
        local += 19
376
      else:
377
        result = ("return", 19)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
  write(    "      counter++;")
  if result == None:
    counter += 1

  if doCatch:
    write(  "    } catch (ex) {")
    write(  "      counter++;")
    if isinstance(result, tuple) and result[0] == 'throw':
      counter += 1
    if catchThrows:
      write("      throw 2 + ex;")
      if isinstance(result, tuple) and result[0] == "throw":
        result = ('throw', 2 + result[1])
    elif catchReturns and catchWithLocal:
      write("      return 2 + local;")
      if isinstance(result, tuple) and result[0] == "throw":
        result = ('return', 2 + local)
    elif catchReturns and not catchWithLocal:
      write("      return 2 + ex;");
      if isinstance(result, tuple) and result[0] == "throw":
        result = ('return', 2 + result[1])
    elif catchWithLocal:
      write("      local += ex;");
      if isinstance(result, tuple) and result[0] == "throw":
        local += result[1]
        result = None
        counter += 1
    else:
      if isinstance(result, tuple) and result[0] == "throw":
        result = None
        counter += 1
    write(  "      counter++;")

  if doFinally:
    write(  "    } finally {")
    write(  "      counter++;")
    counter += 1
    if finallyThrows:
      write("      throw 25;")
      result = ('throw', 25)
    elif finallyReturns:
      write("      return 3 + local;")
      result = ('return', 3 + local)
    elif not finallyReturns and not finallyThrows:
      write("      local += 2;")
      local += 2
      counter += 1
    else: assert False # unreachable
    write(  "      counter++;")

  write(    "    }")
  write(    "    counter++;")
  if result == None:
    counter += 1
  if endReturnLocal:
    write(  "    return 5 + local;")
    if result == None:
      result = ('return', 5 + local)
  write(    "  }")

  if result == None:
    write(  "  resetOptAndAssertResultEquals(undefined, f);")
  else:
    tag, value = result
    if tag == "return":
      write(  "  resetOptAndAssertResultEquals({}, f);".format(value))
    else:
      assert tag == "throw"
      write(  "  resetOptAndAssertThrowsWith({}, f);".format(value))

  write(  "  assertEquals({}, counter);".format(counter))
  write(  "")

  global NUM_TESTS_PRINTED, NUM_TESTS_IN_SHARD
  NUM_TESTS_PRINTED += 1
  NUM_TESTS_IN_SHARD += 1

FILE = None # to be initialised to an open file
SHARD_NUM = 1

def write(*args):
  return print(*args, file=FILE)



def rotateshard():
  global FILE, NUM_TESTS_IN_SHARD, SHARD_SIZE
  if MODE != 'shard':
    return
  if FILE != None and NUM_TESTS_IN_SHARD < SHARD_SIZE:
    return
  if FILE != None:
    finishshard()
    assert FILE == None
  FILE = open(SHARD_FILENAME_TEMPLATE.format(shard=SHARD_NUM), 'w')
  write_shard_header()
  NUM_TESTS_IN_SHARD = 0

def finishshard():
  global FILE, SHARD_NUM, MODE
  assert FILE
  write_shard_footer()
  if MODE == 'shard':
    print("Wrote shard {}.".format(SHARD_NUM))
    FILE.close()
    FILE = None
    SHARD_NUM += 1


def write_shard_header():
  if MODE == 'shard':
    write("// Shard {}.".format(SHARD_NUM))
    write("")
  write(PREAMBLE)
  write("")

def write_shard_footer():
  write("}")
  write("%NeverOptimizeFunction(runThisShard);")
  write("")
  write("// {} tests in this shard.".format(NUM_TESTS_IN_SHARD))
  write("// {} tests up to here.".format(NUM_TESTS_PRINTED))
  write("")
  write("runThisShard();")

503
FLAGLETTERS="54321trflcrltfrtld"
504 505

flagtuple = namedtuple('flagtuple', (
506
  "alternativeFn5",
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
  "alternativeFn4",
  "alternativeFn3",
  "alternativeFn2",
  "alternativeFn1",
  "tryThrows",
  "tryReturns",
  "tryFirstReturns",
  "tryResultToLocal",
  "doCatch",
  "catchReturns",
  "catchWithLocal",
  "catchThrows",
  "doFinally",
  "finallyReturns",
  "finallyThrows",
  "endReturnLocal",
  "deopt"
  ))

emptyflags = flagtuple(*((False,) * len(flagtuple._fields)))
f1 = emptyflags._replace(tryReturns=True, doCatch=True)

# You can test function printtest with f1.

allFlagCombinations = [
    flagtuple(*bools)
    for bools in booltuples(len(flagtuple._fields))
]

if __name__ == '__main__':
  global MODE
  if sys.argv[1:] == []:
    MODE = 'stdout'
    print("// Printing all shards together to stdout.")
    print("")
    write_shard_header()
    FILE = sys.stdout
  elif sys.argv[1:] == ['--shard-and-overwrite']:
    MODE = 'shard'
  else:
    print("Usage:")
    print("")
    print("  python {}".format(sys.argv[0]))
    print("      print all tests to standard output")
    print("  python {} --shard-and-overwrite".format(sys.argv[0]))
    print("      print all tests to {}".format(SHARD_FILENAME_TEMPLATE))

    print("")
    print(sys.argv[1:])
    print("")
    sys.exit(1)

  rotateshard()

  for flags in allFlagCombinations:
    printtest(flags)
    rotateshard()

  finishshard()
566 567 568

  if MODE == 'shard':
    print("Total: {} tests.".format(NUM_TESTS_PRINTED))