LCOV - code coverage report
Current view: top level - test/cctest - test-compiler.cc (source / functions) Hit Total Coverage
Test: app.info Lines: 462 462 100.0 %
Date: 2019-01-20 Functions: 38 38 100.0 %

          Line data    Source code
       1             : // Copyright 2012 the V8 project authors. All rights reserved.
       2             : // Redistribution and use in source and binary forms, with or without
       3             : // modification, are permitted provided that the following conditions are
       4             : // met:
       5             : //
       6             : //     * Redistributions of source code must retain the above copyright
       7             : //       notice, this list of conditions and the following disclaimer.
       8             : //     * Redistributions in binary form must reproduce the above
       9             : //       copyright notice, this list of conditions and the following
      10             : //       disclaimer in the documentation and/or other materials provided
      11             : //       with the distribution.
      12             : //     * Neither the name of Google Inc. nor the names of its
      13             : //       contributors may be used to endorse or promote products derived
      14             : //       from this software without specific prior written permission.
      15             : //
      16             : // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      17             : // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      18             : // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      19             : // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      20             : // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      21             : // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      22             : // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      23             : // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      24             : // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      25             : // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      26             : // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      27             : 
      28             : #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             : #include "src/compiler.h"
      36             : #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             : namespace v8 {
      43             : namespace internal {
      44             : 
      45          30 : static Handle<Object> GetGlobalProperty(const char* name) {
      46             :   Isolate* isolate = CcTest::i_isolate();
      47          60 :   return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
      48          90 :       .ToHandleChecked();
      49             : }
      50             : 
      51          20 : static void SetGlobalProperty(const char* name, Object value) {
      52             :   Isolate* isolate = CcTest::i_isolate();
      53             :   Handle<Object> object(value, isolate);
      54             :   Handle<String> internalized_name =
      55          20 :       isolate->factory()->InternalizeUtf8String(name);
      56          40 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
      57             :   Runtime::SetObjectProperty(isolate, global, internalized_name, object,
      58          20 :                              LanguageMode::kSloppy, StoreOrigin::kMaybeKeyed)
      59          40 :       .Check();
      60          20 : }
      61             : 
      62          40 : static Handle<JSFunction> Compile(const char* source) {
      63             :   Isolate* isolate = CcTest::i_isolate();
      64             :   Handle<String> source_code = isolate->factory()->NewStringFromUtf8(
      65          80 :       CStrVector(source)).ToHandleChecked();
      66             :   Handle<SharedFunctionInfo> shared =
      67             :       Compiler::GetSharedFunctionInfoForScript(
      68             :           isolate, source_code, Compiler::ScriptDetails(),
      69             :           v8::ScriptOriginOptions(), nullptr, nullptr,
      70             :           v8::ScriptCompiler::kNoCompileOptions,
      71          40 :           ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE)
      72          80 :           .ToHandleChecked();
      73             :   return isolate->factory()->NewFunctionFromSharedFunctionInfo(
      74          80 :       shared, isolate->native_context());
      75             : }
      76             : 
      77             : 
      78           5 : static double Inc(Isolate* isolate, int x) {
      79             :   const char* source = "result = %d + 1;";
      80             :   EmbeddedVector<char, 512> buffer;
      81           5 :   SNPrintF(buffer, source, x);
      82             : 
      83           5 :   Handle<JSFunction> fun = Compile(buffer.start());
      84           5 :   if (fun.is_null()) return -1;
      85             : 
      86          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
      87          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
      88          10 :   return GetGlobalProperty("result")->Number();
      89             : }
      90             : 
      91             : 
      92       28342 : TEST(Inc) {
      93           5 :   CcTest::InitializeVM();
      94           5 :   v8::HandleScope scope(CcTest::isolate());
      95           5 :   CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
      96           5 : }
      97             : 
      98             : 
      99           5 : static double Add(Isolate* isolate, int x, int y) {
     100           5 :   Handle<JSFunction> fun = Compile("result = x + y;");
     101           5 :   if (fun.is_null()) return -1;
     102             : 
     103           5 :   SetGlobalProperty("x", Smi::FromInt(x));
     104           5 :   SetGlobalProperty("y", Smi::FromInt(y));
     105          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     106          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
     107          10 :   return GetGlobalProperty("result")->Number();
     108             : }
     109             : 
     110             : 
     111       28342 : TEST(Add) {
     112           5 :   CcTest::InitializeVM();
     113           5 :   v8::HandleScope scope(CcTest::isolate());
     114           5 :   CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
     115           5 : }
     116             : 
     117             : 
     118           5 : static double Abs(Isolate* isolate, int x) {
     119           5 :   Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
     120           5 :   if (fun.is_null()) return -1;
     121             : 
     122           5 :   SetGlobalProperty("x", Smi::FromInt(x));
     123          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     124          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
     125          10 :   return GetGlobalProperty("result")->Number();
     126             : }
     127             : 
     128             : 
     129       28342 : TEST(Abs) {
     130           5 :   CcTest::InitializeVM();
     131           5 :   v8::HandleScope scope(CcTest::isolate());
     132           5 :   CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
     133           5 : }
     134             : 
     135             : 
     136           5 : static double Sum(Isolate* isolate, int n) {
     137             :   Handle<JSFunction> fun =
     138           5 :       Compile("s = 0; while (n > 0) { s += n; n -= 1; }; result = s;");
     139           5 :   if (fun.is_null()) return -1;
     140             : 
     141           5 :   SetGlobalProperty("n", Smi::FromInt(n));
     142          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     143          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
     144          10 :   return GetGlobalProperty("result")->Number();
     145             : }
     146             : 
     147             : 
     148       28342 : TEST(Sum) {
     149           5 :   CcTest::InitializeVM();
     150           5 :   v8::HandleScope scope(CcTest::isolate());
     151           5 :   CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
     152           5 : }
     153             : 
     154             : 
     155       28342 : TEST(Print) {
     156           5 :   v8::HandleScope scope(CcTest::isolate());
     157          10 :   v8::Local<v8::Context> context = CcTest::NewContext({PRINT_EXTENSION_ID});
     158             :   v8::Context::Scope context_scope(context);
     159             :   const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
     160           5 :   Handle<JSFunction> fun = Compile(source);
     161          10 :   if (fun.is_null()) return;
     162          10 :   Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
     163          10 :                           fun->GetIsolate());
     164          15 :   Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
     165             : }
     166             : 
     167             : 
     168             : // The following test method stems from my coding efforts today. It
     169             : // tests all the functionality I have added to the compiler today
     170       28342 : TEST(Stuff) {
     171           5 :   CcTest::InitializeVM();
     172           5 :   v8::HandleScope scope(CcTest::isolate());
     173             :   const char* source =
     174             :     "r = 0;\n"
     175             :     "a = new Object;\n"
     176             :     "if (a == a) r+=1;\n"  // 1
     177             :     "if (a != new Object()) r+=2;\n"  // 2
     178             :     "a.x = 42;\n"
     179             :     "if (a.x == 42) r+=4;\n"  // 4
     180             :     "function foo() { var x = 87; return x; }\n"
     181             :     "if (foo() == 87) r+=8;\n"  // 8
     182             :     "function bar() { var x; x = 99; return x; }\n"
     183             :     "if (bar() == 99) r+=16;\n"  // 16
     184             :     "function baz() { var x = 1, y, z = 2; y = 3; return x + y + z; }\n"
     185             :     "if (baz() == 6) r+=32;\n"  // 32
     186             :     "function Cons0() { this.x = 42; this.y = 87; }\n"
     187             :     "if (new Cons0().x == 42) r+=64;\n"  // 64
     188             :     "if (new Cons0().y == 87) r+=128;\n"  // 128
     189             :     "function Cons2(x, y) { this.sum = x + y; }\n"
     190             :     "if (new Cons2(3,4).sum == 7) r+=256;";  // 256
     191             : 
     192           5 :   Handle<JSFunction> fun = Compile(source);
     193           5 :   CHECK(!fun.is_null());
     194          10 :   Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
     195          10 :                           fun->GetIsolate());
     196          10 :   Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
     197          10 :   CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
     198           5 : }
     199             : 
     200             : 
     201       28342 : TEST(UncaughtThrow) {
     202           5 :   CcTest::InitializeVM();
     203           5 :   v8::HandleScope scope(CcTest::isolate());
     204             : 
     205             :   const char* source = "throw 42;";
     206           5 :   Handle<JSFunction> fun = Compile(source);
     207           5 :   CHECK(!fun.is_null());
     208             :   Isolate* isolate = fun->GetIsolate();
     209          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     210          10 :   CHECK(Execution::Call(isolate, fun, global, 0, nullptr).is_null());
     211           5 :   CHECK_EQ(42.0, isolate->pending_exception()->Number());
     212           5 : }
     213             : 
     214             : 
     215             : // Tests calling a builtin function from C/C++ code, and the builtin function
     216             : // performs GC. It creates a stack frame looks like following:
     217             : //   | C (PerformGC) |
     218             : //   |   JS-to-C     |
     219             : //   |      JS       |
     220             : //   |   C-to-JS     |
     221       28342 : TEST(C2JSFrames) {
     222           5 :   FLAG_expose_gc = true;
     223           5 :   v8::HandleScope scope(CcTest::isolate());
     224             :   v8::Local<v8::Context> context =
     225          10 :       CcTest::NewContext({PRINT_EXTENSION_ID, GC_EXTENSION_ID});
     226             :   v8::Context::Scope context_scope(context);
     227             : 
     228             :   const char* source = "function foo(a) { gc(), print(a); }";
     229             : 
     230           5 :   Handle<JSFunction> fun0 = Compile(source);
     231           5 :   CHECK(!fun0.is_null());
     232             :   Isolate* isolate = fun0->GetIsolate();
     233             : 
     234             :   // Run the generated code to populate the global object with 'foo'.
     235          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     236          10 :   Execution::Call(isolate, fun0, global, 0, nullptr).Check();
     237             : 
     238             :   Handle<Object> fun1 =
     239          10 :       JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
     240          10 :           .ToHandleChecked();
     241          10 :   CHECK(fun1->IsJSFunction());
     242             : 
     243             :   Handle<Object> argv[] = {
     244           5 :       isolate->factory()->InternalizeOneByteString(StaticCharVector("hello"))};
     245             :   Execution::Call(isolate,
     246             :                   Handle<JSFunction>::cast(fun1),
     247             :                   global,
     248             :                   arraysize(argv),
     249          20 :                   argv).Check();
     250           5 : }
     251             : 
     252             : 
     253             : // Regression 236. Calling InitLineEnds on a Script with undefined
     254             : // source resulted in crash.
     255       28342 : TEST(Regression236) {
     256           5 :   CcTest::InitializeVM();
     257             :   Isolate* isolate = CcTest::i_isolate();
     258             :   Factory* factory = isolate->factory();
     259           5 :   v8::HandleScope scope(CcTest::isolate());
     260             : 
     261           5 :   Handle<Script> script = factory->NewScript(factory->empty_string());
     262          15 :   script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
     263           5 :   CHECK_EQ(-1, Script::GetLineNumber(script, 0));
     264           5 :   CHECK_EQ(-1, Script::GetLineNumber(script, 100));
     265           5 :   CHECK_EQ(-1, Script::GetLineNumber(script, -1));
     266           5 : }
     267             : 
     268             : 
     269       28342 : TEST(GetScriptLineNumber) {
     270           5 :   LocalContext context;
     271          10 :   v8::HandleScope scope(CcTest::isolate());
     272           5 :   v8::ScriptOrigin origin = v8::ScriptOrigin(v8_str("test"));
     273           5 :   const char function_f[] = "function f() {}";
     274             :   const int max_rows = 1000;
     275             :   const int buffer_size = max_rows + sizeof(function_f);
     276             :   ScopedVector<char> buffer(buffer_size);
     277             :   memset(buffer.start(), '\n', buffer_size - 1);
     278           5 :   buffer[buffer_size - 1] = '\0';
     279             : 
     280        5005 :   for (int i = 0; i < max_rows; ++i) {
     281        5000 :     if (i > 0)
     282        9990 :       buffer[i - 1] = '\n';
     283        5000 :     MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
     284        5000 :     v8::Local<v8::String> script_body = v8_str(buffer.start());
     285        5000 :     v8::Script::Compile(context.local(), script_body, &origin)
     286        5000 :         .ToLocalChecked()
     287        5000 :         ->Run(context.local())
     288        5000 :         .ToLocalChecked();
     289             :     v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
     290       25000 :         context->Global()->Get(context.local(), v8_str("f")).ToLocalChecked());
     291        5000 :     CHECK_EQ(i, f->GetScriptLineNumber());
     292           5 :   }
     293           5 : }
     294             : 
     295             : 
     296       28342 : TEST(FeedbackVectorPreservedAcrossRecompiles) {
     297           7 :   if (i::FLAG_always_opt || !i::FLAG_opt) return;
     298           3 :   i::FLAG_allow_natives_syntax = true;
     299           3 :   CcTest::InitializeVM();
     300           3 :   if (!CcTest::i_isolate()->use_optimizer()) return;
     301           3 :   v8::HandleScope scope(CcTest::isolate());
     302           3 :   v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
     303             : 
     304             :   // Make sure function f has a call that uses a type feedback slot.
     305             :   CompileRun("function fun() {};"
     306             :              "fun1 = fun;"
     307             :              "function f(a) { a(); } f(fun1);");
     308             : 
     309             :   Handle<JSFunction> f = Handle<JSFunction>::cast(
     310             :       v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
     311          12 :           CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));
     312             : 
     313             :   // Verify that we gathered feedback.
     314           6 :   Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
     315           3 :   CHECK(!feedback_vector->is_empty());
     316             :   FeedbackSlot slot_for_a(0);
     317           6 :   MaybeObject object = feedback_vector->Get(slot_for_a);
     318             :   {
     319           3 :     HeapObject heap_object;
     320           3 :     CHECK(object->GetHeapObjectIfWeak(&heap_object));
     321           3 :     CHECK(heap_object->IsJSFunction());
     322             :   }
     323             : 
     324             :   CompileRun("%OptimizeFunctionOnNextCall(f); f(fun1);");
     325             : 
     326             :   // Verify that the feedback is still "gathered" despite a recompilation
     327             :   // of the full code.
     328           3 :   CHECK(f->IsOptimized());
     329           6 :   object = f->feedback_vector()->Get(slot_for_a);
     330             :   {
     331           3 :     HeapObject heap_object;
     332           3 :     CHECK(object->GetHeapObjectIfWeak(&heap_object));
     333           3 :     CHECK(heap_object->IsJSFunction());
     334           3 :   }
     335             : }
     336             : 
     337             : 
     338       28342 : TEST(FeedbackVectorUnaffectedByScopeChanges) {
     339           5 :   if (i::FLAG_always_opt || !i::FLAG_lazy || i::FLAG_lite_mode) {
     340           1 :     return;
     341             :   }
     342           4 :   CcTest::InitializeVM();
     343           4 :   v8::HandleScope scope(CcTest::isolate());
     344           4 :   v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
     345             : 
     346             :   CompileRun("function builder() {"
     347             :              "  call_target = function() { return 3; };"
     348             :              "  return (function() {"
     349             :              "    eval('');"
     350             :              "    return function() {"
     351             :              "      'use strict';"
     352             :              "      call_target();"
     353             :              "    }"
     354             :              "  })();"
     355             :              "}"
     356             :              "morphing_call = builder();");
     357             : 
     358             :   Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
     359             :       *v8::Local<v8::Function>::Cast(CcTest::global()
     360          12 :                                          ->Get(context, v8_str("morphing_call"))
     361           8 :                                          .ToLocalChecked())));
     362             : 
     363             :   // If we are compiling lazily then it should not be compiled, and so no
     364             :   // feedback vector allocated yet.
     365           4 :   CHECK(!f->shared()->is_compiled());
     366             : 
     367             :   CompileRun("morphing_call();");
     368             : 
     369             :   // Now a feedback vector is allocated.
     370           4 :   CHECK(f->shared()->is_compiled());
     371           8 :   CHECK(!f->feedback_vector()->is_empty());
     372             : }
     373             : 
     374             : // Test that optimized code for different closures is actually shared.
     375       28342 : TEST(OptimizedCodeSharing1) {
     376           5 :   FLAG_stress_compaction = false;
     377           5 :   FLAG_allow_natives_syntax = true;
     378           5 :   CcTest::InitializeVM();
     379           5 :   v8::HandleScope scope(CcTest::isolate());
     380          20 :   for (int i = 0; i < 3; i++) {
     381          15 :     LocalContext env;
     382             :     env->Global()
     383          75 :         ->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
     384          30 :         .FromJust();
     385             :     CompileRun(
     386             :         "function MakeClosure() {"
     387             :         "  return function() { return x; };"
     388             :         "}"
     389             :         "var closure0 = MakeClosure();"
     390             :         "var closure1 = MakeClosure();"  // We only share optimized code
     391             :                                          // if there are at least two closures.
     392             :         "%DebugPrint(closure0());"
     393             :         "%OptimizeFunctionOnNextCall(closure0);"
     394             :         "%DebugPrint(closure0());"
     395             :         "closure1();"
     396             :         "var closure2 = MakeClosure(); closure2();");
     397             :     Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
     398             :         v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
     399             :             env->Global()
     400          60 :                 ->Get(env.local(), v8_str("closure1"))
     401          30 :                 .ToLocalChecked())));
     402             :     Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
     403             :         v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
     404             :             env->Global()
     405          60 :                 ->Get(env.local(), v8_str("closure2"))
     406          30 :                 .ToLocalChecked())));
     407          18 :     CHECK(fun1->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
     408          18 :     CHECK(fun2->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
     409          45 :     CHECK_EQ(fun1->code(), fun2->code());
     410          20 :   }
     411           5 : }
     412             : 
     413       28342 : TEST(CompileFunctionInContext) {
     414           6 :   if (i::FLAG_always_opt) return;
     415           4 :   CcTest::InitializeVM();
     416           4 :   v8::HandleScope scope(CcTest::isolate());
     417           8 :   LocalContext env;
     418             :   CompileRun("var r = 10;");
     419             :   v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
     420          20 :       env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
     421             :   v8::ScriptCompiler::Source script_source(v8_str(
     422             :       "a = PI * r * r;"
     423             :       "x = r * cos(PI);"
     424           4 :       "y = r * sin(PI / 2);"));
     425             :   v8::Local<v8::Function> fun =
     426             :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     427           4 :                                                    0, nullptr, 1, &math)
     428           4 :           .ToLocalChecked();
     429           4 :   CHECK(!fun.IsEmpty());
     430             : 
     431             :   i::DisallowCompilation no_compile(CcTest::i_isolate());
     432          12 :   fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     433          20 :   CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
     434             :   v8::Local<v8::Value> a =
     435          20 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
     436           4 :   CHECK(a->IsNumber());
     437          20 :   CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
     438             :   v8::Local<v8::Value> x =
     439          20 :       env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
     440           4 :   CHECK(x->IsNumber());
     441          20 :   CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
     442             :   v8::Local<v8::Value> y =
     443          20 :       env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
     444           4 :   CHECK(y->IsNumber());
     445           8 :   CHECK_EQ(314.1592653589793, a->NumberValue(env.local()).FromJust());
     446           8 :   CHECK_EQ(-10.0, x->NumberValue(env.local()).FromJust());
     447          12 :   CHECK_EQ(10.0, y->NumberValue(env.local()).FromJust());
     448             : }
     449             : 
     450             : 
     451       28342 : TEST(CompileFunctionInContextComplex) {
     452           5 :   CcTest::InitializeVM();
     453           5 :   v8::HandleScope scope(CcTest::isolate());
     454          10 :   LocalContext env;
     455             :   CompileRun(
     456             :       "var x = 1;"
     457             :       "var y = 2;"
     458             :       "var z = 4;"
     459             :       "var a = {x: 8, y: 16};"
     460             :       "var b = {x: 32};");
     461          15 :   v8::Local<v8::Object> ext[2];
     462             :   ext[0] = v8::Local<v8::Object>::Cast(
     463          25 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
     464             :   ext[1] = v8::Local<v8::Object>::Cast(
     465          25 :       env->Global()->Get(env.local(), v8_str("b")).ToLocalChecked());
     466           5 :   v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
     467             :   v8::Local<v8::Function> fun =
     468             :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     469           5 :                                                    0, nullptr, 2, ext)
     470           5 :           .ToLocalChecked();
     471           5 :   CHECK(!fun.IsEmpty());
     472          15 :   fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     473          25 :   CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
     474             :   v8::Local<v8::Value> result =
     475          25 :       env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
     476           5 :   CHECK(result->IsNumber());
     477          15 :   CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
     478           5 : }
     479             : 
     480             : 
     481       28342 : TEST(CompileFunctionInContextArgs) {
     482           5 :   CcTest::InitializeVM();
     483           5 :   v8::HandleScope scope(CcTest::isolate());
     484          10 :   LocalContext env;
     485             :   CompileRun("var a = {x: 23};");
     486          10 :   v8::Local<v8::Object> ext[1];
     487             :   ext[0] = v8::Local<v8::Object>::Cast(
     488          25 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
     489           5 :   v8::ScriptCompiler::Source script_source(v8_str("result = x + abc"));
     490           5 :   v8::Local<v8::String> arg = v8_str("abc");
     491             :   v8::Local<v8::Function> fun =
     492             :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     493           5 :                                                    1, &arg, 1, ext)
     494           5 :           .ToLocalChecked();
     495          20 :   CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
     496             :                   .ToLocalChecked()
     497             :                   ->ToInt32(env.local())
     498             :                   .ToLocalChecked()
     499             :                   ->Value());
     500           5 :   v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
     501          15 :   fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
     502          25 :   CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
     503             :   v8::Local<v8::Value> result =
     504          25 :       env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
     505           5 :   CHECK(result->IsNumber());
     506          15 :   CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
     507           5 : }
     508             : 
     509             : 
     510       28342 : TEST(CompileFunctionInContextComments) {
     511           5 :   CcTest::InitializeVM();
     512           5 :   v8::HandleScope scope(CcTest::isolate());
     513          10 :   LocalContext env;
     514             :   CompileRun("var a = {x: 23, y: 1, z: 2};");
     515          10 :   v8::Local<v8::Object> ext[1];
     516             :   ext[0] = v8::Local<v8::Object>::Cast(
     517          25 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
     518             :   v8::Local<v8::String> source =
     519             :       CompileRun("'result = /* y + */ x + a\\u4e00 // + z'").As<v8::String>();
     520             :   v8::ScriptCompiler::Source script_source(source);
     521           5 :   v8::Local<v8::String> arg = CompileRun("'a\\u4e00'").As<v8::String>();
     522             :   v8::Local<v8::Function> fun =
     523             :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     524           5 :                                                    1, &arg, 1, ext)
     525           5 :           .ToLocalChecked();
     526           5 :   CHECK(!fun.IsEmpty());
     527           5 :   v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
     528          15 :   fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
     529          25 :   CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
     530             :   v8::Local<v8::Value> result =
     531          25 :       env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
     532           5 :   CHECK(result->IsNumber());
     533          15 :   CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
     534           5 : }
     535             : 
     536             : 
     537       28342 : TEST(CompileFunctionInContextNonIdentifierArgs) {
     538           5 :   CcTest::InitializeVM();
     539           5 :   v8::HandleScope scope(CcTest::isolate());
     540          10 :   LocalContext env;
     541           5 :   v8::ScriptCompiler::Source script_source(v8_str("result = 1"));
     542           5 :   v8::Local<v8::String> arg = v8_str("b }");
     543          10 :   CHECK(v8::ScriptCompiler::CompileFunctionInContext(
     544             :             env.local(), &script_source, 1, &arg, 0, nullptr)
     545           5 :             .IsEmpty());
     546           5 : }
     547             : 
     548       28342 : TEST(CompileFunctionInContextRenderCallSite) {
     549           5 :   CcTest::InitializeVM();
     550           5 :   v8::HandleScope scope(CcTest::isolate());
     551          10 :   LocalContext env;
     552             :   static const char* source1 =
     553             :       "try {"
     554             :       "  var a = [];"
     555             :       "  a[0]();"
     556             :       "} catch (e) {"
     557             :       "  return e.toString();"
     558             :       "}";
     559             :   static const char* expect1 = "TypeError: a[0] is not a function";
     560             :   static const char* source2 =
     561             :       "try {"
     562             :       "  (function() {"
     563             :       "    var a = [];"
     564             :       "    a[0]();"
     565             :       "  })()"
     566             :       "} catch (e) {"
     567             :       "  return e.toString();"
     568             :       "}";
     569             :   static const char* expect2 = "TypeError: a[0] is not a function";
     570             :   {
     571           5 :     v8::ScriptCompiler::Source script_source(v8_str(source1));
     572             :     v8::Local<v8::Function> fun =
     573             :         v8::ScriptCompiler::CompileFunctionInContext(
     574           5 :             env.local(), &script_source, 0, nullptr, 0, nullptr)
     575           5 :             .ToLocalChecked();
     576           5 :     CHECK(!fun.IsEmpty());
     577             :     v8::Local<v8::Value> result =
     578          15 :         fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     579           5 :     CHECK(result->IsString());
     580          15 :     CHECK(v8::Local<v8::String>::Cast(result)
     581             :               ->Equals(env.local(), v8_str(expect1))
     582             :               .FromJust());
     583             :   }
     584             :   {
     585           5 :     v8::ScriptCompiler::Source script_source(v8_str(source2));
     586             :     v8::Local<v8::Function> fun =
     587             :         v8::ScriptCompiler::CompileFunctionInContext(
     588           5 :             env.local(), &script_source, 0, nullptr, 0, nullptr)
     589           5 :             .ToLocalChecked();
     590             :     v8::Local<v8::Value> result =
     591          15 :         fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     592           5 :     CHECK(result->IsString());
     593          15 :     CHECK(v8::Local<v8::String>::Cast(result)
     594             :               ->Equals(env.local(), v8_str(expect2))
     595             :               .FromJust());
     596           5 :   }
     597           5 : }
     598             : 
     599       28342 : TEST(CompileFunctionInContextQuirks) {
     600           5 :   CcTest::InitializeVM();
     601           5 :   v8::HandleScope scope(CcTest::isolate());
     602          10 :   LocalContext env;
     603             :   {
     604             :     static const char* source =
     605             :         "[x, y] = ['ab', 'cd'];"
     606             :         "return x + y";
     607             :     static const char* expect = "abcd";
     608           5 :     v8::ScriptCompiler::Source script_source(v8_str(source));
     609             :     v8::Local<v8::Function> fun =
     610             :         v8::ScriptCompiler::CompileFunctionInContext(
     611           5 :             env.local(), &script_source, 0, nullptr, 0, nullptr)
     612           5 :             .ToLocalChecked();
     613             :     v8::Local<v8::Value> result =
     614          15 :         fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     615           5 :     CHECK(result->IsString());
     616          15 :     CHECK(v8::Local<v8::String>::Cast(result)
     617             :               ->Equals(env.local(), v8_str(expect))
     618             :               .FromJust());
     619             :   }
     620             :   {
     621             :     static const char* source = "'use strict'; var a = 077";
     622           5 :     v8::ScriptCompiler::Source script_source(v8_str(source));
     623          10 :     v8::TryCatch try_catch(CcTest::isolate());
     624          10 :     CHECK(v8::ScriptCompiler::CompileFunctionInContext(
     625             :               env.local(), &script_source, 0, nullptr, 0, nullptr)
     626             :               .IsEmpty());
     627           5 :     CHECK(try_catch.HasCaught());
     628             :   }
     629             :   {
     630             :     static const char* source = "{ let x; { var x } }";
     631           5 :     v8::ScriptCompiler::Source script_source(v8_str(source));
     632          10 :     v8::TryCatch try_catch(CcTest::isolate());
     633          10 :     CHECK(v8::ScriptCompiler::CompileFunctionInContext(
     634             :               env.local(), &script_source, 0, nullptr, 0, nullptr)
     635             :               .IsEmpty());
     636           5 :     CHECK(try_catch.HasCaught());
     637           5 :   }
     638           5 : }
     639             : 
     640       28342 : TEST(CompileFunctionInContextScriptOrigin) {
     641           5 :   CcTest::InitializeVM();
     642           5 :   v8::HandleScope scope(CcTest::isolate());
     643          10 :   LocalContext env;
     644             :   v8::ScriptOrigin origin(v8_str("test"),
     645             :                           v8::Integer::New(CcTest::isolate(), 22),
     646           5 :                           v8::Integer::New(CcTest::isolate(), 41));
     647           5 :   v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
     648             :   v8::Local<v8::Function> fun =
     649             :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     650           5 :                                                    0, nullptr, 0, nullptr)
     651           5 :           .ToLocalChecked();
     652           5 :   CHECK(!fun.IsEmpty());
     653          10 :   v8::TryCatch try_catch(CcTest::isolate());
     654           5 :   CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
     655          15 :   CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
     656           5 :   CHECK(try_catch.HasCaught());
     657          10 :   CHECK(!try_catch.Exception().IsEmpty());
     658             :   v8::Local<v8::StackTrace> stack =
     659           5 :       v8::Exception::GetStackTrace(try_catch.Exception());
     660           5 :   CHECK(!stack.IsEmpty());
     661           5 :   CHECK_GT(stack->GetFrameCount(), 0);
     662           5 :   v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
     663           5 :   CHECK_EQ(23, frame->GetLineNumber());
     664          10 :   CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
     665           5 : }
     666             : 
     667           5 : void TestCompileFunctionInContextToStringImpl() {
     668             : #define CHECK_NOT_CAUGHT(__local_context__, try_catch, __op__)                \
     669             :   do {                                                                        \
     670             :     const char* op = (__op__);                                                \
     671             :     v8::Local<v8::Context> context = (__local_context__);                     \
     672             :     if (try_catch.HasCaught()) {                                              \
     673             :       v8::String::Utf8Value error(                                            \
     674             :           CcTest::isolate(),                                                  \
     675             :           try_catch.Exception()->ToString(context).ToLocalChecked());         \
     676             :       V8_Fatal(__FILE__, __LINE__,                                            \
     677             :                "Unexpected exception thrown during %s:\n\t%s\n", op, *error); \
     678             :     }                                                                         \
     679             :   } while (false)
     680             : 
     681             :   {  // NOLINT
     682           5 :     CcTest::InitializeVM();
     683           5 :     v8::HandleScope scope(CcTest::isolate());
     684          10 :     LocalContext env;
     685             : 
     686             :     // Regression test for v8:6190
     687             :     {
     688           5 :       v8::ScriptOrigin origin(v8_str("test"), v8_int(22), v8_int(41));
     689           5 :       v8::ScriptCompiler::Source script_source(v8_str("return event"), origin);
     690             : 
     691           5 :       v8::Local<v8::String> params[] = {v8_str("event")};
     692          10 :       v8::TryCatch try_catch(CcTest::isolate());
     693             :       v8::MaybeLocal<v8::Function> maybe_fun =
     694             :           v8::ScriptCompiler::CompileFunctionInContext(
     695             :               env.local(), &script_source, arraysize(params), params, 0,
     696           5 :               nullptr);
     697             : 
     698           5 :       CHECK_NOT_CAUGHT(env.local(), try_catch,
     699             :                        "v8::ScriptCompiler::CompileFunctionInContext");
     700             : 
     701             :       v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
     702           5 :       CHECK(!fun.IsEmpty());
     703           5 :       CHECK(!try_catch.HasCaught());
     704             :       v8::Local<v8::String> result =
     705           5 :           fun->ToString(env.local()).ToLocalChecked();
     706             :       v8::Local<v8::String> expected = v8_str(
     707             :           "function (event) {\n"
     708             :           "return event\n"
     709           5 :           "}");
     710          15 :       CHECK(expected->Equals(env.local(), result).FromJust());
     711             :     }
     712             : 
     713             :     // With no parameters:
     714             :     {
     715           5 :       v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
     716           5 :       v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);
     717             : 
     718          10 :       v8::TryCatch try_catch(CcTest::isolate());
     719             :       v8::MaybeLocal<v8::Function> maybe_fun =
     720             :           v8::ScriptCompiler::CompileFunctionInContext(
     721           5 :               env.local(), &script_source, 0, nullptr, 0, nullptr);
     722             : 
     723           5 :       CHECK_NOT_CAUGHT(env.local(), try_catch,
     724             :                        "v8::ScriptCompiler::CompileFunctionInContext");
     725             : 
     726             :       v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
     727           5 :       CHECK(!fun.IsEmpty());
     728           5 :       CHECK(!try_catch.HasCaught());
     729             :       v8::Local<v8::String> result =
     730           5 :           fun->ToString(env.local()).ToLocalChecked();
     731             :       v8::Local<v8::String> expected = v8_str(
     732             :           "function () {\n"
     733             :           "return 0\n"
     734           5 :           "}");
     735          15 :       CHECK(expected->Equals(env.local(), result).FromJust());
     736             :     }
     737             : 
     738             :     // With a name:
     739             :     {
     740           5 :       v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
     741           5 :       v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);
     742             : 
     743          10 :       v8::TryCatch try_catch(CcTest::isolate());
     744             :       v8::MaybeLocal<v8::Function> maybe_fun =
     745             :           v8::ScriptCompiler::CompileFunctionInContext(
     746           5 :               env.local(), &script_source, 0, nullptr, 0, nullptr);
     747             : 
     748           5 :       CHECK_NOT_CAUGHT(env.local(), try_catch,
     749             :                        "v8::ScriptCompiler::CompileFunctionInContext");
     750             : 
     751             :       v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
     752           5 :       CHECK(!fun.IsEmpty());
     753           5 :       CHECK(!try_catch.HasCaught());
     754             : 
     755           5 :       fun->SetName(v8_str("onclick"));
     756             : 
     757             :       v8::Local<v8::String> result =
     758           5 :           fun->ToString(env.local()).ToLocalChecked();
     759             :       v8::Local<v8::String> expected = v8_str(
     760             :           "function onclick() {\n"
     761             :           "return 0\n"
     762           5 :           "}");
     763          15 :       CHECK(expected->Equals(env.local(), result).FromJust());
     764           5 :     }
     765             :   }
     766             : #undef CHECK_NOT_CAUGHT
     767           5 : }
     768             : 
     769       28342 : TEST(CompileFunctionInContextFunctionToString) {
     770           5 :   TestCompileFunctionInContextToStringImpl();
     771           5 : }
     772             : 
     773       28342 : TEST(InvocationCount) {
     774           5 :   if (FLAG_lite_mode) return;
     775           5 :   FLAG_allow_natives_syntax = true;
     776           5 :   FLAG_always_opt = false;
     777           5 :   CcTest::InitializeVM();
     778           5 :   v8::HandleScope scope(CcTest::isolate());
     779             : 
     780             :   CompileRun(
     781             :       "function bar() {};"
     782             :       "function foo() { return bar(); };"
     783             :       "foo();");
     784           5 :   Handle<JSFunction> foo = Handle<JSFunction>::cast(GetGlobalProperty("foo"));
     785          10 :   CHECK_EQ(1, foo->feedback_vector()->invocation_count());
     786             :   CompileRun("foo()");
     787          10 :   CHECK_EQ(2, foo->feedback_vector()->invocation_count());
     788             :   CompileRun("bar()");
     789          10 :   CHECK_EQ(2, foo->feedback_vector()->invocation_count());
     790             :   CompileRun("foo(); foo()");
     791          10 :   CHECK_EQ(4, foo->feedback_vector()->invocation_count());
     792             : }
     793             : 
     794       28342 : TEST(ShallowEagerCompilation) {
     795           5 :   i::FLAG_always_opt = false;
     796           5 :   CcTest::InitializeVM();
     797           5 :   LocalContext env;
     798             :   i::Isolate* isolate = CcTest::i_isolate();
     799          10 :   v8::HandleScope scope(CcTest::isolate());
     800             :   v8::Local<v8::String> source = v8_str(
     801             :       "function f(x) {"
     802             :       "  return x + x;"
     803             :       "}"
     804           5 :       "f(2)");
     805             :   v8::ScriptCompiler::Source script_source(source);
     806             :   v8::Local<v8::Script> script =
     807             :       v8::ScriptCompiler::Compile(env.local(), &script_source,
     808           5 :                                   v8::ScriptCompiler::kEagerCompile)
     809           5 :           .ToLocalChecked();
     810             :   {
     811             :     v8::internal::DisallowCompilation no_compile_expected(isolate);
     812           5 :     v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
     813          10 :     CHECK_EQ(4, result->Int32Value(env.local()).FromJust());
     814           5 :   }
     815           5 : }
     816             : 
     817       28342 : TEST(DeepEagerCompilation) {
     818           5 :   i::FLAG_always_opt = false;
     819           5 :   CcTest::InitializeVM();
     820           5 :   LocalContext env;
     821             :   i::Isolate* isolate = CcTest::i_isolate();
     822          10 :   v8::HandleScope scope(CcTest::isolate());
     823             :   v8::Local<v8::String> source = v8_str(
     824             :       "function f(x) {"
     825             :       "  function g(x) {"
     826             :       "    function h(x) {"
     827             :       "      return x ** x;"
     828             :       "    }"
     829             :       "    return h(x) * h(x);"
     830             :       "  }"
     831             :       "  return g(x) + g(x);"
     832             :       "}"
     833           5 :       "f(2)");
     834             :   v8::ScriptCompiler::Source script_source(source);
     835             :   v8::Local<v8::Script> script =
     836             :       v8::ScriptCompiler::Compile(env.local(), &script_source,
     837           5 :                                   v8::ScriptCompiler::kEagerCompile)
     838           5 :           .ToLocalChecked();
     839             :   {
     840             :     v8::internal::DisallowCompilation no_compile_expected(isolate);
     841           5 :     v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
     842          10 :     CHECK_EQ(32, result->Int32Value(env.local()).FromJust());
     843           5 :   }
     844           5 : }
     845             : 
     846       28342 : TEST(DeepEagerCompilationPeakMemory) {
     847           5 :   i::FLAG_always_opt = false;
     848           5 :   CcTest::InitializeVM();
     849           5 :   LocalContext env;
     850          10 :   v8::HandleScope scope(CcTest::isolate());
     851             :   v8::Local<v8::String> source = v8_str(
     852             :       "function f() {"
     853             :       "  function g1() {"
     854             :       "    function h1() {"
     855             :       "      function i1() {}"
     856             :       "      function i2() {}"
     857             :       "    }"
     858             :       "    function h2() {"
     859             :       "      function i1() {}"
     860             :       "      function i2() {}"
     861             :       "    }"
     862             :       "  }"
     863             :       "  function g2() {"
     864             :       "    function h1() {"
     865             :       "      function i1() {}"
     866             :       "      function i2() {}"
     867             :       "    }"
     868             :       "    function h2() {"
     869             :       "      function i1() {}"
     870             :       "      function i2() {}"
     871             :       "    }"
     872             :       "  }"
     873           5 :       "}");
     874             :   v8::ScriptCompiler::Source script_source(source);
     875           5 :   CcTest::i_isolate()->compilation_cache()->Disable();
     876             : 
     877           5 :   v8::HeapStatistics heap_statistics;
     878           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     879           5 :   size_t peak_mem_1 = heap_statistics.peak_malloced_memory();
     880             :   printf("peak memory after init:          %8zu\n", peak_mem_1);
     881             : 
     882             :   v8::ScriptCompiler::Compile(env.local(), &script_source,
     883           5 :                               v8::ScriptCompiler::kNoCompileOptions)
     884           5 :       .ToLocalChecked();
     885             : 
     886           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     887           5 :   size_t peak_mem_2 = heap_statistics.peak_malloced_memory();
     888             :   printf("peak memory after lazy compile:  %8zu\n", peak_mem_2);
     889             : 
     890             :   v8::ScriptCompiler::Compile(env.local(), &script_source,
     891           5 :                               v8::ScriptCompiler::kNoCompileOptions)
     892           5 :       .ToLocalChecked();
     893             : 
     894           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     895           5 :   size_t peak_mem_3 = heap_statistics.peak_malloced_memory();
     896             :   printf("peak memory after lazy compile:  %8zu\n", peak_mem_3);
     897             : 
     898             :   v8::ScriptCompiler::Compile(env.local(), &script_source,
     899           5 :                               v8::ScriptCompiler::kEagerCompile)
     900           5 :       .ToLocalChecked();
     901             : 
     902           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     903           5 :   size_t peak_mem_4 = heap_statistics.peak_malloced_memory();
     904             :   printf("peak memory after eager compile: %8zu\n", peak_mem_4);
     905             : 
     906           5 :   CHECK_LE(peak_mem_1, peak_mem_2);
     907           5 :   CHECK_EQ(peak_mem_2, peak_mem_3);
     908           5 :   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          10 :   CHECK_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
     912           5 : }
     913             : 
     914             : // TODO(mslekova): Remove the duplication with test-heap.cc
     915           2 : static int AllocationSitesCount(Heap* heap) {
     916             :   int count = 0;
     917           5 :   for (Object site = heap->allocation_sites_list(); site->IsAllocationSite();) {
     918           1 :     AllocationSite cur = AllocationSite::cast(site);
     919           1 :     CHECK(cur->HasWeakNext());
     920           1 :     site = cur->weak_next();
     921           1 :     count++;
     922             :   }
     923           2 :   return count;
     924             : }
     925             : 
     926             : // This test simulates a specific race-condition if GC is triggered just
     927             : // before CompilationDependencies::Commit is finished, and this changes
     928             : // the pretenuring decision, thus causing a deoptimization.
     929       28341 : TEST(DecideToPretenureDuringCompilation) {
     930             :   // The test makes use of optimization and relies on deterministic
     931             :   // compilation.
     932           4 :   if (!i::FLAG_opt || i::FLAG_always_opt ||
     933           1 :       i::FLAG_stress_incremental_marking || i::FLAG_optimize_for_size
     934             : #ifdef ENABLE_MINOR_MC
     935           1 :       || i::FLAG_minor_mc
     936             : #endif
     937             :   )
     938           3 :     return;
     939             : 
     940           1 :   FLAG_stress_gc_during_compilation = true;
     941           1 :   FLAG_allow_natives_syntax = true;
     942           1 :   FLAG_allocation_site_pretenuring = true;
     943           1 :   FLAG_flush_bytecode = false;
     944             : 
     945             :   // We want to trigger exactly 1 optimization.
     946           1 :   FLAG_use_osr = false;
     947             : 
     948             :   // We'll do manual initialization.
     949             :   ManualGCScope manual_gc_scope;
     950             :   v8::Isolate::CreateParams create_params;
     951             : 
     952             :   // This setting ensures Heap::MaximumSizeScavenge will return `true`.
     953             :   // We need to initialize the heap with at least 1 page, while keeping the
     954             :   // limit low, to ensure the new space fills even on 32-bit architectures.
     955             :   create_params.constraints.set_max_semi_space_size_in_kb(Page::kPageSize /
     956             :                                                           1024);
     957           1 :   create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
     958           1 :   v8::Isolate* isolate = v8::Isolate::New(create_params);
     959             : 
     960           1 :   isolate->Enter();
     961             :   {
     962           1 :     i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
     963           1 :     Heap* heap = i_isolate->heap();
     964             :     GlobalHandles* global_handles = i_isolate->global_handles();
     965             :     HandleScope handle_scope(i_isolate);
     966             : 
     967             :     // The allocation site at the head of the list is ours.
     968             :     Handle<AllocationSite> site;
     969             :     {
     970             :       LocalContext context(isolate);
     971           2 :       v8::HandleScope scope(context->GetIsolate());
     972             : 
     973           1 :       int count = AllocationSitesCount(heap);
     974             :       CompileRun(
     975             :           "let arr = [];"
     976             :           "function foo(shouldKeep) {"
     977             :           "  let local_array = new Array();"
     978             :           "  if (shouldKeep) arr.push(local_array);"
     979             :           "}"
     980             :           "function bar(shouldKeep) {"
     981             :           "  for (let i = 0; i < 10000; i++) {"
     982             :           "    foo(shouldKeep);"
     983             :           "  }"
     984             :           "}"
     985             :           "bar();");
     986             : 
     987             :       // This number should be >= kPretenureRatio * 10000,
     988             :       // where 10000 is the number of iterations in `bar`,
     989             :       // in order to make the ratio in DigestPretenuringFeedback close to 1.
     990             :       const int memento_found_bump = 8500;
     991             : 
     992             :       // One allocation site should have been created.
     993           1 :       int new_count = AllocationSitesCount(heap);
     994           1 :       CHECK_EQ(new_count, (count + 1));
     995             :       site = Handle<AllocationSite>::cast(global_handles->Create(
     996           1 :           AllocationSite::cast(heap->allocation_sites_list())));
     997             :       site->set_memento_found_count(memento_found_bump);
     998             : 
     999             :       CompileRun("%OptimizeFunctionOnNextCall(bar);");
    1000             :       CompileRun("bar(true);");
    1001             : 
    1002             :       // The last call should have caused `foo` to bail out of compilation
    1003             :       // due to dependency change (the pretenuring decision in this case).
    1004             :       // This will cause recompilation.
    1005             : 
    1006             :       // Check `bar` can get optimized again, meaning the compiler state is
    1007             :       // recoverable from this point.
    1008             :       CompileRun("%OptimizeFunctionOnNextCall(bar);");
    1009             :       CompileRun("bar();");
    1010             : 
    1011             :       Handle<Object> foo_obj =
    1012           2 :           JSReceiver::GetProperty(i_isolate, i_isolate->global_object(), "bar")
    1013           2 :               .ToHandleChecked();
    1014           1 :       Handle<JSFunction> bar = Handle<JSFunction>::cast(foo_obj);
    1015             : 
    1016           2 :       CHECK(bar->IsOptimized());
    1017             :     }
    1018             :   }
    1019           1 :   isolate->Exit();
    1020           1 :   isolate->Dispose();
    1021             : }
    1022             : 
    1023             : }  // namespace internal
    1024       85011 : }  // namespace v8

Generated by: LCOV version 1.10