profile.mjs 33.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Copyright 2009 the V8 project authors. All rights reserved.
// 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.

28
import { CodeMap, CodeEntry } from "./codemap.mjs";
29 30
import { ConsArray } from "./consarray.mjs";

31
// Used to associate log entries with source positions in scripts.
32 33 34 35 36 37 38 39
// TODO: move to separate modules
export class SourcePosition {
  constructor(script, line, column) {
    this.script = script;
    this.line = line;
    this.column = column;
    this.entries = [];
  }
40

41 42 43
  addEntry(entry) {
    this.entries.push(entry);
  }
44 45

  toString() {
46
    return `${this.script.name}:${this.line}:${this.column}`;
47 48 49 50 51
  }

  toStringLong() {
    return this.toString();
  }
52 53 54
}

export class Script {
55 56 57 58
  name;
  source;
  // Map<line, Map<column, SourcePosition>>
  lineToColumn = new Map();
59
  _entries = [];
60 61

  constructor(id) {
62
    this.id = id;
63 64 65 66
    this.sourcePositions = [];
  }

  update(name, source) {
67 68 69 70
    this.name = name;
    this.source = source;
  }

71 72 73 74
  get length() {
    return this.source.length;
  }

75 76 77 78
  get entries() {
    return this._entries;
  }

79 80 81
  addSourcePosition(line, column, entry) {
    let sourcePosition = this.lineToColumn.get(line)?.get(column);
    if (sourcePosition === undefined) {
82
      sourcePosition = new SourcePosition(this, line, column,)
83
      this._addSourcePosition(line, column, sourcePosition);
84 85
    }
    sourcePosition.addEntry(entry);
86
    this._entries.push(entry);
87 88 89
    return sourcePosition;
  }

90
  _addSourcePosition(line, column, sourcePosition) {
91 92 93 94 95 96 97 98 99 100
    let columnToSourcePosition;
    if (this.lineToColumn.has(line)) {
      columnToSourcePosition = this.lineToColumn.get(line);
    } else {
      columnToSourcePosition = new Map();
      this.lineToColumn.set(line, columnToSourcePosition);
    }
    this.sourcePositions.push(sourcePosition);
    columnToSourcePosition.set(column, sourcePosition);
  }
101

102
  toString() {
103
    return `Script(${this.id}): ${this.name}`;
104
  }
105

106 107 108
  toStringLong() {
    return this.source;
  }
109 110
}

111

112
class SourceInfo {
113 114 115 116 117 118 119
  script;
  start;
  end;
  positions;
  inlined;
  fns;
  disassemble;
120 121

  setSourcePositionInfo(script, startPos, endPos, sourcePositionTable, inliningPositions, inlinedFunctions) {
122 123 124 125 126 127 128
    this.script = script;
    this.start = startPos;
    this.end = endPos;
    this.positions = sourcePositionTable;
    this.inlined = inliningPositions;
    this.fns = inlinedFunctions;
  }
129 130 131 132

  setDisassemble(code) {
    this.disassemble = code;
  }
133 134 135 136

  getSourceCode() {
    return this.script.source?.substring(this.start, this.end);
  }
137 138
}

139 140 141 142 143 144
/**
 * Creates a profile object for processing profiling-related events
 * and calculating function execution times.
 *
 * @constructor
 */
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
export class Profile {
  codeMap_ = new CodeMap();
  topDownTree_ = new CallTree();
  bottomUpTree_ = new CallTree();
  c_entries_ = {};
  ticks_ = [];
  scripts_ = [];
  urlToScript_ = new Map();

  /**
   * Returns whether a function with the specified name must be skipped.
   * Should be overriden by subclasses.
   *
   * @param {string} name Function name.
   */
  skipThisFunction(name) {
    return false;
  }
163

164 165 166 167 168 169 170 171 172 173 174
  /**
   * Enum for profiler operations that involve looking up existing
   * code entries.
   *
   * @enum {number}
   */
  static Operation = {
    MOVE: 0,
    DELETE: 1,
    TICK: 2
  }
175

176 177 178 179 180 181 182
  /**
   * Enum for code state regarding its dynamic optimization.
   *
   * @enum {number}
   */
  static CodeState = {
    COMPILED: 0,
183
    IGNITION: 1,
184
    BASELINE: 2,
185 186 187
    NATIVE_CONTEXT_INDEPENDENT: 3,
    TURBOPROP: 4,
    TURBOFAN: 5,
188 189 190 191 192 193 194 195 196 197 198
  }

  /**
   * Parser for dynamic code optimization state.
   */
  static parseState(s) {
    switch (s) {
      case '':
        return this.CodeState.COMPILED;
      case '~':
        return this.CodeState.IGNITION;
199
      case '^':
200
        return this.CodeState.BASELINE;
201 202
      case '-':
        return this.CodeState.NATIVE_CONTEXT_INDEPENDENT;
203
      case '+':
204 205 206 207 208
        return this.CodeState.TURBOPROP;
      case '*':
        return this.CodeState.TURBOFAN;
    }
    throw new Error(`unknown code state: ${s}`);
209
  }
210

211 212 213 214 215
  static getKindFromState(state) {
    if (state === this.CodeState.COMPILED) {
      return "Builtin";
    } else if (state === this.CodeState.IGNITION) {
      return "Unopt";
216 217
    } else if (state === this.CodeState.BASELINE) {
      return "Baseline";
218 219 220 221 222 223 224 225 226 227
    } else if (state === this.CodeState.NATIVE_CONTEXT_INDEPENDENT) {
      return "NCI";
    } else if (state === this.CodeState.TURBOPROP) {
      return "Turboprop";
    } else if (state === this.CodeState.TURBOFAN) {
      return "Opt";
    }
    throw new Error(`unknown code state: ${state}`);
  }

228 229 230 231 232 233 234 235 236 237 238 239
  /**
   * Called whenever the specified operation has failed finding a function
   * containing the specified address. Should be overriden by subclasses.
   * See the Profile.Operation enum for the list of
   * possible operations.
   *
   * @param {number} operation Operation.
   * @param {number} addr Address of the unknown code.
   * @param {number} opt_stackPos If an unknown address is encountered
   *     during stack strace processing, specifies a position of the frame
   *     containing the address.
   */
240
  handleUnknownCode(operation, addr, opt_stackPos) { }
241 242 243 244 245 246 247 248 249

  /**
   * Registers a library.
   *
   * @param {string} name Code entry name.
   * @param {number} startAddr Starting address.
   * @param {number} endAddr Ending address.
   */
  addLibrary(name, startAddr, endAddr) {
250
    const entry = new CodeEntry(endAddr - startAddr, name, 'SHARED_LIB');
251 252 253
    this.codeMap_.addLibrary(startAddr, entry);
    return entry;
  }
254

255 256 257 258 259 260 261 262
  /**
   * Registers statically compiled code entry.
   *
   * @param {string} name Code entry name.
   * @param {number} startAddr Starting address.
   * @param {number} endAddr Ending address.
   */
  addStaticCode(name, startAddr, endAddr) {
263
    const entry = new CodeEntry(endAddr - startAddr, name, 'CPP');
264 265 266
    this.codeMap_.addStaticCode(startAddr, entry);
    return entry;
  }
267

268 269 270 271 272 273 274 275 276
  /**
   * Registers dynamic (JIT-compiled) code entry.
   *
   * @param {string} type Code entry type.
   * @param {string} name Code entry name.
   * @param {number} start Starting address.
   * @param {number} size Code entry size.
   */
  addCode(type, name, timestamp, start, size) {
277
    const entry = new DynamicCodeEntry(size, type, name);
278 279 280
    this.codeMap_.addCode(start, entry);
    return entry;
  }
281

282 283 284 285 286 287 288 289 290 291 292 293 294
  /**
   * Registers dynamic (JIT-compiled) code entry.
   *
   * @param {string} type Code entry type.
   * @param {string} name Code entry name.
   * @param {number} start Starting address.
   * @param {number} size Code entry size.
   * @param {number} funcAddr Shared function object address.
   * @param {Profile.CodeState} state Optimization state.
   */
  addFuncCode(type, name, timestamp, start, size, funcAddr, state) {
    // As code and functions are in the same address space,
    // it is safe to put them in a single code map.
295
    let func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
296 297 298 299 300 301 302
    if (!func) {
      func = new FunctionEntry(name);
      this.codeMap_.addCode(funcAddr, func);
    } else if (func.name !== name) {
      // Function object has been overwritten with a new one.
      func.name = name;
    }
303
    let entry = this.codeMap_.findDynamicEntryByStartAddress(start);
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    if (entry) {
      if (entry.size === size && entry.func === func) {
        // Entry state has changed.
        entry.state = state;
      } else {
        this.codeMap_.deleteCode(start);
        entry = null;
      }
    }
    if (!entry) {
      entry = new DynamicFuncCodeEntry(size, type, func, state);
      this.codeMap_.addCode(start, entry);
    }
    return entry;
  }
319

320 321 322 323 324 325 326 327 328 329 330 331 332
  /**
   * Reports about moving of a dynamic code entry.
   *
   * @param {number} from Current code entry address.
   * @param {number} to New code entry address.
   */
  moveCode(from, to) {
    try {
      this.codeMap_.moveCode(from, to);
    } catch (e) {
      this.handleUnknownCode(Profile.Operation.MOVE, from);
    }
  }
333

334
  deoptCode(timestamp, code, inliningId, scriptOffset, bailoutType,
335
    sourcePositionText, deoptReasonText) {
336
  }
337 338 339 340 341 342 343 344

  /**
   * Reports about deletion of a dynamic code entry.
   *
   * @param {number} start Starting address.
   */
  deleteCode(start) {
    try {
345
      this.codeMap_.deleteCode(start);
346 347
    } catch (e) {
      this.handleUnknownCode(Profile.Operation.DELETE, start);
348 349 350
    }
  }

351 352 353
  /**
   * Adds source positions for given code.
   */
354
  addSourcePositions(start, scriptId, startPos, endPos, sourcePositionTable,
355
        inliningPositions, inlinedFunctions) {
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    const script = this.getOrCreateScript(scriptId);
    const entry = this.codeMap_.findDynamicEntryByStartAddress(start);
    if (!entry) return;
    // Resolve the inlined functions list.
    if (inlinedFunctions.length > 0) {
      inlinedFunctions = inlinedFunctions.substring(1).split("S");
      for (let i = 0; i < inlinedFunctions.length; i++) {
        const funcAddr = parseInt(inlinedFunctions[i]);
        const func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
        if (!func || func.funcId === undefined) {
          // TODO: fix
          console.warn(`Could not find function ${inlinedFunctions[i]}`);
          inlinedFunctions[i] = null;
        } else {
          inlinedFunctions[i] = func.funcId;
        }
      }
    } else {
      inlinedFunctions = [];
    }

377
    this.getOrCreateSourceInfo(entry).setSourcePositionInfo(
378 379
      script, startPos, endPos, sourcePositionTable, inliningPositions,
      inlinedFunctions);
380 381
  }

382 383 384 385 386 387 388 389 390 391
  addDisassemble(start, kind, disassemble) {
    const entry = this.codeMap_.findDynamicEntryByStartAddress(start);
    if (!entry) return;
    this.getOrCreateSourceInfo(entry).setDisassemble(disassemble);
  }

  getOrCreateSourceInfo(entry) {
    return entry.source ?? (entry.source = new SourceInfo());
  }

392
  addScriptSource(id, url, source) {
393 394
    const script = this.getOrCreateScript(id);
    script.update(url, source);
395
    this.urlToScript_.set(url, script);
396 397
  }

398 399 400 401 402 403 404 405 406
  getOrCreateScript(id) {
    let script = this.scripts_[id];
    if (!script) {
      script = new Script(id);
      this.scripts_[id] = script;
    }
    return script;
  }

407 408
  getScript(url) {
    return this.urlToScript_.get(url);
409 410
  }

411 412 413 414 415 416 417 418 419 420 421
  /**
   * Reports about moving of a dynamic code entry.
   *
   * @param {number} from Current code entry address.
   * @param {number} to New code entry address.
   */
  moveFunc(from, to) {
    if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
      this.codeMap_.moveCode(from, to);
    }
  }
422

423 424 425 426 427 428 429 430
  /**
   * Retrieves a code entry by an address.
   *
   * @param {number} addr Entry address.
   */
  findEntry(addr) {
    return this.codeMap_.findEntry(addr);
  }
431

432 433 434 435 436 437 438
  /**
   * Records a tick event. Stack must contain a sequence of
   * addresses starting with the program counter value.
   *
   * @param {Array<number>} stack Stack sample.
   */
  recordTick(time_ns, vmState, stack) {
439
    const processedStack = this.resolveAndFilterFuncs_(stack);
440 441 442 443
    this.bottomUpTree_.addPath(processedStack);
    processedStack.reverse();
    this.topDownTree_.addPath(processedStack);
  }
444

445 446 447 448 449 450 451
  /**
   * Translates addresses into function names and filters unneeded
   * functions.
   *
   * @param {Array<number>} stack Stack sample.
   */
  resolveAndFilterFuncs_(stack) {
452 453 454 455 456
    const result = [];
    let last_seen_c_function = '';
    let look_for_first_c_function = false;
    for (let i = 0; i < stack.length; ++i) {
      const entry = this.codeMap_.findEntry(stack[i]);
457
      if (entry) {
458
        const name = entry.getName();
459 460 461 462 463 464 465 466 467 468 469 470
        if (i === 0 && (entry.type === 'CPP' || entry.type === 'SHARED_LIB')) {
          look_for_first_c_function = true;
        }
        if (look_for_first_c_function && entry.type === 'CPP') {
          last_seen_c_function = name;
        }
        if (!this.skipThisFunction(name)) {
          result.push(name);
        }
      } else {
        this.handleUnknownCode(Profile.Operation.TICK, stack[i], i);
        if (i === 0) result.push("UNKNOWN");
471
      }
472 473 474 475 476 477 478 479 480
      if (look_for_first_c_function &&
        i > 0 &&
        (!entry || entry.type !== 'CPP') &&
        last_seen_c_function !== '') {
        if (this.c_entries_[last_seen_c_function] === undefined) {
          this.c_entries_[last_seen_c_function] = 0;
        }
        this.c_entries_[last_seen_c_function]++;
        look_for_first_c_function = false;  // Found it, we're done.
481 482
      }
    }
483
    return result;
484 485
  }

486 487 488 489 490 491 492 493
  /**
   * Performs a BF traversal of the top down call graph.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  traverseTopDownTree(f) {
    this.topDownTree_.traverse(f);
  }
494

495 496 497 498 499 500 501 502
  /**
   * Performs a BF traversal of the bottom up call graph.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  traverseBottomUpTree(f) {
    this.bottomUpTree_.traverse(f);
  }
503

504 505 506 507 508 509 510 511 512
  /**
   * Calculates a top down profile for a node with the specified label.
   * If no name specified, returns the whole top down calls tree.
   *
   * @param {string} opt_label Node label.
   */
  getTopDownProfile(opt_label) {
    return this.getTreeProfile_(this.topDownTree_, opt_label);
  }
513

514 515 516 517 518 519 520 521
  /**
   * Calculates a bottom up profile for a node with the specified label.
   * If no name specified, returns the whole bottom up calls tree.
   *
   * @param {string} opt_label Node label.
   */
  getBottomUpProfile(opt_label) {
    return this.getTreeProfile_(this.bottomUpTree_, opt_label);
522 523
  }

524 525 526 527 528 529 530 531 532 533 534
  /**
   * Helper function for calculating a tree profile.
   *
   * @param {Profile.CallTree} tree Call tree.
   * @param {string} opt_label Node label.
   */
  getTreeProfile_(tree, opt_label) {
    if (!opt_label) {
      tree.computeTotalWeights();
      return tree;
    } else {
535
      const subTree = tree.cloneSubtree(opt_label);
536 537 538 539
      subTree.computeTotalWeights();
      return subTree;
    }
  }
540

541 542 543 544 545 546 547
  /**
   * Calculates a flat profile of callees starting from a node with
   * the specified label. If no name specified, starts from the root.
   *
   * @param {string} opt_label Starting node label.
   */
  getFlatProfile(opt_label) {
548 549 550
    const counters = new CallTree();
    const rootLabel = opt_label || CallTree.ROOT_NODE_LABEL;
    const precs = {};
551
    precs[rootLabel] = 0;
552
    const root = counters.findOrAddChild(rootLabel);
553 554 555 556 557 558 559

    this.topDownTree_.computeTotalWeights();
    this.topDownTree_.traverseInDepth(
      function onEnter(node) {
        if (!(node.label in precs)) {
          precs[node.label] = 0;
        }
560
        const nodeLabelIsRootLabel = node.label == rootLabel;
561 562 563 564 565
        if (nodeLabelIsRootLabel || precs[rootLabel] > 0) {
          if (precs[rootLabel] == 0) {
            root.selfWeight += node.selfWeight;
            root.totalWeight += node.totalWeight;
          } else {
566
            const rec = root.findOrAddChild(node.label);
567 568 569 570
            rec.selfWeight += node.selfWeight;
            if (nodeLabelIsRootLabel || precs[node.label] == 0) {
              rec.totalWeight += node.totalWeight;
            }
571
          }
572
          precs[node.label]++;
573
        }
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
      },
      function onExit(node) {
        if (node.label == rootLabel || precs[rootLabel] > 0) {
          precs[node.label]--;
        }
      },
      null);

    if (!opt_label) {
      // If we have created a flat profile for the whole program, we don't
      // need an explicit root in it. Thus, replace the counters tree
      // root with the node corresponding to the whole program.
      counters.root_ = root;
    } else {
      // Propagate weights so percents can be calculated correctly.
      counters.getRoot().selfWeight = root.selfWeight;
      counters.getRoot().totalWeight = root.totalWeight;
    }
    return counters;
593 594
  }

595
  getCEntryProfile() {
596 597 598 599
    const result = [new CEntryNode("TOTAL", 0)];
    let total_ticks = 0;
    for (let f in this.c_entries_) {
      const ticks = this.c_entries_[f];
600 601 602 603
      total_ticks += ticks;
      result.push(new CEntryNode(f, ticks));
    }
    result[0].ticks = total_ticks;  // Sorting will keep this at index 0.
604
    result.sort((n1, n2) => n2.ticks - n1.ticks || (n2.name < n1.name ? -1 : 1));
605
    return result;
606 607 608
  }


609 610 611 612
  /**
   * Cleans up function entries that are not referenced by code entries.
   */
  cleanUpFuncEntries() {
613 614 615
    const referencedFuncEntries = [];
    const entries = this.codeMap_.getAllDynamicEntriesWithAddresses();
    for (let i = 0, l = entries.length; i < l; ++i) {
616 617 618
      if (entries[i][1].constructor === FunctionEntry) {
        entries[i][1].used = false;
      }
619
    }
620
    for (let i = 0, l = entries.length; i < l; ++i) {
621 622 623
      if ("func" in entries[i][1]) {
        entries[i][1].func.used = true;
      }
624
    }
625
    for (let i = 0, l = entries.length; i < l; ++i) {
626 627 628 629
      if (entries[i][1].constructor === FunctionEntry &&
        !entries[i][1].used) {
        this.codeMap_.deleteCode(entries[i][0]);
      }
630 631
    }
  }
632 633 634 635 636 637 638 639
}

class CEntryNode {
  constructor(name, ticks) {
    this.name = name;
    this.ticks = ticks;
  }
}
640 641 642 643 644 645 646 647 648 649


/**
 * Creates a dynamic code entry.
 *
 * @param {number} size Code size.
 * @param {string} type Code type.
 * @param {string} name Function name.
 * @constructor
 */
650 651 652 653
class DynamicCodeEntry extends CodeEntry {
  constructor(size, type, name) {
    super(size, name, type);
  }
654

655 656 657
  getName() {
    return this.type + ': ' + this.name;
  }
658

659 660 661 662 663 664
  /**
   * Returns raw node name (without type decoration).
   */
  getRawName() {
    return this.name;
  }
665

666 667 668
  isJSFunction() {
    return false;
  }
669

670 671 672 673
  toString() {
    return this.getName() + ': ' + this.size.toString(16);
  }
}
674 675 676 677 678 679 680


/**
 * Creates a dynamic code entry.
 *
 * @param {number} size Code size.
 * @param {string} type Code type.
681
 * @param {FunctionEntry} func Shared function entry.
682 683 684
 * @param {Profile.CodeState} state Code optimization state.
 * @constructor
 */
685 686 687 688
class DynamicFuncCodeEntry extends CodeEntry {
  constructor(size, type, func, state) {
    super(size, '', type);
    this.func = func;
689
    func.addDynamicCode(this);
690 691
    this.state = state;
  }
692

693 694 695 696
  get functionName() {
    return this.func.functionName;
  }

697 698 699 700
  getSourceCode() {
    return this.source?.getSourceCode();
  }

701
  static STATE_PREFIX = ["", "~", "^", "-", "+", "*"];
702 703 704
  getState() {
    return DynamicFuncCodeEntry.STATE_PREFIX[this.state];
  }
705

706
  getName() {
707
    const name = this.func.getName();
708 709
    return this.type + ': ' + this.getState() + name;
  }
710

711 712 713 714 715 716
  /**
   * Returns raw node name (without type decoration).
   */
  getRawName() {
    return this.func.getName();
  }
717

718 719 720
  isJSFunction() {
    return true;
  }
721

722 723 724 725
  toString() {
    return this.getName() + ': ' + this.size.toString(16);
  }
}
726 727 728 729 730 731 732

/**
 * Creates a shared function object entry.
 *
 * @param {string} name Function name.
 * @constructor
 */
733
class FunctionEntry extends CodeEntry {
734

735 736 737
  // Contains the list of generated code for this function.
  _codeEntries = new Set();

738 739
  constructor(name) {
    super(0, name);
740 741
    const index = name.lastIndexOf(' ');
    this.functionName = 1 <= index ? name.substring(0, index) : '<anonymous>';
742
  }
743

744 745 746 747 748 749 750 751 752 753 754 755
  addDynamicCode(code) {
    if (code.func != this) {
      throw new Error("Adding dynamic code to wrong function");
    }
    this._codeEntries.add(code);
  }

  getSourceCode() {
    // All code entries should map to the same source positions.
    return this._codeEntries.values().next().value.getSourceCode();
  }

756 757 758 759
  /**
   * Returns node name.
   */
  getName() {
760
    let name = this.name;
761
    if (name.length == 0) {
762
      return '<anonymous>';
763 764
    } else if (name.charAt(0) == ' ') {
      // An anonymous function with location: " aaa.js:10".
765
      return `<anonymous>${name}`;
766 767 768 769
    }
    return name;
  }
}
770 771 772 773 774 775

/**
 * Constructs a call graph.
 *
 * @constructor
 */
776 777 778 779 780 781 782 783 784 785 786 787 788 789
class CallTree {
  root_ = new CallTreeNode(CallTree.ROOT_NODE_LABEL);
  totalsComputed_ = false;

  /**
   * The label of the root node.
   */
  static ROOT_NODE_LABEL = '';

  /**
   * Returns the tree root.
   */
  getRoot() {
    return this.root_;
790 791
  }

792 793 794 795 796 797 798 799
  /**
   * Adds the specified call path, constructing nodes as necessary.
   *
   * @param {Array<string>} path Call path.
   */
  addPath(path) {
    if (path.length == 0) {
      return;
800
    }
801 802
    let curr = this.root_;
    for (let i = 0; i < path.length; ++i) {
803 804 805 806
      curr = curr.findOrAddChild(path[i]);
    }
    curr.selfWeight++;
    this.totalsComputed_ = false;
807 808
  }

809 810 811 812 813 814 815 816 817 818
  /**
   * Finds an immediate child of the specified parent with the specified
   * label, creates a child node if necessary. If a parent node isn't
   * specified, uses tree root.
   *
   * @param {string} label Child node label.
   */
  findOrAddChild(label) {
    return this.root_.findOrAddChild(label);
  }
819

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
  /**
   * Creates a subtree by cloning and merging all subtrees rooted at nodes
   * with a given label. E.g. cloning the following call tree on label 'A'
   * will give the following result:
   *
   *           <A>--<B>                                     <B>
   *          /                                            /
   *     <root>             == clone on 'A' ==>  <root>--<A>
   *          \                                            \
   *           <C>--<A>--<D>                                <D>
   *
   * And <A>'s selfWeight will be the sum of selfWeights of <A>'s from the
   * source call tree.
   *
   * @param {string} label The label of the new root node.
   */
  cloneSubtree(label) {
837
    const subTree = new CallTree();
838 839 840 841
    this.traverse((node, parent) => {
      if (!parent && node.label != label) {
        return null;
      }
842
      const child = (parent ? parent : subTree).findOrAddChild(node.label);
843 844
      child.selfWeight += node.selfWeight;
      return child;
845
    });
846
    return subTree;
847 848
  }

849 850 851 852 853 854 855 856
  /**
   * Computes total weights in the call graph.
   */
  computeTotalWeights() {
    if (this.totalsComputed_) return;
    this.root_.computeTotalWeight();
    this.totalsComputed_ = true;
  }
857

858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
  /**
   * Traverses the call graph in preorder. This function can be used for
   * building optionally modified tree clones. This is the boilerplate code
   * for this scenario:
   *
   * callTree.traverse(function(node, parentClone) {
   *   var nodeClone = cloneNode(node);
   *   if (parentClone)
   *     parentClone.addChild(nodeClone);
   *   return nodeClone;
   * });
   *
   * @param {function(CallTreeNode, *)} f Visitor function.
   *    The second parameter is the result of calling 'f' on the parent node.
   */
  traverse(f) {
874
    const pairsToProcess = new ConsArray();
875 876
    pairsToProcess.concat([{ node: this.root_, param: null }]);
    while (!pairsToProcess.atEnd()) {
877 878 879 880
      const pair = pairsToProcess.next();
      const node = pair.node;
      const newParam = f(node, pair.param);
      const morePairsToProcess = [];
881 882 883 884 885
      node.forEachChild((child) => {
        morePairsToProcess.push({ node: child, param: newParam });
      });
      pairsToProcess.concat(morePairsToProcess);
    }
886
  }
887 888 889 890 891 892 893 894 895

  /**
   * Performs an indepth call graph traversal.
   *
   * @param {function(CallTreeNode)} enter A function called
   *     prior to visiting node's children.
   * @param {function(CallTreeNode)} exit A function called
   *     after visiting node's children.
   */
896
  traverseInDepth(enter, exit) {
897 898 899 900 901 902 903 904
    function traverse(node) {
      enter(node);
      node.forEachChild(traverse);
      exit(node);
    }
    traverse(this.root_);
  }
}
905 906 907 908 909 910


/**
 * Constructs a call graph node.
 *
 * @param {string} label Node label.
911
 * @param {CallTreeNode} opt_parent Node parent.
912
 */
913
class CallTreeNode {
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
  /**
   * Node self weight (how many times this node was the last node in
   * a call path).
   * @type {number}
   */
  selfWeight = 0;

  /**
   * Node total weight (includes weights of all children).
   * @type {number}
   */
  totalWeight = 0;
  children = {};

  constructor(label, opt_parent) {
    this.label = label;
    this.parent = opt_parent;
  }
932 933


934 935 936 937 938 939
  /**
   * Adds a child node.
   *
   * @param {string} label Child node label.
   */
  addChild(label) {
940
    const child = new CallTreeNode(label, this);
941 942 943
    this.children[label] = child;
    return child;
  }
944

945 946 947 948
  /**
   * Computes node's total weight.
   */
  computeTotalWeight() {
949
    let totalWeight = this.selfWeight;
950 951 952 953
    this.forEachChild(function (child) {
      totalWeight += child.computeTotalWeight();
    });
    return this.totalWeight = totalWeight;
954
  }
955

956 957 958 959
  /**
   * Returns all node's children as an array.
   */
  exportChildren() {
960
    const result = [];
961 962 963
    this.forEachChild(function (node) { result.push(node); });
    return result;
  }
964

965 966 967 968 969 970 971
  /**
   * Finds an immediate child with the specified label.
   *
   * @param {string} label Child node label.
   */
  findChild(label) {
    return this.children[label] || null;
972 973
  }

974 975 976 977 978 979 980 981 982
  /**
   * Finds an immediate child with the specified label, creates a child
   * node if necessary.
   *
   * @param {string} label Child node label.
   */
  findOrAddChild(label) {
    return this.findChild(label) || this.addChild(label);
  }
983

984 985 986 987 988 989
  /**
   * Calls the specified function for every child.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  forEachChild(f) {
990
    for (let c in this.children) {
991 992
      f(this.children[c]);
    }
993 994
  }

995 996 997 998 999 1000
  /**
   * Walks up from the current node up to the call tree root.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  walkUpToRoot(f) {
1001
    for (let curr = this; curr != null; curr = curr.parent) {
1002 1003 1004
      f(curr);
    }
  }
1005

1006 1007 1008 1009 1010 1011 1012
  /**
   * Tries to find a node with the specified path.
   *
   * @param {Array<string>} labels The path.
   * @param {function(CallTreeNode)} opt_f Visitor function.
   */
  descendToChild(labels, opt_f) {
1013 1014 1015
    let curr = this;
    for (let pos = 0; pos < labels.length && curr != null; pos++) {
      const child = curr.findChild(labels[pos]);
1016 1017 1018 1019
      if (opt_f) {
        opt_f(child, pos);
      }
      curr = child;
1020
    }
1021
    return curr;
1022
  }
1023
}
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

export function JsonProfile() {
  this.codeMap_ = new CodeMap();
  this.codeEntries_ = [];
  this.functionEntries_ = [];
  this.ticks_ = [];
  this.scripts_ = [];
}

JsonProfile.prototype.addLibrary = function (
  name, startAddr, endAddr) {
1035
  const entry = new CodeEntry(
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    endAddr - startAddr, name, 'SHARED_LIB');
  this.codeMap_.addLibrary(startAddr, entry);

  entry.codeId = this.codeEntries_.length;
  this.codeEntries_.push({ name: entry.name, type: entry.type });
  return entry;
};

JsonProfile.prototype.addStaticCode = function (
  name, startAddr, endAddr) {
1046
  const entry = new CodeEntry(
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
    endAddr - startAddr, name, 'CPP');
  this.codeMap_.addStaticCode(startAddr, entry);

  entry.codeId = this.codeEntries_.length;
  this.codeEntries_.push({ name: entry.name, type: entry.type });
  return entry;
};

JsonProfile.prototype.addCode = function (
  kind, name, timestamp, start, size) {
  let codeId = this.codeEntries_.length;
  // Find out if we have a static code entry for the code. If yes, we will
  // make sure it is written to the JSON file just once.
  let staticEntry = this.codeMap_.findAddress(start);
  if (staticEntry && staticEntry.entry.type === 'CPP') {
    codeId = staticEntry.entry.codeId;
  }

1065
  const entry = new CodeEntry(size, name, 'CODE');
1066 1067 1068 1069 1070 1071 1072
  this.codeMap_.addCode(start, entry);

  entry.codeId = codeId;
  this.codeEntries_[codeId] = {
    name: entry.name,
    timestamp: timestamp,
    type: entry.type,
1073
    kind: kind,
1074 1075 1076 1077 1078 1079 1080 1081 1082
  };

  return entry;
};

JsonProfile.prototype.addFuncCode = function (
  kind, name, timestamp, start, size, funcAddr, state) {
  // As code and functions are in the same address space,
  // it is safe to put them in a single code map.
1083
  let func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
1084
  if (!func) {
1085
    func = new CodeEntry(0, name, 'SFI');
1086 1087 1088
    this.codeMap_.addCode(funcAddr, func);

    func.funcId = this.functionEntries_.length;
1089
    this.functionEntries_.push({ name, codes: [] });
1090 1091 1092 1093 1094
  } else if (func.name !== name) {
    // Function object has been overwritten with a new one.
    func.name = name;

    func.funcId = this.functionEntries_.length;
1095
    this.functionEntries_.push({ name, codes: [] });
1096 1097
  }
  // TODO(jarin): Insert the code object into the SFI's code list.
1098
  let entry = this.codeMap_.findDynamicEntryByStartAddress(start);
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
  if (entry) {
    if (entry.size === size && entry.func === func) {
      // Entry state has changed.
      entry.state = state;
    } else {
      this.codeMap_.deleteCode(start);
      entry = null;
    }
  }
  if (!entry) {
1109
    entry = new CodeEntry(size, name, 'JS');
1110 1111 1112 1113 1114 1115
    this.codeMap_.addCode(start, entry);

    entry.codeId = this.codeEntries_.length;

    this.functionEntries_[func.funcId].codes.push(entry.codeId);

1116
    kind = Profile.getKindFromState(state);
1117 1118 1119 1120 1121 1122

    this.codeEntries_.push({
      name: entry.name,
      type: entry.type,
      kind: kind,
      func: func.funcId,
1123
      tm: timestamp,
1124 1125 1126 1127 1128 1129 1130 1131 1132
    });
  }
  return entry;
};

JsonProfile.prototype.moveCode = function (from, to) {
  try {
    this.codeMap_.moveCode(from, to);
  } catch (e) {
1133
    printErr(`Move: unknown source ${from}`);
1134 1135 1136 1137 1138 1139
  }
};

JsonProfile.prototype.addSourcePositions = function (
  start, script, startPos, endPos, sourcePositions, inliningPositions,
  inlinedFunctions) {
1140
  const entry = this.codeMap_.findDynamicEntryByStartAddress(start);
1141
  if (!entry) return;
1142
  const codeId = entry.codeId;
1143 1144 1145 1146

  // Resolve the inlined functions list.
  if (inlinedFunctions.length > 0) {
    inlinedFunctions = inlinedFunctions.substring(1).split("S");
1147 1148 1149
    for (let i = 0; i < inlinedFunctions.length; i++) {
      const funcAddr = parseInt(inlinedFunctions[i]);
      const func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
1150
      if (!func || func.funcId === undefined) {
1151
        printErr(`Could not find function ${inlinedFunctions[i]}`);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
        inlinedFunctions[i] = null;
      } else {
        inlinedFunctions[i] = func.funcId;
      }
    }
  } else {
    inlinedFunctions = [];
  }

  this.codeEntries_[entry.codeId].source = {
    script: script,
    start: startPos,
    end: endPos,
    positions: sourcePositions,
    inlined: inliningPositions,
    fns: inlinedFunctions
  };
};

JsonProfile.prototype.addScriptSource = function (id, url, source) {
  this.scripts_[id] = new Script(id, url, source);
};

JsonProfile.prototype.deoptCode = function (
  timestamp, code, inliningId, scriptOffset, bailoutType,
  sourcePositionText, deoptReasonText) {
  let entry = this.codeMap_.findDynamicEntryByStartAddress(code);
  if (entry) {
    let codeId = entry.codeId;
    if (!this.codeEntries_[codeId].deopt) {
      // Only add the deopt if there was no deopt before.
      // The subsequent deoptimizations should be lazy deopts for
      // other on-stack activations.
      this.codeEntries_[codeId].deopt = {
        tm: timestamp,
        inliningId: inliningId,
        scriptOffset: scriptOffset,
        posText: sourcePositionText,
        reason: deoptReasonText,
1191
        bailoutType: bailoutType,
1192 1193 1194 1195 1196 1197 1198 1199 1200
      };
    }
  }
};

JsonProfile.prototype.deleteCode = function (start) {
  try {
    this.codeMap_.deleteCode(start);
  } catch (e) {
1201
    printErr(`Delete: unknown address ${start}`);
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  }
};

JsonProfile.prototype.moveFunc = function (from, to) {
  if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
    this.codeMap_.moveCode(from, to);
  }
};

JsonProfile.prototype.findEntry = function (addr) {
  return this.codeMap_.findEntry(addr);
};

JsonProfile.prototype.recordTick = function (time_ns, vmState, stack) {
  // TODO(jarin) Resolve the frame-less case (when top of stack is
  // known code).
1218 1219 1220
  const processedStack = [];
  for (let i = 0; i < stack.length; i++) {
    const resolved = this.codeMap_.findAddress(stack[i]);
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    if (resolved) {
      processedStack.push(resolved.entry.codeId, resolved.offset);
    } else {
      processedStack.push(-1, stack[i]);
    }
  }
  this.ticks_.push({ tm: time_ns, vm: vmState, s: processedStack });
};

function writeJson(s) {
  write(JSON.stringify(s, null, 2));
}

JsonProfile.prototype.writeJson = function () {
  // Write out the JSON in a partially manual way to avoid creating too-large
  // strings in one JSON.stringify call when there are a lot of ticks.
  write('{\n')

  write('  "code": ');
  writeJson(this.codeEntries_);
  write(',\n');

  write('  "functions": ');
  writeJson(this.functionEntries_);
  write(',\n');

  write('  "ticks": [\n');
1248
  for (let i = 0; i < this.ticks_.length; i++) {
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    write('    ');
    writeJson(this.ticks_[i]);
    if (i < this.ticks_.length - 1) {
      write(',\n');
    } else {
      write('\n');
    }
  }
  write('  ],\n');

  write('  "scripts": ');
  writeJson(this.scripts_);

  write('}\n');
};