test-compiler.cc 32.7 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdlib.h>
29
#include <wchar.h>
30

31
#include "src/v8.h"
32

33
#include "src/api-inl.h"
34
#include "src/compilation-cache.h"
35 36
#include "src/compiler.h"
#include "src/disasm.h"
37
#include "src/heap/factory.h"
38
#include "src/interpreter/interpreter.h"
39
#include "src/objects-inl.h"
40
#include "test/cctest/cctest.h"
41

42 43
namespace v8 {
namespace internal {
44

45
static Handle<Object> GetGlobalProperty(const char* name) {
46
  Isolate* isolate = CcTest::i_isolate();
47 48
  return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
      .ToHandleChecked();
49 50 51 52
}


static void SetGlobalProperty(const char* name, Object* value) {
53
  Isolate* isolate = CcTest::i_isolate();
54
  Handle<Object> object(value, isolate);
55 56
  Handle<String> internalized_name =
      isolate->factory()->InternalizeUtf8String(name);
57
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
58
  Runtime::SetObjectProperty(isolate, global, internalized_name, object,
59
                             LanguageMode::kSloppy, StoreOrigin::kMaybeKeyed)
60
      .Check();
61 62 63 64
}


static Handle<JSFunction> Compile(const char* source) {
65
  Isolate* isolate = CcTest::i_isolate();
66 67
  Handle<String> source_code = isolate->factory()->NewStringFromUtf8(
      CStrVector(source)).ToHandleChecked();
68 69
  Handle<SharedFunctionInfo> shared =
      Compiler::GetSharedFunctionInfoForScript(
70 71 72
          isolate, source_code, Compiler::ScriptDetails(),
          v8::ScriptOriginOptions(), nullptr, nullptr,
          v8::ScriptCompiler::kNoCompileOptions,
73
          ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE)
74
          .ToHandleChecked();
75
  return isolate->factory()->NewFunctionFromSharedFunctionInfo(
76
      shared, isolate->native_context());
77 78 79
}


80
static double Inc(Isolate* isolate, int x) {
81
  const char* source = "result = %d + 1;";
82
  EmbeddedVector<char, 512> buffer;
83
  SNPrintF(buffer, source, x);
84

85
  Handle<JSFunction> fun = Compile(buffer.start());
86 87
  if (fun.is_null()) return -1;

88
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
89
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
90
  return GetGlobalProperty("result")->Number();
91 92 93 94
}


TEST(Inc) {
95 96
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
97
  CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
98 99 100
}


101
static double Add(Isolate* isolate, int x, int y) {
102 103 104 105 106
  Handle<JSFunction> fun = Compile("result = x + y;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
  SetGlobalProperty("y", Smi::FromInt(y));
107
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
108
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
109
  return GetGlobalProperty("result")->Number();
110 111 112 113
}


TEST(Add) {
114 115
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
116
  CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
117 118 119
}


120
static double Abs(Isolate* isolate, int x) {
121 122 123 124
  Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
125
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
126
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
127
  return GetGlobalProperty("result")->Number();
128 129 130 131
}


TEST(Abs) {
132 133
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
134
  CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
135 136 137
}


138
static double Sum(Isolate* isolate, int n) {
139 140 141 142 143
  Handle<JSFunction> fun =
      Compile("s = 0; while (n > 0) { s += n; n -= 1; }; result = s;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("n", Smi::FromInt(n));
144
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
145
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
146
  return GetGlobalProperty("result")->Number();
147 148 149 150
}


TEST(Sum) {
151 152
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
153
  CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
154 155 156 157
}


TEST(Print) {
158
  v8::HandleScope scope(CcTest::isolate());
159 160
  v8::Local<v8::Context> context = CcTest::NewContext(PRINT_EXTENSION);
  v8::Context::Scope context_scope(context);
161 162 163
  const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
  Handle<JSFunction> fun = Compile(source);
  if (fun.is_null()) return;
164 165
  Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
                          fun->GetIsolate());
166
  Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
167 168 169 170 171 172
}


// The following test method stems from my coding efforts today. It
// tests all the functionality I have added to the compiler today
TEST(Stuff) {
173 174
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  const char* source =
    "r = 0;\n"
    "a = new Object;\n"
    "if (a == a) r+=1;\n"  // 1
    "if (a != new Object()) r+=2;\n"  // 2
    "a.x = 42;\n"
    "if (a.x == 42) r+=4;\n"  // 4
    "function foo() { var x = 87; return x; }\n"
    "if (foo() == 87) r+=8;\n"  // 8
    "function bar() { var x; x = 99; return x; }\n"
    "if (bar() == 99) r+=16;\n"  // 16
    "function baz() { var x = 1, y, z = 2; y = 3; return x + y + z; }\n"
    "if (baz() == 6) r+=32;\n"  // 32
    "function Cons0() { this.x = 42; this.y = 87; }\n"
    "if (new Cons0().x == 42) r+=64;\n"  // 64
    "if (new Cons0().y == 87) r+=128;\n"  // 128
    "function Cons2(x, y) { this.sum = x + y; }\n"
    "if (new Cons2(3,4).sum == 7) r+=256;";  // 256

  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
196 197
  Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
                          fun->GetIsolate());
198
  Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
199
  CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
200 201 202 203
}


TEST(UncaughtThrow) {
204 205
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
206 207 208 209

  const char* source = "throw 42;";
  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
210
  Isolate* isolate = fun->GetIsolate();
211
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
212
  CHECK(Execution::Call(isolate, fun, global, 0, nullptr).is_null());
213
  CHECK_EQ(42.0, isolate->pending_exception()->Number());
214 215 216 217 218 219 220 221 222 223
}


// Tests calling a builtin function from C/C++ code, and the builtin function
// performs GC. It creates a stack frame looks like following:
//   | C (PerformGC) |
//   |   JS-to-C     |
//   |      JS       |
//   |   C-to-JS     |
TEST(C2JSFrames) {
224
  FLAG_expose_gc = true;
225
  v8::HandleScope scope(CcTest::isolate());
226 227 228
  v8::Local<v8::Context> context =
    CcTest::NewContext(PRINT_EXTENSION | GC_EXTENSION);
  v8::Context::Scope context_scope(context);
229 230 231 232 233

  const char* source = "function foo(a) { gc(), print(a); }";

  Handle<JSFunction> fun0 = Compile(source);
  CHECK(!fun0.is_null());
234
  Isolate* isolate = fun0->GetIsolate();
235 236

  // Run the generated code to populate the global object with 'foo'.
237
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
238
  Execution::Call(isolate, fun0, global, 0, nullptr).Check();
239

240 241 242
  Handle<Object> fun1 =
      JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
          .ToHandleChecked();
243 244
  CHECK(fun1->IsJSFunction());

245 246
  Handle<Object> argv[] = {isolate->factory()->InternalizeOneByteString(
      STATIC_CHAR_VECTOR("hello"))};
247 248
  Execution::Call(isolate,
                  Handle<JSFunction>::cast(fun1),
249
                  global,
250
                  arraysize(argv),
251
                  argv).Check();
252
}
253 254 255 256 257


// Regression 236. Calling InitLineEnds on a Script with undefined
// source resulted in crash.
TEST(Regression236) {
258
  CcTest::InitializeVM();
259
  Isolate* isolate = CcTest::i_isolate();
260
  Factory* factory = isolate->factory();
261
  v8::HandleScope scope(CcTest::isolate());
262

263
  Handle<Script> script = factory->NewScript(factory->empty_string());
264
  script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
265 266 267
  CHECK_EQ(-1, Script::GetLineNumber(script, 0));
  CHECK_EQ(-1, Script::GetLineNumber(script, 100));
  CHECK_EQ(-1, Script::GetLineNumber(script, -1));
268
}
269 270 271


TEST(GetScriptLineNumber) {
272
  LocalContext context;
273
  v8::HandleScope scope(CcTest::isolate());
274
  v8::ScriptOrigin origin = v8::ScriptOrigin(v8_str("test"));
275 276 277 278 279 280 281 282 283 284
  const char function_f[] = "function f() {}";
  const int max_rows = 1000;
  const int buffer_size = max_rows + sizeof(function_f);
  ScopedVector<char> buffer(buffer_size);
  memset(buffer.start(), '\n', buffer_size - 1);
  buffer[buffer_size - 1] = '\0';

  for (int i = 0; i < max_rows; ++i) {
    if (i > 0)
      buffer[i - 1] = '\n';
285
    MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
286 287 288 289 290 291 292
    v8::Local<v8::String> script_body = v8_str(buffer.start());
    v8::Script::Compile(context.local(), script_body, &origin)
        .ToLocalChecked()
        ->Run(context.local())
        .ToLocalChecked();
    v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
        context->Global()->Get(context.local(), v8_str("f")).ToLocalChecked());
293 294 295
    CHECK_EQ(i, f->GetScriptLineNumber());
  }
}
296 297


298
TEST(FeedbackVectorPreservedAcrossRecompiles) {
299
  if (i::FLAG_always_opt || !i::FLAG_opt) return;
300 301
  i::FLAG_allow_natives_syntax = true;
  CcTest::InitializeVM();
Mythri's avatar
Mythri committed
302
  if (!CcTest::i_isolate()->use_optimizer()) return;
303
  v8::HandleScope scope(CcTest::isolate());
304
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
305 306 307 308 309 310

  // Make sure function f has a call that uses a type feedback slot.
  CompileRun("function fun() {};"
             "fun1 = fun;"
             "function f(a) { a(); } f(fun1);");

311 312 313
  Handle<JSFunction> f = Handle<JSFunction>::cast(
      v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
          CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));
314 315

  // Verify that we gathered feedback.
316
  Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
317
  CHECK(!feedback_vector->is_empty());
318
  FeedbackSlot slot_for_a(0);
319
  MaybeObject object = feedback_vector->Get(slot_for_a);
320 321
  {
    HeapObject* heap_object;
322
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
323 324
    CHECK(heap_object->IsJSFunction());
  }
325 326 327 328 329 330

  CompileRun("%OptimizeFunctionOnNextCall(f); f(fun1);");

  // Verify that the feedback is still "gathered" despite a recompilation
  // of the full code.
  CHECK(f->IsOptimized());
331
  object = f->feedback_vector()->Get(slot_for_a);
332 333
  {
    HeapObject* heap_object;
334
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
335 336
    CHECK(heap_object->IsJSFunction());
  }
337 338 339 340
}


TEST(FeedbackVectorUnaffectedByScopeChanges) {
341
  if (i::FLAG_always_opt || !i::FLAG_lazy) {
342 343
    return;
  }
344 345
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
346
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
347 348 349 350 351 352 353 354 355 356 357 358 359

  CompileRun("function builder() {"
             "  call_target = function() { return 3; };"
             "  return (function() {"
             "    eval('');"
             "    return function() {"
             "      'use strict';"
             "      call_target();"
             "    }"
             "  })();"
             "}"
             "morphing_call = builder();");

360 361 362 363
  Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
      *v8::Local<v8::Function>::Cast(CcTest::global()
                                         ->Get(context, v8_str("morphing_call"))
                                         .ToLocalChecked())));
364

365 366
  // If we are compiling lazily then it should not be compiled, and so no
  // feedback vector allocated yet.
367 368 369 370
  CHECK(!f->shared()->is_compiled());

  CompileRun("morphing_call();");

371 372
  // Now a feedback vector is allocated.
  CHECK(f->shared()->is_compiled());
373
  CHECK(!f->feedback_vector()->is_empty());
374 375
}

376
// Test that optimized code for different closures is actually shared.
377
TEST(OptimizedCodeSharing1) {
378
  FLAG_stress_compaction = false;
379
  FLAG_allow_natives_syntax = true;
380 381
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
382
  for (int i = 0; i < 3; i++) {
383
    LocalContext env;
384 385 386
    env->Global()
        ->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
        .FromJust();
387 388 389 390 391
    CompileRun(
        "function MakeClosure() {"
        "  return function() { return x; };"
        "}"
        "var closure0 = MakeClosure();"
392 393
        "var closure1 = MakeClosure();"  // We only share optimized code
                                         // if there are at least two closures.
394 395 396
        "%DebugPrint(closure0());"
        "%OptimizeFunctionOnNextCall(closure0);"
        "%DebugPrint(closure0());"
397
        "closure1();"
398
        "var closure2 = MakeClosure(); closure2();");
399 400
    Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
401 402 403
            env->Global()
                ->Get(env.local(), v8_str("closure1"))
                .ToLocalChecked())));
404 405
    Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
406 407 408
            env->Global()
                ->Get(env.local(), v8_str("closure2"))
                .ToLocalChecked())));
Mythri's avatar
Mythri committed
409 410
    CHECK(fun1->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
    CHECK(fun2->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
411 412 413 414
    CHECK_EQ(fun1->code(), fun2->code());
  }
}

415
TEST(CompileFunctionInContext) {
416
  if (i::FLAG_always_opt) return;
417 418 419 420
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var r = 10;");
421 422
  v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
423 424 425 426
  v8::ScriptCompiler::Source script_source(v8_str(
      "a = PI * r * r;"
      "x = r * cos(PI);"
      "y = r * sin(PI / 2);"));
427 428
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
429
                                                   0, nullptr, 1, &math)
430
          .ToLocalChecked();
431
  CHECK(!fun.IsEmpty());
432 433

  i::DisallowCompilation no_compile(CcTest::i_isolate());
434
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
435 436 437
  CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
  v8::Local<v8::Value> a =
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
438
  CHECK(a->IsNumber());
439 440 441
  CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
  v8::Local<v8::Value> x =
      env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
442
  CHECK(x->IsNumber());
443 444 445
  CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
  v8::Local<v8::Value> y =
      env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
446
  CHECK(y->IsNumber());
447 448 449
  CHECK_EQ(314.1592653589793, a->NumberValue(env.local()).FromJust());
  CHECK_EQ(-10.0, x->NumberValue(env.local()).FromJust());
  CHECK_EQ(10.0, y->NumberValue(env.local()).FromJust());
450 451 452 453 454 455 456 457 458 459 460 461 462 463
}


TEST(CompileFunctionInContextComplex) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun(
      "var x = 1;"
      "var y = 2;"
      "var z = 4;"
      "var a = {x: 8, y: 16};"
      "var b = {x: 32};");
  v8::Local<v8::Object> ext[2];
464 465 466 467
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
  ext[1] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("b")).ToLocalChecked());
468
  v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
469 470
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
471
                                                   0, nullptr, 2, ext)
472
          .ToLocalChecked();
473
  CHECK(!fun.IsEmpty());
474
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
475 476 477
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
478
  CHECK(result->IsNumber());
479
  CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
480 481 482
}


483 484 485 486 487 488
TEST(CompileFunctionInContextArgs) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23};");
  v8::Local<v8::Object> ext[1];
489 490
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
491 492
  v8::ScriptCompiler::Source script_source(v8_str("result = x + b"));
  v8::Local<v8::String> arg = v8_str("b");
493 494 495 496
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   1, &arg, 1, ext)
          .ToLocalChecked();
497 498 499 500 501
  CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
                  .ToLocalChecked()
                  ->ToInt32(env.local())
                  .ToLocalChecked()
                  ->Value());
502
  v8::Local<v8::Value> b_value = v8::Number::New(CcTest::isolate(), 42.0);
503 504 505 506
  fun->Call(env.local(), env->Global(), 1, &b_value).ToLocalChecked();
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
507
  CHECK(result->IsNumber());
508
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
509 510 511 512 513 514 515 516 517
}


TEST(CompileFunctionInContextComments) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23, y: 1, z: 2};");
  v8::Local<v8::Object> ext[1];
518 519
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
520 521 522
  v8::ScriptCompiler::Source script_source(
      v8_str("result = /* y + */ x + b // + z"));
  v8::Local<v8::String> arg = v8_str("b");
523 524 525 526
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   1, &arg, 1, ext)
          .ToLocalChecked();
527 528
  CHECK(!fun.IsEmpty());
  v8::Local<v8::Value> b_value = v8::Number::New(CcTest::isolate(), 42.0);
529 530 531 532
  fun->Call(env.local(), env->Global(), 1, &b_value).ToLocalChecked();
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
533
  CHECK(result->IsNumber());
534
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
535 536 537 538 539 540 541 542 543
}


TEST(CompileFunctionInContextNonIdentifierArgs) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  v8::ScriptCompiler::Source script_source(v8_str("result = 1"));
  v8::Local<v8::String> arg = v8_str("b }");
544
  CHECK(v8::ScriptCompiler::CompileFunctionInContext(
545
            env.local(), &script_source, 1, &arg, 0, nullptr)
546
            .IsEmpty());
547 548
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
TEST(CompileFunctionInContextRenderCallSite) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  static const char* source1 =
      "try {"
      "  var a = [];"
      "  a[0]();"
      "} catch (e) {"
      "  return e.toString();"
      "}";
  static const char* expect1 = "TypeError: a[0] is not a function";
  static const char* source2 =
      "try {"
      "  (function() {"
      "    var a = [];"
      "    a[0]();"
      "  })()"
      "} catch (e) {"
      "  return e.toString();"
      "}";
  static const char* expect2 = "TypeError: a[0] is not a function";
  {
    v8::ScriptCompiler::Source script_source(v8_str(source1));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .ToLocalChecked();
    CHECK(!fun.IsEmpty());
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect1))
              .FromJust());
  }
  {
    v8::ScriptCompiler::Source script_source(v8_str(source2));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .ToLocalChecked();
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect2))
              .FromJust());
  }
}

TEST(CompileFunctionInContextQuirks) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  {
    static const char* source =
        "[x, y] = ['ab', 'cd'];"
        "return x + y";
    static const char* expect = "abcd";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .ToLocalChecked();
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect))
              .FromJust());
  }
  {
    static const char* source = "'use strict'; var a = 077";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::TryCatch try_catch(CcTest::isolate());
    CHECK(v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr)
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
  {
    static const char* source = "{ let x; { var x } }";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::TryCatch try_catch(CcTest::isolate());
    CHECK(v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr)
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
}
640

641 642 643 644 645 646 647 648
TEST(CompileFunctionInContextScriptOrigin) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  v8::ScriptOrigin origin(v8_str("test"),
                          v8::Integer::New(CcTest::isolate(), 22),
                          v8::Integer::New(CcTest::isolate(), 41));
  v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
649 650
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
651
                                                   0, nullptr, 0, nullptr)
652
          .ToLocalChecked();
653
  CHECK(!fun.IsEmpty());
654
  v8::TryCatch try_catch(CcTest::isolate());
655
  CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
656
  CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
657 658 659 660 661
  CHECK(try_catch.HasCaught());
  CHECK(!try_catch.Exception().IsEmpty());
  v8::Local<v8::StackTrace> stack =
      v8::Exception::GetStackTrace(try_catch.Exception());
  CHECK(!stack.IsEmpty());
662
  CHECK_GT(stack->GetFrameCount(), 0);
663
  v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
664 665 666 667
  CHECK_EQ(23, frame->GetLineNumber());
  CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
}

668
void TestCompileFunctionInContextToStringImpl() {
669 670 671 672 673 674
#define CHECK_NOT_CAUGHT(__local_context__, try_catch, __op__)                \
  do {                                                                        \
    const char* op = (__op__);                                                \
    v8::Local<v8::Context> context = (__local_context__);                     \
    if (try_catch.HasCaught()) {                                              \
      v8::String::Utf8Value error(                                            \
675
          CcTest::isolate(),                                                  \
676 677 678 679
          try_catch.Exception()->ToString(context).ToLocalChecked());         \
      V8_Fatal(__FILE__, __LINE__,                                            \
               "Unexpected exception thrown during %s:\n\t%s\n", op, *error); \
    }                                                                         \
680
  } while (false)
681

682
  {  // NOLINT
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
    CcTest::InitializeVM();
    v8::HandleScope scope(CcTest::isolate());
    LocalContext env;

    // Regression test for v8:6190
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(22), v8_int(41));
      v8::ScriptCompiler::Source script_source(v8_str("return event"), origin);

      v8::Local<v8::String> params[] = {v8_str("event")};
      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, arraysize(params), params, 0,
              nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());
      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
708 709
          "function (event) {\n"
          "return event\n"
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
    }

    // With no parameters:
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());
      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
733 734
          "function () {\n"
          "return 0\n"
735 736
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    }

    // With a name:
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());

      fun->SetName(v8_str("onclick"));

      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
          "function onclick() {\n"
          "return 0\n"
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
765 766 767 768
    }
  }
#undef CHECK_NOT_CAUGHT
}
769

770 771 772 773
TEST(CompileFunctionInContextFunctionToString) {
  TestCompileFunctionInContextToStringImpl();
}

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
TEST(InvocationCount) {
  FLAG_allow_natives_syntax = true;
  FLAG_always_opt = false;
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());

  CompileRun(
      "function bar() {};"
      "function foo() { return bar(); };"
      "foo();");
  Handle<JSFunction> foo = Handle<JSFunction>::cast(GetGlobalProperty("foo"));
  CHECK_EQ(1, foo->feedback_vector()->invocation_count());
  CompileRun("foo()");
  CHECK_EQ(2, foo->feedback_vector()->invocation_count());
  CompileRun("bar()");
  CHECK_EQ(2, foo->feedback_vector()->invocation_count());
  CompileRun("foo(); foo()");
  CHECK_EQ(4, foo->feedback_vector()->invocation_count());
}
793

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
TEST(ShallowEagerCompilation) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f(x) {"
      "  return x + x;"
      "}"
      "f(2)");
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(env.local(), &script_source,
                                  v8::ScriptCompiler::kEagerCompile)
          .ToLocalChecked();
  {
    v8::internal::DisallowCompilation no_compile_expected(isolate);
    v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
    CHECK_EQ(4, result->Int32Value(env.local()).FromJust());
  }
}

TEST(DeepEagerCompilation) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f(x) {"
      "  function g(x) {"
      "    function h(x) {"
      "      return x ** x;"
      "    }"
      "    return h(x) * h(x);"
      "  }"
      "  return g(x) + g(x);"
      "}"
      "f(2)");
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(env.local(), &script_source,
                                  v8::ScriptCompiler::kEagerCompile)
          .ToLocalChecked();
  {
    v8::internal::DisallowCompilation no_compile_expected(isolate);
    v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
    CHECK_EQ(32, result->Int32Value(env.local()).FromJust());
  }
}

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
TEST(DeepEagerCompilationPeakMemory) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f() {"
      "  function g1() {"
      "    function h1() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "    function h2() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "  }"
      "  function g2() {"
      "    function h1() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "    function h2() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "  }"
      "}");
  v8::ScriptCompiler::Source script_source(source);
  CcTest::i_isolate()->compilation_cache()->Disable();

  v8::HeapStatistics heap_statistics;
  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_1 = heap_statistics.peak_malloced_memory();
  printf("peak memory after init:          %8zu\n", peak_mem_1);

  v8::ScriptCompiler::Compile(env.local(), &script_source,
                              v8::ScriptCompiler::kNoCompileOptions)
      .ToLocalChecked();

  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_2 = heap_statistics.peak_malloced_memory();
  printf("peak memory after lazy compile:  %8zu\n", peak_mem_2);

  v8::ScriptCompiler::Compile(env.local(), &script_source,
                              v8::ScriptCompiler::kNoCompileOptions)
      .ToLocalChecked();

  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_3 = heap_statistics.peak_malloced_memory();
  printf("peak memory after lazy compile:  %8zu\n", peak_mem_3);

  v8::ScriptCompiler::Compile(env.local(), &script_source,
                              v8::ScriptCompiler::kEagerCompile)
      .ToLocalChecked();

  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_4 = heap_statistics.peak_malloced_memory();
  printf("peak memory after eager compile: %8zu\n", peak_mem_4);

  CHECK_LE(peak_mem_1, peak_mem_2);
  CHECK_EQ(peak_mem_2, peak_mem_3);
  CHECK_LE(peak_mem_3, peak_mem_4);
909
  // Check that eager compilation does not cause significantly higher (+100%)
910
  // peak memory than lazy compilation.
911
  CHECK_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
912 913
}

914 915
}  // namespace internal
}  // namespace v8