test-cpu-profiler.cc 83.4 KB
Newer Older
1
// Copyright 2010 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
// 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.
27 28 29
//
// Tests of profiles generator and utilities.

30 31 32
#include "src/v8.h"

#include "include/v8-profiler.h"
33
#include "src/api.h"
34
#include "src/base/platform/platform.h"
35
#include "src/deoptimizer.h"
36
#include "src/libplatform/default-platform.h"
37
#include "src/objects-inl.h"
38
#include "src/profiler/cpu-profiler-inl.h"
lpy's avatar
lpy committed
39
#include "src/profiler/profiler-listener.h"
40 41 42
#include "src/utils.h"
#include "test/cctest/cctest.h"
#include "test/cctest/profiler-extension.h"
43

44 45 46
#include "include/libplatform/v8-tracing.h"
#include "src/tracing/trace-event.h"

47 48 49
namespace v8 {
namespace internal {
namespace test_cpu_profiler {
50

51
// Helper methods
52 53 54 55
static v8::Local<v8::Function> GetFunction(v8::Local<v8::Context> env,
                                           const char* name) {
  return v8::Local<v8::Function>::Cast(
      env->Global()->Get(env, v8_str(name)).ToLocalChecked());
56 57
}

58 59 60 61
static size_t offset(const char* src, const char* substring) {
  const char* it = strstr(src, substring);
  CHECK(it);
  return static_cast<size_t>(it - src);
62 63
}

64 65 66 67 68
template <typename A, typename B>
static int dist(A a, B b) {
  return abs(static_cast<int>(a) - static_cast<int>(b));
}

69 70
static const char* reason(const i::DeoptimizeReason reason) {
  return i::DeoptimizeReasonToString(reason);
loislo's avatar
loislo committed
71 72
}

73
TEST(StartStop) {
74 75
  i::Isolate* isolate = CcTest::i_isolate();
  CpuProfilesCollection profiles(isolate);
76
  ProfileGenerator generator(&profiles);
77
  std::unique_ptr<ProfilerEventsProcessor> processor(
78
      new ProfilerEventsProcessor(isolate, &generator,
79
                                  v8::base::TimeDelta::FromMicroseconds(100)));
80 81
  processor->Start();
  processor->StopSynchronously();
82 83
}

84 85
static void EnqueueTickSampleEvent(ProfilerEventsProcessor* proc,
                                   i::Address frame1,
86 87
                                   i::Address frame2 = nullptr,
                                   i::Address frame3 = nullptr) {
88
  v8::TickSample* sample = proc->StartTickSample();
89
  sample->pc = frame1;
90
  sample->tos = frame1;
91
  sample->frames_count = 0;
92
  if (frame2 != nullptr) {
93 94 95
    sample->stack[0] = frame2;
    sample->frames_count = 1;
  }
96
  if (frame3 != nullptr) {
97 98 99
    sample->stack[1] = frame3;
    sample->frames_count = 2;
  }
100
  proc->FinishTickSample();
101 102
}

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
namespace {

class TestSetup {
 public:
  TestSetup()
      : old_flag_prof_browser_mode_(i::FLAG_prof_browser_mode) {
    i::FLAG_prof_browser_mode = false;
  }

  ~TestSetup() {
    i::FLAG_prof_browser_mode = old_flag_prof_browser_mode_;
  }

 private:
  bool old_flag_prof_browser_mode_;
};

}  // namespace

122
i::AbstractCode* CreateCode(LocalContext* env) {
123 124 125 126
  static int counter = 0;
  i::EmbeddedVector<char, 256> script;
  i::EmbeddedVector<char, 32> name;

127
  i::SNPrintF(name, "function_%d", ++counter);
128
  const char* name_start = name.start();
129
  i::SNPrintF(script,
130 131 132 133 134 135 136
      "function %s() {\n"
           "var counter = 0;\n"
           "for (var i = 0; i < %d; ++i) counter += i;\n"
           "return '%s_' + counter;\n"
       "}\n"
       "%s();\n", name_start, counter, name_start, name_start);
  CompileRun(script.start());
137

138
  i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(
139
      v8::Utils::OpenHandle(*GetFunction(env->local(), name_start)));
140
  return fun->abstract_code();
141 142
}

143
TEST(CodeEvents) {
144
  CcTest::InitializeVM();
145
  LocalContext env;
146
  i::Isolate* isolate = CcTest::i_isolate();
147
  i::Factory* factory = isolate->factory();
148
  TestSetup test_setup;
149 150 151

  i::HandleScope scope(isolate);

152 153 154 155
  i::AbstractCode* aaa_code = CreateCode(&env);
  i::AbstractCode* comment_code = CreateCode(&env);
  i::AbstractCode* comment2_code = CreateCode(&env);
  i::AbstractCode* moved_code = CreateCode(&env);
156

157
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
158
  ProfileGenerator* generator = new ProfileGenerator(profiles);
159 160
  ProfilerEventsProcessor* processor = new ProfilerEventsProcessor(
      isolate, generator, v8::base::TimeDelta::FromMicroseconds(100));
161
  CpuProfiler profiler(isolate, profiles, generator, processor);
162
  profiles->StartProfiling("", false);
163
  processor->Start();
lpy's avatar
lpy committed
164 165 166
  ProfilerListener profiler_listener(isolate);
  isolate->code_event_dispatcher()->AddListener(&profiler_listener);
  profiler_listener.AddObserver(&profiler);
167 168 169

  // Enqueue code creation events.
  const char* aaa_str = "aaa";
170
  i::Handle<i::String> aaa_name = factory->NewStringFromAsciiChecked(aaa_str);
lpy's avatar
lpy committed
171 172 173 174 175 176 177
  profiler_listener.CodeCreateEvent(i::Logger::FUNCTION_TAG, aaa_code,
                                    *aaa_name);
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, comment_code,
                                    "comment");
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, comment2_code,
                                    "comment2");
  profiler_listener.CodeMoveEvent(comment2_code, moved_code->address());
178

179
  // Enqueue a tick event to enable code events processing.
180
  EnqueueTickSampleEvent(processor, aaa_code->address());
181

lpy's avatar
lpy committed
182 183
  profiler_listener.RemoveObserver(&profiler);
  isolate->code_event_dispatcher()->RemoveListener(&profiler_listener);
184
  processor->StopSynchronously();
185 186

  // Check the state of profile generator.
187
  CodeEntry* aaa = generator->code_map()->FindEntry(aaa_code->address());
188
  CHECK(aaa);
189
  CHECK_EQ(0, strcmp(aaa_str, aaa->name()));
190

191 192
  CodeEntry* comment =
      generator->code_map()->FindEntry(comment_code->address());
193
  CHECK(comment);
194
  CHECK_EQ(0, strcmp("comment", comment->name()));
195

196
  CHECK(!generator->code_map()->FindEntry(comment2_code->address()));
197

198
  CodeEntry* comment2 = generator->code_map()->FindEntry(moved_code->address());
199
  CHECK(comment2);
200
  CHECK_EQ(0, strcmp("comment2", comment2->name()));
201 202 203 204 205 206 207 208
}

template<typename T>
static int CompareProfileNodes(const T* p1, const T* p2) {
  return strcmp((*p1)->entry()->name(), (*p2)->entry()->name());
}

TEST(TickEvents) {
209
  TestSetup test_setup;
210
  LocalContext env;
211
  i::Isolate* isolate = CcTest::i_isolate();
212 213
  i::HandleScope scope(isolate);

214 215 216
  i::AbstractCode* frame1_code = CreateCode(&env);
  i::AbstractCode* frame2_code = CreateCode(&env);
  i::AbstractCode* frame3_code = CreateCode(&env);
217

218
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
219
  ProfileGenerator* generator = new ProfileGenerator(profiles);
lpy's avatar
lpy committed
220 221 222
  ProfilerEventsProcessor* processor =
      new ProfilerEventsProcessor(CcTest::i_isolate(), generator,
                                  v8::base::TimeDelta::FromMicroseconds(100));
223
  CpuProfiler profiler(isolate, profiles, generator, processor);
224
  profiles->StartProfiling("", false);
225
  processor->Start();
lpy's avatar
lpy committed
226 227 228
  ProfilerListener profiler_listener(isolate);
  isolate->code_event_dispatcher()->AddListener(&profiler_listener);
  profiler_listener.AddObserver(&profiler);
229

lpy's avatar
lpy committed
230
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, frame1_code, "bbb");
231
  profiler_listener.CodeCreateEvent(i::Logger::STUB_TAG, frame2_code, "ccc");
lpy's avatar
lpy committed
232
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, frame3_code, "ddd");
233

234
  EnqueueTickSampleEvent(processor, frame1_code->instruction_start());
235
  EnqueueTickSampleEvent(
236
      processor,
237
      frame2_code->instruction_start() + frame2_code->ExecutableSize() / 2,
238
      frame1_code->instruction_start() + frame1_code->ExecutableSize() / 2);
239 240 241
  EnqueueTickSampleEvent(processor, frame3_code->instruction_end() - 1,
                         frame2_code->instruction_end() - 1,
                         frame1_code->instruction_end() - 1);
242

lpy's avatar
lpy committed
243 244
  profiler_listener.RemoveObserver(&profiler);
  isolate->code_event_dispatcher()->RemoveListener(&profiler_listener);
245
  processor->StopSynchronously();
246
  CpuProfile* profile = profiles->StopProfiling("");
247
  CHECK(profile);
248 249

  // Check call trees.
250
  const std::vector<ProfileNode*>* top_down_root_children =
251
      profile->top_down()->root()->children();
252 253 254 255 256
  CHECK_EQ(1, top_down_root_children->size());
  CHECK_EQ(0, strcmp("bbb", top_down_root_children->back()->entry()->name()));
  const std::vector<ProfileNode*>* top_down_bbb_children =
      top_down_root_children->back()->children();
  CHECK_EQ(1, top_down_bbb_children->size());
257
  CHECK_EQ(0, strcmp("ccc", top_down_bbb_children->back()->entry()->name()));
258 259 260 261 262 263 264
  const std::vector<ProfileNode*>* top_down_stub_children =
      top_down_bbb_children->back()->children();
  CHECK_EQ(1, top_down_stub_children->size());
  CHECK_EQ(0, strcmp("ddd", top_down_stub_children->back()->entry()->name()));
  const std::vector<ProfileNode*>* top_down_ddd_children =
      top_down_stub_children->back()->children();
  CHECK(top_down_ddd_children->empty());
lpy's avatar
lpy committed
265 266

  isolate->code_event_dispatcher()->RemoveListener(&profiler_listener);
267
}
268

269 270 271
// http://crbug/51594
// This test must not crash.
TEST(CrashIfStoppingLastNonExistentProfile) {
272
  CcTest::InitializeVM();
273
  TestSetup test_setup;
274
  std::unique_ptr<CpuProfiler> profiler(new CpuProfiler(CcTest::i_isolate()));
275 276 277 278
  profiler->StartProfiling("1");
  profiler->StopProfiling("2");
  profiler->StartProfiling("1");
  profiler->StopProfiling("");
279 280
}

281 282 283 284
// http://code.google.com/p/v8/issues/detail?id=1398
// Long stacks (exceeding max frames limit) must not be erased.
TEST(Issue1398) {
  TestSetup test_setup;
285
  LocalContext env;
286
  i::Isolate* isolate = CcTest::i_isolate();
287 288
  i::HandleScope scope(isolate);

289
  i::AbstractCode* code = CreateCode(&env);
290

291
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
292
  ProfileGenerator* generator = new ProfileGenerator(profiles);
lpy's avatar
lpy committed
293 294 295
  ProfilerEventsProcessor* processor =
      new ProfilerEventsProcessor(CcTest::i_isolate(), generator,
                                  v8::base::TimeDelta::FromMicroseconds(100));
296
  CpuProfiler profiler(isolate, profiles, generator, processor);
297
  profiles->StartProfiling("", false);
298
  processor->Start();
lpy's avatar
lpy committed
299 300 301
  ProfilerListener profiler_listener(isolate);
  isolate->code_event_dispatcher()->AddListener(&profiler_listener);
  profiler_listener.AddObserver(&profiler);
302

lpy's avatar
lpy committed
303
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, code, "bbb");
304

305
  v8::TickSample* sample = processor->StartTickSample();
306
  sample->pc = code->address();
307
  sample->tos = 0;
308
  sample->frames_count = v8::TickSample::kMaxFramesCount;
309
  for (unsigned i = 0; i < sample->frames_count; ++i) {
310
    sample->stack[i] = code->address();
311
  }
312
  processor->FinishTickSample();
313

lpy's avatar
lpy committed
314 315
  profiler_listener.RemoveObserver(&profiler);
  isolate->code_event_dispatcher()->RemoveListener(&profiler_listener);
316
  processor->StopSynchronously();
317
  CpuProfile* profile = profiles->StopProfiling("");
318
  CHECK(profile);
319

320
  unsigned actual_depth = 0;
321
  const ProfileNode* node = profile->top_down()->root();
322 323
  while (!node->children()->empty()) {
    node = node->children()->back();
324 325 326
    ++actual_depth;
  }

327
  CHECK_EQ(1 + v8::TickSample::kMaxFramesCount, actual_depth);  // +1 for PC.
328 329
}

330
TEST(DeleteAllCpuProfiles) {
331
  CcTest::InitializeVM();
332
  TestSetup test_setup;
333
  std::unique_ptr<CpuProfiler> profiler(new CpuProfiler(CcTest::i_isolate()));
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  CHECK_EQ(0, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());

  profiler->StartProfiling("1");
  profiler->StopProfiling("1");
  CHECK_EQ(1, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());
  profiler->StartProfiling("1");
  profiler->StartProfiling("2");
  profiler->StopProfiling("2");
  profiler->StopProfiling("1");
  CHECK_EQ(2, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());
350 351

  // Test profiling cancellation by the 'delete' command.
352 353 354 355 356
  profiler->StartProfiling("1");
  profiler->StartProfiling("2");
  CHECK_EQ(0, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());
357 358 359
}


360 361 362 363 364 365
static bool FindCpuProfile(v8::CpuProfiler* v8profiler,
                           const v8::CpuProfile* v8profile) {
  i::CpuProfiler* profiler = reinterpret_cast<i::CpuProfiler*>(v8profiler);
  const i::CpuProfile* profile =
      reinterpret_cast<const i::CpuProfile*>(v8profile);
  int length = profiler->GetProfilesCount();
366
  for (int i = 0; i < length; i++) {
367 368
    if (profile == profiler->GetProfile(i))
      return true;
369
  }
370
  return false;
371 372 373
}


374 375
TEST(DeleteCpuProfile) {
  LocalContext env;
376
  v8::HandleScope scope(env->GetIsolate());
377
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
378
  i::CpuProfiler* iprofiler = reinterpret_cast<i::CpuProfiler*>(cpu_profiler);
379

380
  CHECK_EQ(0, iprofiler->GetProfilesCount());
381
  v8::Local<v8::String> name1 = v8_str("1");
382 383
  cpu_profiler->StartProfiling(name1);
  v8::CpuProfile* p1 = cpu_profiler->StopProfiling(name1);
384
  CHECK(p1);
385 386
  CHECK_EQ(1, iprofiler->GetProfilesCount());
  CHECK(FindCpuProfile(cpu_profiler, p1));
387
  p1->Delete();
388
  CHECK_EQ(0, iprofiler->GetProfilesCount());
389

390
  v8::Local<v8::String> name2 = v8_str("2");
391 392
  cpu_profiler->StartProfiling(name2);
  v8::CpuProfile* p2 = cpu_profiler->StopProfiling(name2);
393
  CHECK(p2);
394 395
  CHECK_EQ(1, iprofiler->GetProfilesCount());
  CHECK(FindCpuProfile(cpu_profiler, p2));
396
  v8::Local<v8::String> name3 = v8_str("3");
397 398
  cpu_profiler->StartProfiling(name3);
  v8::CpuProfile* p3 = cpu_profiler->StopProfiling(name3);
399
  CHECK(p3);
400 401 402 403
  CHECK_EQ(2, iprofiler->GetProfilesCount());
  CHECK_NE(p2, p3);
  CHECK(FindCpuProfile(cpu_profiler, p3));
  CHECK(FindCpuProfile(cpu_profiler, p2));
404
  p2->Delete();
405 406 407
  CHECK_EQ(1, iprofiler->GetProfilesCount());
  CHECK(!FindCpuProfile(cpu_profiler, p2));
  CHECK(FindCpuProfile(cpu_profiler, p3));
408
  p3->Delete();
409
  CHECK_EQ(0, iprofiler->GetProfilesCount());
410
  cpu_profiler->Dispose();
411 412 413
}


414 415 416
TEST(ProfileStartEndTime) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
417
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
418

419
  v8::Local<v8::String> profile_name = v8_str("test");
420 421
  cpu_profiler->StartProfiling(profile_name);
  const v8::CpuProfile* profile = cpu_profiler->StopProfiling(profile_name);
422
  CHECK(profile->GetStartTime() <= profile->GetEndTime());
423
  cpu_profiler->Dispose();
424 425
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
class ProfilerHelper {
 public:
  explicit ProfilerHelper(const v8::Local<v8::Context>& context)
      : context_(context),
        profiler_(v8::CpuProfiler::New(context->GetIsolate())) {
    i::ProfilerExtension::set_profiler(profiler_);
  }
  ~ProfilerHelper() {
    i::ProfilerExtension::set_profiler(static_cast<CpuProfiler*>(nullptr));
    profiler_->Dispose();
  }

  v8::CpuProfile* Run(v8::Local<v8::Function> function,
                      v8::Local<v8::Value> argv[], int argc,
                      unsigned min_js_samples = 0,
                      unsigned min_external_samples = 0,
                      bool collect_samples = false);

  v8::CpuProfiler* profiler() { return profiler_; }

 private:
  v8::Local<v8::Context> context_;
  v8::CpuProfiler* profiler_;
};

v8::CpuProfile* ProfilerHelper::Run(v8::Local<v8::Function> function,
                                    v8::Local<v8::Value> argv[], int argc,
                                    unsigned min_js_samples,
                                    unsigned min_external_samples,
                                    bool collect_samples) {
456
  v8::Local<v8::String> profile_name = v8_str("my_profile");
457

458 459
  profiler_->SetSamplingInterval(100);
  profiler_->StartProfiling(profile_name, collect_samples);
460

461 462 463
  v8::internal::CpuProfiler* iprofiler =
      reinterpret_cast<v8::internal::CpuProfiler*>(profiler_);
  v8::sampler::Sampler* sampler = iprofiler->processor()->sampler();
464 465
  sampler->StartCountingSamples();
  do {
466
    function->Call(context_, context_->Global(), argc, argv).ToLocalChecked();
467 468
  } while (sampler->js_sample_count() < min_js_samples ||
           sampler->external_sample_count() < min_external_samples);
469

470
  v8::CpuProfile* profile = profiler_->StopProfiling(profile_name);
471

472
  CHECK(profile);
473
  // Dump collected profile to have a better diagnostic in case of failure.
474
  reinterpret_cast<i::CpuProfile*>(profile)->Print();
475 476 477 478

  return profile;
}

479 480 481 482 483 484 485
static unsigned TotalHitCount(const v8::CpuProfileNode* node) {
  unsigned hit_count = node->GetHitCount();
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i)
    hit_count += TotalHitCount(node->GetChild(i));
  return hit_count;
}

486 487
static const v8::CpuProfileNode* FindChild(v8::Local<v8::Context> context,
                                           const v8::CpuProfileNode* node,
488 489
                                           const char* name) {
  int count = node->GetChildrenCount();
alph's avatar
alph committed
490
  v8::Local<v8::String> name_handle = v8_str(name);
491 492
  for (int i = 0; i < count; i++) {
    const v8::CpuProfileNode* child = node->GetChild(i);
alph's avatar
alph committed
493
    if (name_handle->Equals(context, child->GetFunctionName()).FromJust()) {
494 495
      return child;
    }
496
  }
497
  return nullptr;
498 499
}

500 501 502 503 504 505 506 507 508 509
static const v8::CpuProfileNode* FindChild(const v8::CpuProfileNode* node,
                                           const char* name) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::CpuProfileNode* child = node->GetChild(i);
    if (strcmp(child->GetFunctionNameStr(), name) == 0) {
      return child;
    }
  }
  return nullptr;
}
510

511 512
static const v8::CpuProfileNode* GetChild(v8::Local<v8::Context> context,
                                          const v8::CpuProfileNode* node,
513
                                          const char* name) {
514
  const v8::CpuProfileNode* result = FindChild(context, node, name);
515
  if (!result) FATAL("Failed to GetChild: %s", name);
516 517 518 519
  return result;
}


520 521
static void CheckSimpleBranch(v8::Local<v8::Context> context,
                              const v8::CpuProfileNode* node,
522 523 524
                              const char* names[], int length) {
  for (int i = 0; i < length; i++) {
    const char* name = names[i];
525
    node = GetChild(context, node, name);
526 527 528 529
  }
}


530 531
static const ProfileNode* GetSimpleBranch(v8::Local<v8::Context> context,
                                          v8::CpuProfile* profile,
loislo's avatar
loislo committed
532 533
                                          const char* names[], int length) {
  const v8::CpuProfileNode* node = profile->GetTopDownRoot();
534
  for (int i = 0; i < length; i++) {
535
    node = GetChild(context, node, names[i]);
536
  }
loislo's avatar
loislo committed
537
  return reinterpret_cast<const ProfileNode*>(node);
538 539
}

alph's avatar
alph committed
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
static const char* cpu_profiler_test_source =
    "%NeverOptimizeFunction(loop);\n"
    "%NeverOptimizeFunction(delay);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(baz);\n"
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(start);\n"
    "function loop(timeout) {\n"
    "  this.mmm = 0;\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    var n = 1000;\n"
    "    while(n > 1) {\n"
    "      n--;\n"
    "      this.mmm += n * n * n;\n"
    "    }\n"
    "  } while (Date.now() - start < timeout);\n"
    "}\n"
    "function delay() { loop(10); }\n"
    "function bar() { delay(); }\n"
    "function baz() { delay(); }\n"
    "function foo() {\n"
    "  delay();\n"
    "  bar();\n"
    "  delay();\n"
    "  baz();\n"
    "}\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    foo();\n"
    "  } while (Date.now() - start < duration);\n"
    "}\n";
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

// Check that the profile tree for the script above will look like the
// following:
//
// [Top down]:
//  1062     0   (root) [-1]
//  1054     0    start [-1]
//  1054     1      foo [-1]
//   265     0        baz [-1]
//   265     1          delay [-1]
//   264   264            loop [-1]
//   525     3        delay [-1]
//   522   522          loop [-1]
//   263     0        bar [-1]
//   263     1          delay [-1]
//   262   262            loop [-1]
//     2     2    (program) [-1]
//     6     6    (garbage collector) [-1]
TEST(CollectCpuProfile) {
alph's avatar
alph committed
592
  i::FLAG_allow_natives_syntax = true;
593 594 595
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

596
  CompileRun(cpu_profiler_test_source);
597
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
598

599
  int32_t profiling_interval_ms = 200;
600 601
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
602 603
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
604 605

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
606 607
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  const v8::CpuProfileNode* foo_node = GetChild(env.local(), start_node, "foo");
608

alph's avatar
alph committed
609 610 611 612 613 614 615
  const char* bar_branch[] = {"bar", "delay", "loop"};
  CheckSimpleBranch(env.local(), foo_node, bar_branch, arraysize(bar_branch));
  const char* baz_branch[] = {"baz", "delay", "loop"};
  CheckSimpleBranch(env.local(), foo_node, baz_branch, arraysize(baz_branch));
  const char* delay_branch[] = {"delay", "loop"};
  CheckSimpleBranch(env.local(), foo_node, delay_branch,
                    arraysize(delay_branch));
616

617
  profile->Delete();
618
}
619

620
static const char* hot_deopt_no_frame_entry_test_source =
alph's avatar
alph committed
621 622 623 624 625 626 627 628 629 630 631 632 633
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(start);\n"
    "function foo(a, b) {\n"
    "  return a + b;\n"
    "}\n"
    "function start(timeout) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    for (var i = 1; i < 1000; ++i) foo(1, i);\n"
    "    var duration = Date.now() - start;\n"
    "  } while (duration < timeout);\n"
    "  return duration;\n"
    "}\n";
634 635 636 637 638 639 640 641 642 643 644

// Check that the profile tree for the script above will look like the
// following:
//
// [Top down]:
//  1062     0  (root) [-1]
//  1054     0    start [-1]
//  1054     1      foo [-1]
//     2     2    (program) [-1]
//     6     6    (garbage collector) [-1]
//
645
// The test checks no FP ranges are present in a deoptimized function.
646 647 648
// If 'foo' has no ranges the samples falling into the prologue will miss the
// 'start' function on the stack, so 'foo' will be attached to the (root).
TEST(HotDeoptNoFrameEntry) {
alph's avatar
alph committed
649
  i::FLAG_allow_natives_syntax = true;
650 651 652
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

653
  CompileRun(hot_deopt_no_frame_entry_test_source);
654
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
655 656

  int32_t profiling_interval_ms = 200;
657 658
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
659 660
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
661 662
  function->Call(env.local(), env->Global(), arraysize(args), args)
      .ToLocalChecked();
663 664

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
665 666
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "foo");
667 668 669 670

  profile->Delete();
}

671
TEST(CollectCpuProfileSamples) {
alph's avatar
alph committed
672
  i::FLAG_allow_natives_syntax = true;
673 674 675
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

676
  CompileRun(cpu_profiler_test_source);
677
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
678 679

  int32_t profiling_interval_ms = 200;
680 681
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
682
  ProfilerHelper helper(env.local());
683
  v8::CpuProfile* profile =
684
      helper.Run(function, args, arraysize(args), 1000, 0, true);
685 686 687 688 689 690

  CHECK_LE(200, profile->GetSamplesCount());
  uint64_t end_time = profile->GetEndTime();
  uint64_t current_time = profile->GetStartTime();
  CHECK_LE(current_time, end_time);
  for (int i = 0; i < profile->GetSamplesCount(); i++) {
691
    CHECK(profile->GetSample(i));
692 693 694 695 696 697 698 699 700
    uint64_t timestamp = profile->GetSampleTimestamp(i);
    CHECK_LE(current_time, timestamp);
    CHECK_LE(timestamp, end_time);
    current_time = timestamp;
  }

  profile->Delete();
}

alph's avatar
alph committed
701 702 703 704 705 706 707 708 709 710 711 712
static const char* cpu_profiler_test_source2 =
    "%NeverOptimizeFunction(loop);\n"
    "%NeverOptimizeFunction(delay);\n"
    "%NeverOptimizeFunction(start);\n"
    "function loop() {}\n"
    "function delay() { loop(); }\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    for (var i = 0; i < 10000; ++i) delay();\n"
    "  } while (Date.now() - start < duration);\n"
    "}";
713

714
// Check that the profile tree doesn't contain unexpected traces:
715 716 717 718 719 720 721 722 723 724 725
//  - 'loop' can be called only by 'delay'
//  - 'delay' may be called only by 'start'
// The profile will look like the following:
//
// [Top down]:
//   135     0   (root) [-1] #1
//   121    72    start [-1] #3
//    49    33      delay [-1] #4
//    16    16        loop [-1] #5
//    14    14    (program) [-1] #2
TEST(SampleWhenFrameIsNotSetup) {
alph's avatar
alph committed
726
  i::FLAG_allow_natives_syntax = true;
727 728 729
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

730
  CompileRun(cpu_profiler_test_source2);
731
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
732

alph's avatar
alph committed
733
  int32_t duration_ms = 100;
734
  v8::Local<v8::Value> args[] = {
alph's avatar
alph committed
735
      v8::Integer::New(env->GetIsolate(), duration_ms)};
736 737
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
738 739

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
740 741 742 743
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  const v8::CpuProfileNode* delay_node =
      GetChild(env.local(), start_node, "delay");
  GetChild(env.local(), delay_node, "loop");
744

745
  profile->Delete();
746
}
747 748 749 750 751 752 753 754

static const char* native_accessor_test_source = "function start(count) {\n"
"  for (var i = 0; i < count; i++) {\n"
"    var o = instance.foo;\n"
"    instance.foo = o + 1;\n"
"  }\n"
"}\n";

755
class TestApiCallbacks {
756
 public:
757
  explicit TestApiCallbacks(int min_duration_ms)
758
      : min_duration_ms_(min_duration_ms),
759
        is_warming_up_(false) {}
760

761 762
  static void Getter(v8::Local<v8::String> name,
                     const v8::PropertyCallbackInfo<v8::Value>& info) {
alph's avatar
alph committed
763
    TestApiCallbacks* data = FromInfo(info);
764
    data->Wait();
765 766 767 768
  }

  static void Setter(v8::Local<v8::String> name,
                     v8::Local<v8::Value> value,
769
                     const v8::PropertyCallbackInfo<void>& info) {
alph's avatar
alph committed
770
    TestApiCallbacks* data = FromInfo(info);
771 772 773 774
    data->Wait();
  }

  static void Callback(const v8::FunctionCallbackInfo<v8::Value>& info) {
alph's avatar
alph committed
775
    TestApiCallbacks* data = FromInfo(info);
776
    data->Wait();
777 778
  }

779
  void set_warming_up(bool value) { is_warming_up_ = value; }
780 781

 private:
782 783
  void Wait() {
    if (is_warming_up_) return;
784 785
    v8::Platform* platform = v8::internal::V8::GetCurrentPlatform();
    double start = platform->CurrentClockTimeMillis();
786 787
    double duration = 0;
    while (duration < min_duration_ms_) {
788
      v8::base::OS::Sleep(v8::base::TimeDelta::FromMilliseconds(1));
789
      duration = platform->CurrentClockTimeMillis() - start;
790 791 792
    }
  }

alph's avatar
alph committed
793 794
  template <typename T>
  static TestApiCallbacks* FromInfo(const T& info) {
795
    void* data = v8::External::Cast(*info.Data())->Value();
796
    return reinterpret_cast<TestApiCallbacks*>(data);
797 798 799
  }

  int min_duration_ms_;
800
  bool is_warming_up_;
801 802 803 804 805 806 807
};


// Test that native accessors are properly reported in the CPU profile.
// This test checks the case when the long-running accessors are called
// only once and the optimizer doesn't have chance to change the invocation
// code.
808
TEST(NativeAccessorUninitializedIC) {
809
  LocalContext env;
810 811
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
812

813 814
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
815 816 817
  v8::Local<v8::ObjectTemplate> instance_template =
      func_template->InstanceTemplate();

818
  TestApiCallbacks accessors(100);
819
  v8::Local<v8::External> data = v8::External::New(isolate, &accessors);
820 821
  instance_template->SetAccessor(v8_str("foo"), &TestApiCallbacks::Getter,
                                 &TestApiCallbacks::Setter, data);
822 823 824 825 826
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
827

828
  CompileRun(native_accessor_test_source);
829
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
830

831
  ProfilerHelper helper(env.local());
832
  int32_t repeat_count = 1;
833
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
834
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 100);
835 836

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
837 838 839
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "get foo");
  GetChild(env.local(), start_node, "set foo");
840

841
  profile->Delete();
842 843 844 845 846 847
}


// Test that native accessors are properly reported in the CPU profile.
// This test makes sure that the accessors are called enough times to become
// hot and to trigger optimizations.
848
TEST(NativeAccessorMonomorphicIC) {
849
  LocalContext env;
850 851
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
852

853 854
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
855 856 857
  v8::Local<v8::ObjectTemplate> instance_template =
      func_template->InstanceTemplate();

858
  TestApiCallbacks accessors(1);
859
  v8::Local<v8::External> data =
860
      v8::External::New(isolate, &accessors);
861 862
  instance_template->SetAccessor(v8_str("foo"), &TestApiCallbacks::Getter,
                                 &TestApiCallbacks::Setter, data);
863 864 865 866 867
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
868

869
  CompileRun(native_accessor_test_source);
870
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
871

872 873 874 875 876
  {
    // Make sure accessors ICs are in monomorphic state before starting
    // profiling.
    accessors.set_warming_up(true);
    int32_t warm_up_iterations = 3;
877 878 879 880
    v8::Local<v8::Value> args[] = {
        v8::Integer::New(isolate, warm_up_iterations)};
    function->Call(env.local(), env->Global(), arraysize(args), args)
        .ToLocalChecked();
881 882 883
    accessors.set_warming_up(false);
  }

884
  int32_t repeat_count = 100;
885
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
886 887
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 100);
888 889

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
890 891 892
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "get foo");
  GetChild(env.local(), start_node, "set foo");
893

894
  profile->Delete();
895
}
896 897 898 899 900 901 902 903 904 905 906


static const char* native_method_test_source = "function start(count) {\n"
"  for (var i = 0; i < count; i++) {\n"
"    instance.fooMethod();\n"
"  }\n"
"}\n";


TEST(NativeMethodUninitializedIC) {
  LocalContext env;
907 908
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
909 910

  TestApiCallbacks callbacks(100);
911
  v8::Local<v8::External> data = v8::External::New(isolate, &callbacks);
912

913 914
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
915
  func_template->SetClassName(v8_str("Test_InstanceConstructor"));
916 917
  v8::Local<v8::ObjectTemplate> proto_template =
      func_template->PrototypeTemplate();
918
  v8::Local<v8::Signature> signature =
919
      v8::Signature::New(isolate, func_template);
920 921 922 923
  proto_template->Set(
      v8_str("fooMethod"),
      v8::FunctionTemplate::New(isolate, &TestApiCallbacks::Callback, data,
                                signature, 0));
924

925 926 927 928 929
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
930

931
  CompileRun(native_method_test_source);
932
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
933

934
  ProfilerHelper helper(env.local());
935
  int32_t repeat_count = 1;
936
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
937
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 100);
938 939

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
940 941
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "fooMethod");
942

943
  profile->Delete();
944 945 946 947 948
}


TEST(NativeMethodMonomorphicIC) {
  LocalContext env;
949 950
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
951 952

  TestApiCallbacks callbacks(1);
953
  v8::Local<v8::External> data =
954
      v8::External::New(isolate, &callbacks);
955

956 957
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
958
  func_template->SetClassName(v8_str("Test_InstanceCostructor"));
959 960
  v8::Local<v8::ObjectTemplate> proto_template =
      func_template->PrototypeTemplate();
961
  v8::Local<v8::Signature> signature =
962
      v8::Signature::New(isolate, func_template);
963 964 965 966
  proto_template->Set(
      v8_str("fooMethod"),
      v8::FunctionTemplate::New(isolate, &TestApiCallbacks::Callback, data,
                                signature, 0));
967

968 969 970 971 972
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
973

974
  CompileRun(native_method_test_source);
975
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
976 977 978 979 980
  {
    // Make sure method ICs are in monomorphic state before starting
    // profiling.
    callbacks.set_warming_up(true);
    int32_t warm_up_iterations = 3;
981 982 983 984
    v8::Local<v8::Value> args[] = {
        v8::Integer::New(isolate, warm_up_iterations)};
    function->Call(env.local(), env->Global(), arraysize(args), args)
        .ToLocalChecked();
985 986 987
    callbacks.set_warming_up(false);
  }

988
  ProfilerHelper helper(env.local());
989
  int32_t repeat_count = 100;
990
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
991
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 200);
992 993

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
994
  GetChild(env.local(), root, "start");
alph's avatar
alph committed
995 996
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "fooMethod");
997

998
  profile->Delete();
999
}
1000 1001


1002 1003 1004 1005 1006 1007 1008 1009
static const char* bound_function_test_source =
    "function foo() {\n"
    "  startProfiling('my_profile');\n"
    "}\n"
    "function start() {\n"
    "  var callback = foo.bind(this);\n"
    "  callback();\n"
    "}";
1010 1011 1012


TEST(BoundFunctionCall) {
1013 1014 1015
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1016

1017
  CompileRun(bound_function_test_source);
1018
  v8::Local<v8::Function> function = GetFunction(env, "start");
1019

1020 1021
  ProfilerHelper helper(env);
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0);
1022 1023 1024

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();

alph's avatar
alph committed
1025 1026
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  GetChild(env, start_node, "foo");
1027

1028
  profile->Delete();
1029
}
1030

1031
// This tests checks distribution of the samples through the source lines.
1032
static void TickLines(bool optimize) {
1033
  if (!optimize) i::FLAG_opt = false;
1034 1035
  CcTest::InitializeVM();
  LocalContext env;
1036
  i::FLAG_allow_natives_syntax = true;
1037 1038 1039 1040 1041
  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();
  i::HandleScope scope(isolate);

  i::EmbeddedVector<char, 512> script;
1042
  i::EmbeddedVector<char, 64> optimize_call;
1043 1044

  const char* func_name = "func";
1045 1046 1047 1048
  if (optimize) {
    i::SNPrintF(optimize_call, "%%OptimizeFunctionOnNextCall(%s);\n",
                func_name);
  } else {
1049
    optimize_call[0] = '\0';
1050
  }
1051 1052 1053 1054 1055 1056 1057 1058 1059
  i::SNPrintF(script,
              "function %s() {\n"
              "  var n = 0;\n"
              "  var m = 100*100;\n"
              "  while (m > 1) {\n"
              "    m--;\n"
              "    n += m * m * m;\n"
              "  }\n"
              "}\n"
1060 1061
              "%s();\n"
              "%s"
1062
              "%s();\n",
1063
              func_name, func_name, optimize_call.start(), func_name);
1064 1065 1066

  CompileRun(script.start());

1067
  i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(
1068
      v8::Utils::OpenHandle(*GetFunction(env.local(), func_name)));
1069
  CHECK(func->shared());
1070
  CHECK(func->shared()->abstract_code());
1071
  CHECK(!optimize || func->IsOptimized() ||
Mythri's avatar
Mythri committed
1072
        !CcTest::i_isolate()->use_optimizer());
1073
  i::AbstractCode* code = func->abstract_code();
1074
  CHECK(code);
1075
  i::Address code_address = code->instruction_start();
1076
  CHECK(code_address);
1077

1078
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
1079
  ProfileGenerator* generator = new ProfileGenerator(profiles);
lpy's avatar
lpy committed
1080 1081 1082
  ProfilerEventsProcessor* processor =
      new ProfilerEventsProcessor(CcTest::i_isolate(), generator,
                                  v8::base::TimeDelta::FromMicroseconds(100));
1083
  CpuProfiler profiler(isolate, profiles, generator, processor);
1084 1085
  profiles->StartProfiling("", false);
  processor->Start();
lpy's avatar
lpy committed
1086 1087 1088
  ProfilerListener profiler_listener(isolate);
  isolate->code_event_dispatcher()->AddListener(&profiler_listener);
  profiler_listener.AddObserver(&profiler);
1089 1090 1091 1092 1093

  // Enqueue code creation events.
  i::Handle<i::String> str = factory->NewStringFromAsciiChecked(func_name);
  int line = 1;
  int column = 1;
lpy's avatar
lpy committed
1094 1095
  profiler_listener.CodeCreateEvent(i::Logger::FUNCTION_TAG, code,
                                    func->shared(), *str, line, column);
1096 1097

  // Enqueue a tick event to enable code events processing.
1098
  EnqueueTickSampleEvent(processor, code_address);
1099

lpy's avatar
lpy committed
1100 1101
  profiler_listener.RemoveObserver(&profiler);
  isolate->code_event_dispatcher()->RemoveListener(&profiler_listener);
1102 1103 1104
  processor->StopSynchronously();

  CpuProfile* profile = profiles->StopProfiling("");
1105
  CHECK(profile);
1106 1107

  // Check the state of profile generator.
1108
  CodeEntry* func_entry = generator->code_map()->FindEntry(code_address);
1109
  CHECK(func_entry);
1110
  CHECK_EQ(0, strcmp(func_name, func_entry->name()));
1111
  const i::JITLineInfoTable* line_info = func_entry->line_info();
1112
  CHECK(line_info);
1113 1114 1115 1116 1117
  CHECK(!line_info->empty());

  // Check the hit source lines using V8 Public APIs.
  const i::ProfileTree* tree = profile->top_down();
  ProfileNode* root = tree->root();
1118
  CHECK(root);
1119
  ProfileNode* func_node = root->FindChild(func_entry);
1120
  CHECK(func_node);
1121 1122 1123 1124 1125 1126 1127

  // Add 10 faked ticks to source line #5.
  int hit_line = 5;
  int hit_count = 10;
  for (int i = 0; i < hit_count; i++) func_node->IncrementLineTicks(hit_line);

  unsigned int line_count = func_node->GetHitLineCount();
1128
  CHECK_EQ(2u, line_count);  // Expect two hit source lines - #1 and #5.
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  ScopedVector<v8::CpuProfileNode::LineTick> entries(line_count);
  CHECK(func_node->GetLineTicks(&entries[0], line_count));
  int value = 0;
  for (int i = 0; i < entries.length(); i++)
    if (entries[i].line == hit_line) {
      value = entries[i].hit_count;
      break;
    }
  CHECK_EQ(hit_count, value);
}

1140 1141 1142 1143
TEST(TickLinesBaseline) { TickLines(false); }

TEST(TickLinesOptimized) { TickLines(true); }

alph's avatar
alph committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
static const char* call_function_test_source =
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
    "function bar(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
    "}\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    for (var i = 0; i < 100; ++i)\n"
    "      bar.call(this, 1000);\n"
    "  } while (Date.now() - start < duration);\n"
    "}";
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

// Test that if we sampled thread when it was inside FunctionCall buitin then
// its caller frame will be '(unresolved function)' as we have no reliable way
// to resolve it.
//
// [Top down]:
//    96     0   (root) [-1] #1
//     1     1    (garbage collector) [-1] #4
//     5     0    (unresolved function) [-1] #5
//     5     5      call [-1] #6
//    71    70    start [-1] #3
//     1     1      bar [-1] #7
//    19    19    (program) [-1] #2
TEST(FunctionCallSample) {
alph's avatar
alph committed
1173
  i::FLAG_allow_natives_syntax = true;
1174 1175 1176
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

1177 1178
  // Collect garbage that might have be generated while installing
  // extensions.
1179
  CcTest::CollectAllGarbage();
1180

1181
  CompileRun(call_function_test_source);
1182
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
1183

1184
  ProfilerHelper helper(env.local());
1185
  int32_t duration_ms = 100;
1186 1187
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), duration_ms)};
1188
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
1189 1190

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1191 1192
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "bar");
1193

lpy's avatar
lpy committed
1194 1195
  const v8::CpuProfileNode* unresolved_node =
      FindChild(env.local(), root, i::CodeEntry::kUnresolvedFunctionName);
alph's avatar
alph committed
1196
  CHECK(!unresolved_node || GetChild(env.local(), unresolved_node, "call"));
1197

1198
  profile->Delete();
1199 1200
}

1201
static const char* function_apply_test_source =
alph's avatar
alph committed
1202 1203 1204 1205 1206 1207 1208
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(test);\n"
    "%NeverOptimizeFunction(start);\n"
    "function bar(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
1209 1210
    "}\n"
    "function test() {\n"
alph's avatar
alph committed
1211
    "  bar.apply(this, [1000]);\n"
1212 1213 1214
    "}\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
alph's avatar
alph committed
1215 1216 1217
    "  do {\n"
    "    for (var i = 0; i < 100; ++i) test();\n"
    "  } while (Date.now() - start < duration);\n"
1218
    "}";
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

// [Top down]:
//    94     0   (root) [-1] #0 1
//     2     2    (garbage collector) [-1] #0 7
//    82    49    start [-1] #16 3
//     1     0      (unresolved function) [-1] #0 8
//     1     1        apply [-1] #0 9
//    32    21      test [-1] #16 4
//     2     2        bar [-1] #16 6
//    10    10    (program) [-1] #0 2
TEST(FunctionApplySample) {
alph's avatar
alph committed
1230
  i::FLAG_allow_natives_syntax = true;
1231 1232 1233
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

1234
  CompileRun(function_apply_test_source);
1235
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
1236

1237
  ProfilerHelper helper(env.local());
1238
  int32_t duration_ms = 100;
1239 1240
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), duration_ms)};
1241
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
1242 1243

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1244 1245 1246 1247
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  const v8::CpuProfileNode* test_node =
      GetChild(env.local(), start_node, "test");
  GetChild(env.local(), test_node, "bar");
1248

lpy's avatar
lpy committed
1249 1250
  const v8::CpuProfileNode* unresolved_node =
      FindChild(env.local(), start_node, CodeEntry::kUnresolvedFunctionName);
alph's avatar
alph committed
1251
  CHECK(!unresolved_node || GetChild(env.local(), unresolved_node, "apply"));
1252

1253
  profile->Delete();
1254
}
1255

1256
static const char* cpu_profiler_deep_stack_test_source =
alph's avatar
alph committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    "function foo(n) {\n"
    "  if (n)\n"
    "    foo(n - 1);\n"
    "  else\n"
    "    collectSample();\n"
    "}\n"
    "function start() {\n"
    "  startProfiling('my_profile');\n"
    "  foo(250);\n"
    "}\n";
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276

// Check a deep stack
//
// [Top down]:
//    0  (root) 0 #1
//    2    (program) 0 #2
//    0    start 21 #3 no reason
//    0      foo 21 #4 no reason
//    0        foo 21 #5 no reason
//                ....
alph's avatar
alph committed
1277
//    0          foo 21 #254 no reason
1278 1279 1280 1281
TEST(CpuProfileDeepStack) {
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1282
  ProfilerHelper helper(env);
1283

1284
  CompileRun(cpu_profiler_deep_stack_test_source);
1285
  v8::Local<v8::Function> function = GetFunction(env, "start");
1286

1287
  v8::Local<v8::String> profile_name = v8_str("my_profile");
1288
  function->Call(env, env->Global(), 0, nullptr).ToLocalChecked();
1289
  v8::CpuProfile* profile = helper.profiler()->StopProfiling(profile_name);
1290
  CHECK(profile);
1291 1292 1293 1294
  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
1295
  const v8::CpuProfileNode* node = GetChild(env, root, "start");
alph's avatar
alph committed
1296
  for (int i = 0; i <= 250; ++i) {
1297
    node = GetChild(env, node, "foo");
1298
  }
alph's avatar
alph committed
1299
  CHECK(!FindChild(env, node, "foo"));
1300 1301 1302 1303

  profile->Delete();
}

1304
static const char* js_native_js_test_source =
alph's avatar
alph committed
1305 1306 1307 1308 1309 1310 1311
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
    "function foo(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
1312 1313
    "}\n"
    "function bar() {\n"
alph's avatar
alph committed
1314
    "  foo(1000);\n"
1315 1316
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1317
    "  CallJsFunction(bar);\n"
1318
    "}";
1319 1320

static void CallJsFunction(const v8::FunctionCallbackInfo<v8::Value>& info) {
1321 1322 1323 1324 1325
  v8::Local<v8::Function> function = info[0].As<v8::Function>();
  v8::Local<v8::Value> argv[] = {info[1]};
  function->Call(info.GetIsolate()->GetCurrentContext(), info.This(),
                 arraysize(argv), argv)
      .ToLocalChecked();
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
}

// [Top down]:
//    58     0   (root) #0 1
//     2     2    (program) #0 2
//    56     1    start #16 3
//    55     0      CallJsFunction #0 4
//    55     1        bar #16 5
//    54    54          foo #16 6
TEST(JsNativeJsSample) {
alph's avatar
alph committed
1336
  i::FLAG_allow_natives_syntax = true;
1337 1338 1339
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1340 1341

  v8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(
1342
      env->GetIsolate(), CallJsFunction);
1343 1344
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
1345
  func->SetName(v8_str("CallJsFunction"));
1346
  env->Global()->Set(env, v8_str("CallJsFunction"), func).FromJust();
1347

1348
  CompileRun(js_native_js_test_source);
1349
  v8::Local<v8::Function> function = GetFunction(env, "start");
1350

1351 1352
  ProfilerHelper helper(env);
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 1000);
1353 1354

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1355 1356 1357 1358 1359
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node =
      GetChild(env, start_node, "CallJsFunction");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node, "bar");
  GetChild(env, bar_node, "foo");
1360

1361
  profile->Delete();
1362 1363 1364
}

static const char* js_native_js_runtime_js_test_source =
alph's avatar
alph committed
1365 1366 1367 1368 1369 1370 1371
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
    "function foo(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
1372 1373 1374
    "}\n"
    "var bound = foo.bind(this);\n"
    "function bar() {\n"
alph's avatar
alph committed
1375
    "  bound(1000);\n"
1376 1377
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1378
    "  CallJsFunction(bar);\n"
1379
    "}";
1380 1381 1382 1383 1384 1385 1386 1387 1388

// [Top down]:
//    57     0   (root) #0 1
//    55     1    start #16 3
//    54     0      CallJsFunction #0 4
//    54     3        bar #16 5
//    51    51          foo #16 6
//     2     2    (program) #0 2
TEST(JsNativeJsRuntimeJsSample) {
alph's avatar
alph committed
1389
  i::FLAG_allow_natives_syntax = true;
1390 1391 1392
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1393 1394

  v8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(
1395
      env->GetIsolate(), CallJsFunction);
1396 1397
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
1398
  func->SetName(v8_str("CallJsFunction"));
1399
  env->Global()->Set(env, v8_str("CallJsFunction"), func).FromJust();
1400

1401
  CompileRun(js_native_js_runtime_js_test_source);
1402
  ProfilerHelper helper(env);
1403
  v8::Local<v8::Function> function = GetFunction(env, "start");
1404
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 1000);
1405 1406

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1407 1408 1409 1410 1411
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node =
      GetChild(env, start_node, "CallJsFunction");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node, "bar");
  GetChild(env, bar_node, "foo");
1412

1413
  profile->Delete();
1414 1415 1416
}

static void CallJsFunction2(const v8::FunctionCallbackInfo<v8::Value>& info) {
1417
  v8::base::OS::Print("In CallJsFunction2\n");
1418 1419 1420 1421
  CallJsFunction(info);
}

static const char* js_native1_js_native2_js_test_source =
alph's avatar
alph committed
1422 1423 1424
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
1425
    "function foo() {\n"
alph's avatar
alph committed
1426 1427 1428
    "  var s = 0;\n"
    "  for (var i = 0; i < 1000; i++) s += i * i * i;\n"
    "  return s;\n"
1429 1430 1431 1432 1433
    "}\n"
    "function bar() {\n"
    "  CallJsFunction2(foo);\n"
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1434
    "  CallJsFunction1(bar);\n"
1435
    "}";
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445

// [Top down]:
//    57     0   (root) #0 1
//    55     1    start #16 3
//    54     0      CallJsFunction1 #0 4
//    54     0        bar #16 5
//    54     0          CallJsFunction2 #0 6
//    54    54            foo #16 7
//     2     2    (program) #0 2
TEST(JsNative1JsNative2JsSample) {
alph's avatar
alph committed
1446
  i::FLAG_allow_natives_syntax = true;
1447 1448 1449
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1450

1451
  v8::Local<v8::Function> func1 =
alph's avatar
alph committed
1452 1453 1454
      v8::FunctionTemplate::New(env->GetIsolate(), CallJsFunction)
          ->GetFunction(env)
          .ToLocalChecked();
1455
  func1->SetName(v8_str("CallJsFunction1"));
1456
  env->Global()->Set(env, v8_str("CallJsFunction1"), func1).FromJust();
1457

1458 1459 1460 1461
  v8::Local<v8::Function> func2 =
      v8::FunctionTemplate::New(env->GetIsolate(), CallJsFunction2)
          ->GetFunction(env)
          .ToLocalChecked();
1462
  func2->SetName(v8_str("CallJsFunction2"));
1463
  env->Global()->Set(env, v8_str("CallJsFunction2"), func2).FromJust();
1464

1465
  CompileRun(js_native1_js_native2_js_test_source);
1466

1467 1468 1469
  ProfilerHelper helper(env);
  v8::Local<v8::Function> function = GetFunction(env, "start");
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 1000);
1470 1471

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1472 1473 1474 1475 1476 1477 1478
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node1 =
      GetChild(env, start_node, "CallJsFunction1");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node1, "bar");
  const v8::CpuProfileNode* native_node2 =
      GetChild(env, bar_node, "CallJsFunction2");
  GetChild(env, native_node2, "foo");
1479

1480
  profile->Delete();
1481
}
1482

1483 1484 1485 1486 1487
static const char* js_force_collect_sample_source =
    "function start() {\n"
    "  CallCollectSample();\n"
    "}";

1488
static void CallCollectSample(const v8::FunctionCallbackInfo<v8::Value>& info) {
1489
  v8::CpuProfiler::CollectSample(info.GetIsolate());
1490 1491
}

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
TEST(CollectSampleAPI) {
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
  func->SetName(v8_str("CallCollectSample"));
  env->Global()->Set(env, v8_str("CallCollectSample"), func).FromJust();

  CompileRun(js_force_collect_sample_source);
1505
  ProfilerHelper helper(env);
1506
  v8::Local<v8::Function> function = GetFunction(env, "start");
1507
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 0);
1508 1509

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1510 1511 1512
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  CHECK_LE(1, start_node->GetChildrenCount());
  GetChild(env, start_node, "CallCollectSample");
1513 1514 1515

  profile->Delete();
}
1516

1517
static const char* js_native_js_runtime_multiple_test_source =
alph's avatar
alph committed
1518 1519 1520
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
1521 1522 1523 1524 1525
    "function foo() {\n"
    "  return Math.sin(Math.random());\n"
    "}\n"
    "var bound = foo.bind(this);\n"
    "function bar() {\n"
alph's avatar
alph committed
1526
    "  return bound();\n"
1527 1528
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1529 1530 1531 1532 1533
    "  startProfiling('my_profile');\n"
    "  var startTime = Date.now();\n"
    "  do {\n"
    "    CallJsFunction(bar);\n"
    "  } while (Date.now() - startTime < 200);\n"
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    "}";

// The test check multiple entrances/exits between JS and native code.
//
// [Top down]:
//    (root) #0 1
//      start #16 3
//        CallJsFunction #0 4
//          bar #16 5
//            foo #16 6
//      (program) #0 2
TEST(JsNativeJsRuntimeJsSampleMultiple) {
alph's avatar
alph committed
1546
  i::FLAG_allow_natives_syntax = true;
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallJsFunction);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
  func->SetName(v8_str("CallJsFunction"));
  env->Global()->Set(env, v8_str("CallJsFunction"), func).FromJust();

  CompileRun(js_native_js_runtime_multiple_test_source);

1560 1561 1562
  ProfilerHelper helper(env);
  v8::Local<v8::Function> function = GetFunction(env, "start");
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 500, 500);
1563 1564

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1565 1566 1567 1568 1569
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node =
      GetChild(env, start_node, "CallJsFunction");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node, "bar");
  GetChild(env, bar_node, "foo");
1570 1571 1572 1573

  profile->Delete();
}

1574 1575 1576
static const char* inlining_test_source =
    "%NeverOptimizeFunction(action);\n"
    "%NeverOptimizeFunction(start);\n"
1577
    "level1()\n"
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    "%OptimizeFunctionOnNextCall(level1);\n"
    "%OptimizeFunctionOnNextCall(level2);\n"
    "%OptimizeFunctionOnNextCall(level3);\n"
    "var finish = false;\n"
    "function action(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; ++i) s += i*i*i;\n"
    "  if (finish)\n"
    "    startProfiling('my_profile');\n"
    "  return s;\n"
    "}\n"
    "function level3() { return action(100); }\n"
    "function level2() { return level3() * 2; }\n"
    "function level1() { return level2(); }\n"
    "function start() {\n"
    "  var n = 100;\n"
    "  while (--n)\n"
    "    level1();\n"
    "  finish = true;\n"
    "  level1();\n"
    "}";

// The test check multiple entrances/exits between JS and native code.
//
// [Top down]:
//    (root) #0 1
//      start #16 3
//        level1 #0 4
//          level2 #16 5
//            level3 #16 6
//              action #16 7
//      (program) #0 2
TEST(Inlining) {
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1615
  ProfilerHelper helper(env);
1616 1617 1618 1619 1620

  CompileRun(inlining_test_source);
  v8::Local<v8::Function> function = GetFunction(env, "start");

  v8::Local<v8::String> profile_name = v8_str("my_profile");
1621
  function->Call(env, env->Global(), 0, nullptr).ToLocalChecked();
1622
  v8::CpuProfile* profile = helper.profiler()->StopProfiling(profile_name);
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
  CHECK(profile);
  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* level1_node = GetChild(env, start_node, "level1");
  const v8::CpuProfileNode* level2_node = GetChild(env, level1_node, "level2");
  const v8::CpuProfileNode* level3_node = GetChild(env, level2_node, "level3");
  GetChild(env, level3_node, "action");

  profile->Delete();
}

1637
// [Top down]:
1638 1639 1640
//     0   (root) #0 1
//     2    (program) #0 2
//     3    (idle) #0 3
1641 1642 1643
TEST(IdleTime) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
1644
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
1645

1646
  v8::Local<v8::String> profile_name = v8_str("my_profile");
1647
  cpu_profiler->StartProfiling(profile_name);
1648

1649
  i::Isolate* isolate = CcTest::i_isolate();
1650 1651
  i::ProfilerEventsProcessor* processor =
      reinterpret_cast<i::CpuProfiler*>(cpu_profiler)->processor();
1652

alph's avatar
alph committed
1653
  processor->AddCurrentStack(isolate, true);
1654 1655
  cpu_profiler->SetIdle(true);
  for (int i = 0; i < 3; i++) {
1656
    processor->AddCurrentStack(isolate, true);
1657 1658
  }
  cpu_profiler->SetIdle(false);
1659
  processor->AddCurrentStack(isolate, true);
1660

1661
  v8::CpuProfile* profile = cpu_profiler->StopProfiling(profile_name);
1662
  CHECK(profile);
1663
  // Dump collected profile to have a better diagnostic in case of failure.
1664
  reinterpret_cast<i::CpuProfile*>(profile)->Print();
1665 1666

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1667
  const v8::CpuProfileNode* program_node =
lpy's avatar
lpy committed
1668
      GetChild(env.local(), root, CodeEntry::kProgramEntryName);
alph's avatar
alph committed
1669 1670
  CHECK_EQ(0, program_node->GetChildrenCount());
  CHECK_GE(program_node->GetHitCount(), 2u);
1671

alph's avatar
alph committed
1672
  const v8::CpuProfileNode* idle_node =
lpy's avatar
lpy committed
1673
      GetChild(env.local(), root, CodeEntry::kIdleEntryName);
alph's avatar
alph committed
1674 1675
  CHECK_EQ(0, idle_node->GetChildrenCount());
  CHECK_GE(idle_node->GetHitCount(), 3u);
1676

1677
  profile->Delete();
1678
  cpu_profiler->Dispose();
1679
}
1680

1681 1682 1683 1684
static void CheckFunctionDetails(v8::Isolate* isolate,
                                 const v8::CpuProfileNode* node,
                                 const char* name, const char* script_name,
                                 int script_id, int line, int column) {
1685 1686
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  CHECK(v8_str(name)->Equals(context, node->GetFunctionName()).FromJust());
1687
  CHECK_EQ(0, strcmp(name, node->GetFunctionNameStr()));
1688 1689 1690
  CHECK(v8_str(script_name)
            ->Equals(context, node->GetScriptResourceName())
            .FromJust());
1691
  CHECK_EQ(0, strcmp(script_name, node->GetScriptResourceNameStr()));
1692 1693 1694 1695 1696 1697 1698
  CHECK_EQ(script_id, node->GetScriptId());
  CHECK_EQ(line, node->GetLineNumber());
  CHECK_EQ(column, node->GetColumnNumber());
}


TEST(FunctionDetails) {
alph's avatar
alph committed
1699
  i::FLAG_allow_natives_syntax = true;
1700 1701 1702
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1703
  ProfilerHelper helper(env);
1704

1705
  v8::Local<v8::Script> script_a = CompileWithOrigin(
alph's avatar
alph committed
1706 1707 1708
      "%NeverOptimizeFunction(foo);\n"
      "%NeverOptimizeFunction(bar);\n"
      "    function foo\n() { bar(); }\n"
1709 1710 1711 1712
      " function bar() { startProfiling(); }\n",
      "script_a");
  script_a->Run(env).ToLocalChecked();
  v8::Local<v8::Script> script_b = CompileWithOrigin(
alph's avatar
alph committed
1713 1714
      "%NeverOptimizeFunction(baz);"
      "\n\n   function baz() { foo(); }\n"
1715 1716 1717 1718
      "\n\nbaz();\n"
      "stopProfiling();\n",
      "script_b");
  script_b->Run(env).ToLocalChecked();
1719
  const v8::CpuProfile* profile = i::ProfilerExtension::last_profile;
1720 1721 1722 1723 1724
  const v8::CpuProfileNode* current = profile->GetTopDownRoot();
  reinterpret_cast<ProfileNode*>(
      const_cast<v8::CpuProfileNode*>(current))->Print(0);
  // The tree should look like this:
  //  0   (root) 0 #1
1725
  //  0    "" 19 #2 no reason script_b:1
1726 1727 1728 1729
  //  0      baz 19 #3 TryCatchStatement script_b:3
  //  0        foo 18 #4 TryCatchStatement script_a:2
  //  1          bar 18 #5 no reason script_a:3
  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
1730
  const v8::CpuProfileNode* script = GetChild(env, root, "");
1731
  CheckFunctionDetails(env->GetIsolate(), script, "", "script_b",
1732
                       script_b->GetUnboundScript()->GetId(), 1, 1);
1733
  const v8::CpuProfileNode* baz = GetChild(env, script, "baz");
1734
  CheckFunctionDetails(env->GetIsolate(), baz, "baz", "script_b",
1735
                       script_b->GetUnboundScript()->GetId(), 3, 16);
1736
  const v8::CpuProfileNode* foo = GetChild(env, baz, "foo");
1737
  CheckFunctionDetails(env->GetIsolate(), foo, "foo", "script_a",
alph's avatar
alph committed
1738
                       script_a->GetUnboundScript()->GetId(), 4, 1);
1739
  const v8::CpuProfileNode* bar = GetChild(env, foo, "bar");
1740
  CheckFunctionDetails(env->GetIsolate(), bar, "bar", "script_a",
alph's avatar
alph committed
1741
                       script_a->GetUnboundScript()->GetId(), 5, 14);
1742
}
1743

1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
TEST(FunctionDetailsInlining) {
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
  ProfilerHelper helper(env);

  // alpha is in a_script, beta in b_script. beta is
  // inlined in alpha, but it should be attributed to b_script.

  v8::Local<v8::Script> script_b = CompileWithOrigin(
      "function beta(k) {\n"
      "  let sum = 2;\n"
      "  for(let i = 0; i < k; i ++) {\n"
      "    sum += i;\n"
      "    sum = sum + 'a';\n"
      "  }\n"
      "  return sum;\n"
      "}\n"
      "\n",
      "script_b");

  v8::Local<v8::Script> script_a = CompileWithOrigin(
      "function alpha(p) {\n"
      "  let res = beta(p);\n"
      "  res = res + res;\n"
      "  return res;\n"
      "}\n"
      "let p = 2;\n"
      "\n"
      "\n"
      "// Warm up before profiling or the inlining doesn't happen.\n"
      "p = alpha(p);\n"
      "p = alpha(p);\n"
      "%OptimizeFunctionOnNextCall(alpha);\n"
      "p = alpha(p);\n"
      "\n"
      "\n"
      "startProfiling();\n"
      "for(let i = 0; i < 10000; i++) {\n"
      "  p = alpha(p);\n"
      "}\n"
      "stopProfiling();\n"
      "\n"
      "\n",
      "script_a");

  script_b->Run(env).ToLocalChecked();
  script_a->Run(env).ToLocalChecked();

  const v8::CpuProfile* profile = i::ProfilerExtension::last_profile;
  const v8::CpuProfileNode* current = profile->GetTopDownRoot();
  reinterpret_cast<ProfileNode*>(const_cast<v8::CpuProfileNode*>(current))
      ->Print(0);
  //   The tree should look like this:
  //  0  (root) 0 #1
  //  5    (program) 0 #6
  //  2     14 #2 script_a:1
  //    ;;; deopted at script_id: 14 position: 299 with reason 'Insufficient
  //    type feedback for call'.
  //  1      alpha 14 #4 script_a:1
  //  9        beta 13 #5 script_b:0
  //  0      startProfiling 0 #3

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* script = GetChild(env, root, "");
  CheckFunctionDetails(env->GetIsolate(), script, "", "script_a",
                       script_a->GetUnboundScript()->GetId(), 1, 1);
  const v8::CpuProfileNode* alpha = FindChild(env, script, "alpha");
  // Return early if profiling didn't sample alpha.
  if (!alpha) return;
  CheckFunctionDetails(env->GetIsolate(), alpha, "alpha", "script_a",
                       script_a->GetUnboundScript()->GetId(), 1, 15);
  const v8::CpuProfileNode* beta = FindChild(env, alpha, "beta");
  if (!beta) return;
  CheckFunctionDetails(env->GetIsolate(), beta, "beta", "script_b",
                       script_b->GetUnboundScript()->GetId(), 0, 0);
}
1823 1824

TEST(DontStopOnFinishedProfileDelete) {
1825 1826 1827
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1828

1829
  v8::CpuProfiler* profiler = v8::CpuProfiler::New(env->GetIsolate());
1830
  i::CpuProfiler* iprofiler = reinterpret_cast<i::CpuProfiler*>(profiler);
1831

1832
  CHECK_EQ(0, iprofiler->GetProfilesCount());
1833
  v8::Local<v8::String> outer = v8_str("outer");
1834
  profiler->StartProfiling(outer);
1835
  CHECK_EQ(0, iprofiler->GetProfilesCount());
1836

1837
  v8::Local<v8::String> inner = v8_str("inner");
1838
  profiler->StartProfiling(inner);
1839
  CHECK_EQ(0, iprofiler->GetProfilesCount());
1840

1841
  v8::CpuProfile* inner_profile = profiler->StopProfiling(inner);
1842
  CHECK(inner_profile);
1843
  CHECK_EQ(1, iprofiler->GetProfilesCount());
1844
  inner_profile->Delete();
1845
  inner_profile = nullptr;
1846
  CHECK_EQ(0, iprofiler->GetProfilesCount());
1847

1848
  v8::CpuProfile* outer_profile = profiler->StopProfiling(outer);
1849
  CHECK(outer_profile);
1850
  CHECK_EQ(1, iprofiler->GetProfilesCount());
1851
  outer_profile->Delete();
1852
  outer_profile = nullptr;
1853
  CHECK_EQ(0, iprofiler->GetProfilesCount());
1854
  profiler->Dispose();
1855
}
1856 1857


1858 1859
const char* GetBranchDeoptReason(v8::Local<v8::Context> context,
                                 i::CpuProfile* iprofile, const char* branch[],
1860 1861
                                 int length) {
  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);
1862
  const ProfileNode* iopt_function = nullptr;
1863
  iopt_function = GetSimpleBranch(context, profile, branch, length);
1864
  CHECK_EQ(1U, iopt_function->deopt_infos().size());
1865 1866 1867 1868
  return iopt_function->deopt_infos()[0].deopt_reason;
}


loislo's avatar
loislo committed
1869
// deopt at top function
1870
TEST(CollectDeoptEvents) {
Mythri's avatar
Mythri committed
1871
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
1872 1873 1874 1875
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
1876 1877 1878
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
1879

1880 1881 1882
  const char opt_source[] =
      "function opt_function%d(value, depth) {\n"
      "  if (depth) return opt_function%d(value, depth - 1);\n"
loislo's avatar
loislo committed
1883
      "\n"
1884
      "  return  10 / value;\n"
loislo's avatar
loislo committed
1885
      "}\n"
1886 1887 1888 1889 1890
      "\n";

  for (int i = 0; i < 3; ++i) {
    i::EmbeddedVector<char, sizeof(opt_source) + 100> buffer;
    i::SNPrintF(buffer, opt_source, i, i);
1891 1892 1893 1894
    v8::Script::Compile(env, v8_str(buffer.start()))
        .ToLocalChecked()
        ->Run(env)
        .ToLocalChecked();
1895 1896 1897 1898
  }

  const char* source =
      "startProfiling();\n"
loislo's avatar
loislo committed
1899
      "\n"
1900
      "opt_function0(1, 1);\n"
loislo's avatar
loislo committed
1901
      "\n"
1902 1903 1904 1905 1906
      "%OptimizeFunctionOnNextCall(opt_function0)\n"
      "\n"
      "opt_function0(1, 1);\n"
      "\n"
      "opt_function0(undefined, 1);\n"
loislo's avatar
loislo committed
1907
      "\n"
1908
      "opt_function1(1, 1);\n"
loislo's avatar
loislo committed
1909
      "\n"
1910
      "%OptimizeFunctionOnNextCall(opt_function1)\n"
loislo's avatar
loislo committed
1911
      "\n"
1912
      "opt_function1(1, 1);\n"
loislo's avatar
loislo committed
1913
      "\n"
1914
      "opt_function1(NaN, 1);\n"
loislo's avatar
loislo committed
1915
      "\n"
1916
      "opt_function2(1, 1);\n"
loislo's avatar
loislo committed
1917
      "\n"
1918
      "%OptimizeFunctionOnNextCall(opt_function2)\n"
loislo's avatar
loislo committed
1919
      "\n"
1920 1921 1922
      "opt_function2(1, 1);\n"
      "\n"
      "opt_function2(0, 1);\n"
loislo's avatar
loislo committed
1923 1924 1925 1926
      "\n"
      "stopProfiling();\n"
      "\n";

1927 1928 1929 1930
  v8::Script::Compile(env, v8_str(source))
      .ToLocalChecked()
      ->Run(env)
      .ToLocalChecked();
1931 1932
  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
  /* The expected profile
  [Top down]:
      0  (root) 0 #1
     23     32 #2
      1      opt_function2 31 #7
      1        opt_function2 31 #8
                  ;;; deopted at script_id: 31 position: 106 with reason
  'division by zero'.
      2      opt_function0 29 #3
      4        opt_function0 29 #4
                  ;;; deopted at script_id: 29 position: 108 with reason 'not a
  heap number'.
      0      opt_function1 30 #5
      1        opt_function1 30 #6
                  ;;; deopted at script_id: 30 position: 108 with reason 'lost
  precision or NaN'.
  */

1951 1952
  {
    const char* branch[] = {"", "opt_function0", "opt_function0"};
1953 1954 1955 1956
    const char* deopt_reason =
        GetBranchDeoptReason(env, iprofile, branch, arraysize(branch));
    if (deopt_reason != reason(i::DeoptimizeReason::kNotAHeapNumber) &&
        deopt_reason != reason(i::DeoptimizeReason::kNotASmi)) {
1957
      FATAL("%s", deopt_reason);
1958
    }
1959 1960 1961
  }
  {
    const char* branch[] = {"", "opt_function1", "opt_function1"};
1962
    const char* deopt_reason =
1963
        GetBranchDeoptReason(env, iprofile, branch, arraysize(branch));
1964
    if (deopt_reason != reason(i::DeoptimizeReason::kNaN) &&
1965 1966
        deopt_reason != reason(i::DeoptimizeReason::kLostPrecisionOrNaN) &&
        deopt_reason != reason(i::DeoptimizeReason::kNotASmi)) {
1967
      FATAL("%s", deopt_reason);
1968
    }
1969 1970 1971
  }
  {
    const char* branch[] = {"", "opt_function2", "opt_function2"};
1972
    CHECK_EQ(reason(i::DeoptimizeReason::kDivisionByZero),
1973
             GetBranchDeoptReason(env, iprofile, branch, arraysize(branch)));
1974
  }
1975 1976
  iprofiler->DeleteProfile(iprofile);
}
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989


TEST(SourceLocation) {
  i::FLAG_always_opt = true;
  LocalContext env;
  v8::HandleScope scope(CcTest::isolate());

  const char* source =
      "function CompareStatementWithThis() {\n"
      "  if (this === 1) {}\n"
      "}\n"
      "CompareStatementWithThis();\n";

1990 1991 1992 1993
  v8::Script::Compile(env.local(), v8_str(source))
      .ToLocalChecked()
      ->Run(env.local())
      .ToLocalChecked();
1994
}
1995 1996

static const char* inlined_source =
1997 1998
    "function opt_function(left, right) { var k = left*right; return k + 1; "
    "}\n";
1999 2000 2001 2002 2003
//   0.........1.........2.........3.........4....*....5.........6......*..7


// deopt at the first level inlined function
TEST(DeoptAtFirstLevelInlinedSource) {
Mythri's avatar
Mythri committed
2004
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2005 2006 2007 2008
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
2009 2010 2011
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2012 2013 2014

  //   0.........1.........2.........3.........4.........5.........6.........7
  const char* source =
2015
      "function test(left, right) { return opt_function(left, right); }\n"
2016 2017 2018
      "\n"
      "startProfiling();\n"
      "\n"
2019
      "test(10, 10);\n"
2020 2021 2022
      "\n"
      "%OptimizeFunctionOnNextCall(test)\n"
      "\n"
2023 2024 2025
      "test(10, 10);\n"
      "\n"
      "test(undefined, 1e9);\n"
2026 2027 2028 2029
      "\n"
      "stopProfiling();\n"
      "\n";

2030 2031
  v8::Local<v8::Script> inlined_script = v8_compile(inlined_source);
  inlined_script->Run(env).ToLocalChecked();
2032 2033
  int inlined_script_id = inlined_script->GetUnboundScript()->GetId();

2034 2035
  v8::Local<v8::Script> script = v8_compile(source);
  script->Run(env).ToLocalChecked();
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
  int script_id = script->GetUnboundScript()->GetId();

  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
  /* The expected profile output
  [Top down]:
      0  (root) 0 #1
     10     30 #2
      1      test 30 #3
                ;;; deopted at script_id: 29 position: 45 with reason 'not a
  heap number'.
                ;;;     Inline point: script_id 30 position: 36.
      4        opt_function 29 #4
  */
  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);

  const char* branch[] = {"", "test"};
  const ProfileNode* itest_node =
2054
      GetSimpleBranch(env, profile, branch, arraysize(branch));
2055 2056
  const std::vector<v8::CpuProfileDeoptInfo>& deopt_infos =
      itest_node->deopt_infos();
2057
  CHECK_EQ(1U, deopt_infos.size());
2058

2059
  const v8::CpuProfileDeoptInfo& info = deopt_infos[0];
2060 2061
  CHECK(reason(i::DeoptimizeReason::kNotASmi) == info.deopt_reason ||
        reason(i::DeoptimizeReason::kNotAHeapNumber) == info.deopt_reason);
2062
  CHECK_EQ(2U, info.stack.size());
2063
  CHECK_EQ(inlined_script_id, info.stack[0].script_id);
2064
  CHECK_LE(dist(offset(inlined_source, "*right"), info.stack[0].position), 1);
2065
  CHECK_EQ(script_id, info.stack[1].script_id);
2066
  CHECK_EQ(offset(source, "opt_function(left,"), info.stack[1].position);
2067 2068 2069 2070 2071 2072 2073

  iprofiler->DeleteProfile(iprofile);
}


// deopt at the second level inlined function
TEST(DeoptAtSecondLevelInlinedSource) {
Mythri's avatar
Mythri committed
2074
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2075 2076 2077 2078
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
2079 2080 2081
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2082 2083 2084

  //   0.........1.........2.........3.........4.........5.........6.........7
  const char* source =
2085 2086
      "function test2(left, right) { return opt_function(left, right); }\n"
      "function test1(left, right) { return test2(left, right); } \n"
2087 2088 2089
      "\n"
      "startProfiling();\n"
      "\n"
2090
      "test1(10, 10);\n"
2091 2092 2093
      "\n"
      "%OptimizeFunctionOnNextCall(test1)\n"
      "\n"
2094
      "test1(10, 10);\n"
2095
      "\n"
2096
      "test1(undefined, 1e9);\n"
2097 2098 2099 2100
      "\n"
      "stopProfiling();\n"
      "\n";

2101 2102
  v8::Local<v8::Script> inlined_script = v8_compile(inlined_source);
  inlined_script->Run(env).ToLocalChecked();
2103 2104
  int inlined_script_id = inlined_script->GetUnboundScript()->GetId();

2105 2106
  v8::Local<v8::Script> script = v8_compile(source);
  script->Run(env).ToLocalChecked();
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
  int script_id = script->GetUnboundScript()->GetId();

  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
  /* The expected profile output
  [Top down]:
      0  (root) 0 #1
     11     30 #2
      1      test1 30 #3
                ;;; deopted at script_id: 29 position: 45 with reason 'not a
  heap number'.
                ;;;     Inline point: script_id 30 position: 37.
                ;;;     Inline point: script_id 30 position: 103.
      1        test2 30 #4
      3          opt_function 29 #5
  */

  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);

  const char* branch[] = {"", "test1"};
  const ProfileNode* itest_node =
2128
      GetSimpleBranch(env, profile, branch, arraysize(branch));
2129 2130
  const std::vector<v8::CpuProfileDeoptInfo>& deopt_infos =
      itest_node->deopt_infos();
2131
  CHECK_EQ(1U, deopt_infos.size());
2132

2133
  const v8::CpuProfileDeoptInfo info = deopt_infos[0];
2134 2135
  CHECK(reason(i::DeoptimizeReason::kNotASmi) == info.deopt_reason ||
        reason(i::DeoptimizeReason::kNotAHeapNumber) == info.deopt_reason);
2136
  CHECK_EQ(3U, info.stack.size());
2137
  CHECK_EQ(inlined_script_id, info.stack[0].script_id);
2138
  CHECK_LE(dist(offset(inlined_source, "*right"), info.stack[0].position), 1);
2139
  CHECK_EQ(script_id, info.stack[1].script_id);
2140 2141
  CHECK_EQ(offset(source, "opt_function(left,"), info.stack[1].position);
  CHECK_EQ(offset(source, "test2(left, right);"), info.stack[2].position);
2142 2143 2144 2145 2146 2147 2148

  iprofiler->DeleteProfile(iprofile);
}


// deopt in untracked function
TEST(DeoptUntrackedFunction) {
Mythri's avatar
Mythri committed
2149
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2150 2151 2152 2153
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);
2154 2155 2156
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2157 2158 2159 2160 2161

  //   0.........1.........2.........3.........4.........5.........6.........7
  const char* source =
      "function test(left, right) { return opt_function(left, right); }\n"
      "\n"
2162
      "test(10, 10);\n"
2163 2164 2165
      "\n"
      "%OptimizeFunctionOnNextCall(test)\n"
      "\n"
2166
      "test(10, 10);\n"
2167 2168 2169
      "\n"
      "startProfiling();\n"  // profiler started after compilation.
      "\n"
2170
      "test(undefined, 10);\n"
2171 2172 2173 2174
      "\n"
      "stopProfiling();\n"
      "\n";

2175 2176
  v8::Local<v8::Script> inlined_script = v8_compile(inlined_source);
  inlined_script->Run(env).ToLocalChecked();
2177

2178 2179
  v8::Local<v8::Script> script = v8_compile(source);
  script->Run(env).ToLocalChecked();
2180 2181 2182 2183 2184 2185 2186

  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);

  const char* branch[] = {"", "test"};
  const ProfileNode* itest_node =
2187
      GetSimpleBranch(env, profile, branch, arraysize(branch));
2188
  CHECK_EQ(0U, itest_node->deopt_infos().size());
2189 2190 2191

  iprofiler->DeleteProfile(iprofile);
}
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201

using v8::platform::tracing::TraceBuffer;
using v8::platform::tracing::TraceConfig;
using v8::platform::tracing::TraceObject;

namespace {

class CpuProfileEventChecker : public v8::platform::tracing::TraceWriter {
 public:
  void AppendTraceEvent(TraceObject* trace_event) override {
2202 2203
    if (trace_event->name() != std::string("Profile") &&
        trace_event->name() != std::string("ProfileChunk"))
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
      return;
    CHECK(!profile_id_ || trace_event->id() == profile_id_);
    CHECK_EQ(1, trace_event->num_args());
    CHECK_EQ(TRACE_VALUE_TYPE_CONVERTABLE, trace_event->arg_types()[0]);
    profile_id_ = trace_event->id();
    v8::ConvertableToTraceFormat* arg =
        trace_event->arg_convertables()[0].get();
    arg->AppendAsTraceFormat(&result_json_);
  }
  void Flush() override {}

  std::string result_json() const { return result_json_; }

 private:
  std::string result_json_;
  uint64_t profile_id_ = 0;
};

}  // namespace

TEST(TracingCpuProfiler) {
  v8::Platform* old_platform = i::V8::GetCurrentPlatform();
2226 2227 2228
  std::unique_ptr<v8::Platform> default_platform =
      v8::platform::NewDefaultPlatform();
  i::V8::SetPlatformForTesting(default_platform.get());
2229

2230 2231 2232 2233
  auto tracing = base::make_unique<v8::platform::tracing::TracingController>();
  v8::platform::tracing::TracingController* tracing_controller = tracing.get();
  static_cast<v8::platform::DefaultPlatform*>(default_platform.get())
      ->SetTracingController(std::move(tracing));
2234 2235 2236 2237

  CpuProfileEventChecker* event_checker = new CpuProfileEventChecker();
  TraceBuffer* ring_buffer =
      TraceBuffer::CreateTraceBufferRingBuffer(1, event_checker);
2238
  tracing_controller->Initialize(ring_buffer);
2239 2240 2241 2242 2243 2244 2245
  TraceConfig* trace_config = new TraceConfig();
  trace_config->AddIncludedCategory(
      TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler"));

  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  {
2246
    tracing_controller->StartTracing(trace_config);
2247 2248
    auto profiler = v8::TracingCpuProfiler::Create(env->GetIsolate());
    CompileRun("function foo() { } foo();");
2249
    tracing_controller->StopTracing();
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
    CompileRun("function bar() { } bar();");
  }

  const char* profile_checker =
      "function checkProfile(profile) {\n"
      "  if (typeof profile['startTime'] !== 'number') return 'startTime';\n"
      "  return '';\n"
      "}\n"
      "checkProfile(";
  std::string profile_json = event_checker->result_json();
  CHECK_LT(0u, profile_json.length());
  printf("Profile JSON: %s\n", profile_json.c_str());
  std::string code = profile_checker + profile_json + ")";
  v8::Local<v8::Value> result =
      CompileRunChecked(CcTest::isolate(), code.c_str());
2265
  v8::String::Utf8Value value(CcTest::isolate(), result);
2266 2267 2268 2269 2270
  printf("Check result: %*s\n", value.length(), *value);
  CHECK_EQ(0, value.length());

  i::V8::SetPlatformForTesting(old_platform);
}
2271

2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
TEST(Issue763073) {
  class AllowNativesSyntax {
   public:
    AllowNativesSyntax()
        : allow_natives_syntax_(i::FLAG_allow_natives_syntax),
          trace_deopt_(i::FLAG_trace_deopt) {
      i::FLAG_allow_natives_syntax = true;
      i::FLAG_trace_deopt = true;
    }

    ~AllowNativesSyntax() {
      i::FLAG_allow_natives_syntax = allow_natives_syntax_;
      i::FLAG_trace_deopt = trace_deopt_;
    }

   private:
    bool allow_natives_syntax_;
    bool trace_deopt_;
  };

  AllowNativesSyntax allow_natives_syntax_scope;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  CompileRun(
      "function f() { return function g(x) { }; }"
      // Create first closure, optimize it, and deoptimize it.
      "var g = f();"
      "g(1);"
      "%OptimizeFunctionOnNextCall(g);"
      "g(1);"
      "%DeoptimizeFunction(g);"
      // Create second closure, and optimize it. This will create another
      // optimized code object and put in the (shared) type feedback vector.
      "var h = f();"
      "h(1);"
      "%OptimizeFunctionOnNextCall(h);"
      "h(1);");

  // Start profiling.
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
  v8::Local<v8::String> profile_name = v8_str("test");

  // Here we test that the heap iteration upon profiling start is not
  // confused by having a deoptimized code object for a closure while
  // having a different optimized code object in the type feedback vector.
  cpu_profiler->StartProfiling(profile_name);
  v8::CpuProfile* p = cpu_profiler->StopProfiling(profile_name);
  p->Delete();
  cpu_profiler->Dispose();
}

2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
static const char* js_collect_sample_api_source =
    "%NeverOptimizeFunction(start);\n"
    "function start() {\n"
    "  CallStaticCollectSample();\n"
    "}";

static void CallStaticCollectSample(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::CpuProfiler::CollectSample(info.GetIsolate());
}

TEST(StaticCollectSampleAPI) {
  i::FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallStaticCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  func->SetName(v8_str("CallStaticCollectSample"));
  env->Global()
      ->Set(env.local(), v8_str("CallStaticCollectSample"), func)
      .FromJust();

  CompileRun(js_collect_sample_api_source);
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");

  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 100);

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "CallStaticCollectSample");

  profile->Delete();
}

2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
TEST(CodeEntriesMemoryLeak) {
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);

  std::string source = "function start() {}\n";
  for (int i = 0; i < 1000; ++i) {
    source += "function foo" + std::to_string(i) + "() { return " +
              std::to_string(i) +
              "; }\n"
              "foo" +
              std::to_string(i) + "();\n";
  }
  CompileRun(source.c_str());
  v8::Local<v8::Function> function = GetFunction(env, "start");

  ProfilerHelper helper(env);

  for (int j = 0; j < 100; ++j) {
    v8::CpuProfile* profile = helper.Run(function, nullptr, 0);
    profile->Delete();
  }
  ProfilerListener* profiler_listener =
      CcTest::i_isolate()->logger()->profiler_listener();

  CHECK_GE(10000ul, profiler_listener->entries_count_for_test());
}

2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
TEST(NativeFrameStackTrace) {
  // A test for issue https://crbug.com/768540
  // When a sample lands in a native function which has not EXIT frame
  // stack frame iterator used to bail out and produce an empty stack trace.
  // The source code below makes v8 call the
  // v8::internal::StringTable::LookupStringIfExists_NoAllocate native function
  // without producing an EXIT frame.
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext(PROFILER_EXTENSION);
  v8::Context::Scope context_scope(env);

  const char* source = R"(
      function jsFunction() {
        var s = {};
        for (var i = 0; i < 1e4; ++i) {
          for (var j = 0; j < 100; j++) {
            s['item' + j] = 'alph';
          }
        }
      })";

  CompileRun(source);
  v8::Local<v8::Function> function = GetFunction(env, "jsFunction");

  ProfilerHelper helper(env);

  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 100, 0, true);

  // Count the fraction of samples landing in 'jsFunction' (valid stack)
  // vs '(program)' (no stack captured).
  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* js_function = FindChild(root, "jsFunction");
  const v8::CpuProfileNode* program = FindChild(root, "(program)");
  if (program) {
    unsigned js_function_samples = TotalHitCount(js_function);
    unsigned program_samples = TotalHitCount(program);
    double valid_samples_ratio =
        1. * js_function_samples / (js_function_samples + program_samples);
    i::PrintF("Ratio: %f\n", valid_samples_ratio);
    // TODO(alph): Investigate other causes of dropped frames. The ratio
    // should be close to 99%.
    CHECK_GE(valid_samples_ratio, 0.3);
  }

  profile->Delete();
}

2437 2438 2439
}  // namespace test_cpu_profiler
}  // namespace internal
}  // namespace v8