interpreter.cc 14.8 KB
Newer Older
1 2 3 4 5 6
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/interpreter/interpreter.h"

7
#include <fstream>
8
#include <memory>
9

10
#include "builtins-generated/bytecodes-builtins-list.h"
11
#include "src/ast/prettyprinter.h"
12
#include "src/ast/scopes.h"
13 14
#include "src/codegen/compiler.h"
#include "src/codegen/unoptimized-compilation-info.h"
15 16
#include "src/init/bootstrapper.h"
#include "src/init/setup-isolate.h"
17
#include "src/interpreter/bytecode-generator.h"
18
#include "src/interpreter/bytecodes.h"
19
#include "src/logging/counters-inl.h"
20
#include "src/objects/objects-inl.h"
21
#include "src/objects/shared-function-info.h"
22
#include "src/objects/slots.h"
23
#include "src/objects/visitors.h"
24
#include "src/parsing/parse-info.h"
25
#include "src/snapshot/snapshot.h"
26
#include "src/utils/ostreams.h"
27 28 29 30 31

namespace v8 {
namespace internal {
namespace interpreter {

32
class InterpreterCompilationJob final : public UnoptimizedCompilationJob {
33
 public:
34 35 36 37
  InterpreterCompilationJob(
      ParseInfo* parse_info, FunctionLiteral* literal,
      AccountingAllocator* allocator,
      std::vector<FunctionLiteral*>* eager_inner_literals);
38 39 40

 protected:
  Status ExecuteJobImpl() final;
41 42
  Status FinalizeJobImpl(Handle<SharedFunctionInfo> shared_info,
                         Isolate* isolate) final;
43 44 45

 private:
  BytecodeGenerator* generator() { return &generator_; }
46 47
  void CheckAndPrintBytecodeMismatch(Isolate* isolate,
                                     Handle<BytecodeArray> bytecode);
48

49
  Zone zone_;
50
  UnoptimizedCompilationInfo compilation_info_;
51 52 53 54 55
  BytecodeGenerator generator_;

  DISALLOW_COPY_AND_ASSIGN(InterpreterCompilationJob);
};

56 57 58
Interpreter::Interpreter(Isolate* isolate)
    : isolate_(isolate),
      interpreter_entry_trampoline_instruction_start_(kNullAddress) {
59
  memset(dispatch_table_, 0, sizeof(dispatch_table_));
60

61 62
  if (FLAG_trace_ignition_dispatches) {
    static const int kBytecodeCount = static_cast<int>(Bytecode::kLast) + 1;
63
    bytecode_dispatch_counters_table_.reset(
64
        new uintptr_t[kBytecodeCount * kBytecodeCount]);
65
    memset(bytecode_dispatch_counters_table_.get(), 0,
66 67
           sizeof(uintptr_t) * kBytecodeCount * kBytecodeCount);
  }
68 69
}

70 71 72 73 74 75 76 77 78 79 80 81 82
namespace {

int BuiltinIndexFromBytecode(Bytecode bytecode, OperandScale operand_scale) {
  int index = BytecodeOperands::OperandScaleAsIndex(operand_scale) *
                  kNumberOfBytecodeHandlers +
              static_cast<int>(bytecode);
  int offset = kBytecodeToBuiltinsMapping[index];
  return offset >= 0 ? Builtins::kFirstBytecodeHandler + offset
                     : Builtins::kIllegalHandler;
}

}  // namespace

83 84
Code Interpreter::GetBytecodeHandler(Bytecode bytecode,
                                     OperandScale operand_scale) {
85 86
  int builtin_index = BuiltinIndexFromBytecode(bytecode, operand_scale);
  Builtins* builtins = isolate_->builtins();
87
  return builtins->builtin(builtin_index);
88 89
}

90
void Interpreter::SetBytecodeHandler(Bytecode bytecode,
91
                                     OperandScale operand_scale, Code handler) {
92
  DCHECK(handler.kind() == Code::BYTECODE_HANDLER);
93
  size_t index = GetDispatchTableIndex(bytecode, operand_scale);
94
  dispatch_table_[index] = handler.InstructionStart();
95 96
}

97 98 99 100 101
// static
size_t Interpreter::GetDispatchTableIndex(Bytecode bytecode,
                                          OperandScale operand_scale) {
  static const size_t kEntriesPerOperandScale = 1u << kBitsPerByte;
  size_t index = static_cast<size_t>(bytecode);
102 103
  return index + BytecodeOperands::OperandScaleAsIndex(operand_scale) *
                     kEntriesPerOperandScale;
104 105
}

106
void Interpreter::IterateDispatchTable(RootVisitor* v) {
107 108 109
  if (!isolate_->serializer_enabled() && isolate_->embedded_blob() != nullptr) {
// If we're not generating a snapshot, then every bytecode handler will be
// off-heap, so there's no point iterating over them.
110 111 112 113 114 115
#ifdef DEBUG
    for (int i = 0; i < kDispatchTableSize; i++) {
      Address code_entry = dispatch_table_[i];
      CHECK(code_entry == kNullAddress ||
            InstructionStream::PcIsOffHeap(isolate_, code_entry));
    }
116
#endif  // DEBUG
117 118 119
    return;
  }

120 121
  for (int i = 0; i < kDispatchTableSize; i++) {
    Address code_entry = dispatch_table_[i];
122 123 124
    // Skip over off-heap bytecode handlers since they will never move.
    if (InstructionStream::PcIsOffHeap(isolate_, code_entry)) continue;

125 126 127 128 129 130 131
    // TODO(jkummerow): Would it hurt to simply do:
    // if (code_entry == kNullAddress) continue;
    Code code;
    if (code_entry != kNullAddress) {
      code = Code::GetCodeFromTargetAddress(code_entry);
    }
    Code old_code = code;
132
    v->VisitRootPointer(Root::kDispatchTable, nullptr, FullObjectSlot(&code));
133
    if (code != old_code) {
134
      dispatch_table_[i] = code.entry();
135 136
    }
  }
137 138
}

139 140 141 142
int Interpreter::InterruptBudget() {
  return FLAG_interrupt_budget;
}

143 144
namespace {

145 146
void MaybePrintAst(ParseInfo* parse_info,
                   UnoptimizedCompilationInfo* compilation_info) {
147
  if (!FLAG_print_ast) return;
148

149
  StdoutStream os;
150 151
  std::unique_ptr<char[]> name = compilation_info->literal()->GetDebugName();
  os << "[generating bytecode for function: " << name.get() << "]" << std::endl;
152 153
#ifdef DEBUG
  os << "--- AST ---" << std::endl
154 155
     << AstPrinter(parse_info->stack_limit())
            .PrintProgram(compilation_info->literal())
156
     << std::endl;
157 158 159
#endif  // DEBUG
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173
bool ShouldPrintBytecode(Handle<SharedFunctionInfo> shared) {
  if (!FLAG_print_bytecode) return false;

  // Checks whether function passed the filter.
  if (shared->is_toplevel()) {
    Vector<const char> filter = CStrVector(FLAG_print_bytecode_filter);
    return (filter.length() == 0) || (filter.length() == 1 && filter[0] == '*');
  } else {
    return shared->PassesFilter(FLAG_print_bytecode_filter);
  }
}

}  // namespace

174 175
InterpreterCompilationJob::InterpreterCompilationJob(
    ParseInfo* parse_info, FunctionLiteral* literal,
176
    AccountingAllocator* allocator,
177
    std::vector<FunctionLiteral*>* eager_inner_literals)
178 179
    : UnoptimizedCompilationJob(parse_info->stack_limit(), parse_info,
                                &compilation_info_),
180 181
      zone_(allocator, ZONE_NAME),
      compilation_info_(&zone_, parse_info, literal),
182 183
      generator_(&compilation_info_, parse_info->ast_string_constants(),
                 eager_inner_literals) {}
184 185

InterpreterCompilationJob::Status InterpreterCompilationJob::ExecuteJobImpl() {
186
  RuntimeCallTimerScope runtimeTimerScope(
187 188
      parse_info()->runtime_call_stats(),
      parse_info()->on_background_thread()
189 190
          ? RuntimeCallCounterId::kCompileBackgroundIgnition
          : RuntimeCallCounterId::kCompileIgnition);
191 192
  // TODO(lpy): add support for background compilation RCS trace.
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileIgnition");
193 194 195 196

  // Print AST if flag is enabled. Note, if compiling on a background thread
  // then ASTs from different functions may be intersperse when printed.
  MaybePrintAst(parse_info(), compilation_info());
197

198
  generator()->GenerateBytecode(stack_limit());
199 200 201 202 203 204 205

  if (generator()->HasStackOverflow()) {
    return FAILED;
  }
  return SUCCEEDED;
}

206 207 208 209 210 211 212 213 214 215
#ifdef DEBUG
void InterpreterCompilationJob::CheckAndPrintBytecodeMismatch(
    Isolate* isolate, Handle<BytecodeArray> bytecode) {
  int first_mismatch = generator()->CheckBytecodeMatches(bytecode);
  if (first_mismatch >= 0) {
    parse_info()->ast_value_factory()->Internalize(isolate);
    DeclarationScope::AllocateScopeInfos(parse_info(), isolate);

    Handle<BytecodeArray> new_bytecode =
        generator()->FinalizeBytecode(isolate, parse_info()->script());
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

    std::cerr << "Bytecode mismatch";
#ifdef OBJECT_PRINT
    std::cerr << " found for function: ";
    Handle<String> name = parse_info()->function_name()->string();
    if (name->length() == 0) {
      std::cerr << "anonymous";
    } else {
      name->StringPrint(std::cerr);
    }
    Object script_name = parse_info()->script()->GetNameOrSourceURL();
    if (script_name.IsString()) {
      std::cerr << " ";
      String::cast(script_name).StringPrint(std::cerr);
      std::cerr << ":" << parse_info()->start_position();
    }
#endif
    std::cerr << "\nOriginal bytecode:\n";
234 235 236 237 238 239 240 241
    bytecode->Disassemble(std::cerr);
    std::cerr << "\nNew bytecode:\n";
    new_bytecode->Disassemble(std::cerr);
    FATAL("Bytecode mismatch at offset %d\n", first_mismatch);
  }
}
#endif

242
InterpreterCompilationJob::Status InterpreterCompilationJob::FinalizeJobImpl(
243
    Handle<SharedFunctionInfo> shared_info, Isolate* isolate) {
244
  RuntimeCallTimerScope runtimeTimerScope(
245
      parse_info()->runtime_call_stats(),
246
      RuntimeCallCounterId::kCompileIgnitionFinalization);
247 248
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"),
               "V8.CompileIgnitionFinalization");
249

250 251 252 253 254 255 256 257 258 259 260 261 262 263
  Handle<BytecodeArray> bytecodes = compilation_info_.bytecode_array();
  if (bytecodes.is_null()) {
    bytecodes = generator()->FinalizeBytecode(isolate, parse_info()->script());
    if (generator()->HasStackOverflow()) {
      return FAILED;
    }
    compilation_info()->SetBytecodeArray(bytecodes);
  }

  if (compilation_info()->SourcePositionRecordingMode() ==
      SourcePositionTableBuilder::RecordingMode::RECORD_SOURCE_POSITIONS) {
    Handle<ByteArray> source_position_table =
        generator()->FinalizeSourcePositionTable(isolate);
    bytecodes->set_source_position_table(*source_position_table);
264 265
  }

266
  if (ShouldPrintBytecode(shared_info)) {
267
    StdoutStream os;
268 269
    std::unique_ptr<char[]> name =
        compilation_info()->literal()->GetDebugName();
270 271
    os << "[generated bytecode for function: " << name.get() << " ("
       << shared_info << ")]" << std::endl;
272
    bytecodes->Disassemble(os);
273 274 275
    os << std::flush;
  }

276 277 278 279
#ifdef DEBUG
  CheckAndPrintBytecodeMismatch(isolate, bytecodes);
#endif

280 281 282
  return SUCCEEDED;
}

283
std::unique_ptr<UnoptimizedCompilationJob> Interpreter::NewCompilationJob(
284 285
    ParseInfo* parse_info, FunctionLiteral* literal,
    AccountingAllocator* allocator,
286
    std::vector<FunctionLiteral*>* eager_inner_literals) {
287
  return std::make_unique<InterpreterCompilationJob>(
288
      parse_info, literal, allocator, eager_inner_literals);
289 290
}

291 292 293 294
std::unique_ptr<UnoptimizedCompilationJob>
Interpreter::NewSourcePositionCollectionJob(
    ParseInfo* parse_info, FunctionLiteral* literal,
    Handle<BytecodeArray> existing_bytecode, AccountingAllocator* allocator) {
295 296
  auto job = std::make_unique<InterpreterCompilationJob>(parse_info, literal,
                                                         allocator, nullptr);
297 298 299 300
  job->compilation_info()->SetBytecodeArray(existing_bytecode);
  return job;
}

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
void Interpreter::ForEachBytecode(
    const std::function<void(Bytecode, OperandScale)>& f) {
  constexpr OperandScale kOperandScales[] = {
#define VALUE(Name, _) OperandScale::k##Name,
      OPERAND_SCALE_LIST(VALUE)
#undef VALUE
  };

  for (OperandScale operand_scale : kOperandScales) {
    for (int i = 0; i < Bytecodes::kBytecodeCount; i++) {
      f(Bytecodes::FromByte(i), operand_scale);
    }
  }
}

316
void Interpreter::Initialize() {
317
  Builtins* builtins = isolate_->builtins();
318 319 320 321 322

  // Set the interpreter entry trampoline entry point now that builtins are
  // initialized.
  Handle<Code> code = BUILTIN_CODE(isolate_, InterpreterEntryTrampoline);
  DCHECK(builtins->is_initialized());
323 324
  DCHECK(code->is_off_heap_trampoline() ||
         isolate_->heap()->IsImmovable(*code));
325 326 327
  interpreter_entry_trampoline_instruction_start_ = code->InstructionStart();

  // Initialize the dispatch table.
328
  Code illegal = builtins->builtin(Builtins::kIllegalHandler);
329
  int builtin_id = Builtins::kFirstBytecodeHandler;
330 331
  ForEachBytecode([=, &builtin_id](Bytecode bytecode,
                                   OperandScale operand_scale) {
332
    Code handler = illegal;
333 334 335 336 337 338 339 340 341
    if (Bytecodes::BytecodeHasHandler(bytecode, operand_scale)) {
#ifdef DEBUG
      std::string builtin_name(Builtins::name(builtin_id));
      std::string expected_name =
          Bytecodes::ToString(bytecode, operand_scale, "") + "Handler";
      DCHECK_EQ(expected_name, builtin_name);
#endif
      handler = builtins->builtin(builtin_id++);
    }
342 343
    SetBytecodeHandler(bytecode, operand_scale, handler);
  });
344
  DCHECK(builtin_id == Builtins::builtin_count);
345
  DCHECK(IsDispatchTableInitialized());
346 347
}

348
bool Interpreter::IsDispatchTableInitialized() const {
349
  return dispatch_table_[0] != kNullAddress;
350 351
}

352
const char* Interpreter::LookupNameOfBytecodeHandler(const Code code) {
353 354
  if (code.kind() == Code::BYTECODE_HANDLER) {
    return Builtins::name(code.builtin_index());
355 356 357 358
  }
  return nullptr;
}

359 360 361 362 363 364 365 366 367 368 369 370
uintptr_t Interpreter::GetDispatchCounter(Bytecode from, Bytecode to) const {
  int from_index = Bytecodes::ToByte(from);
  int to_index = Bytecodes::ToByte(to);
  return bytecode_dispatch_counters_table_[from_index * kNumberOfBytecodes +
                                           to_index];
}

Local<v8::Object> Interpreter::GetDispatchCountersObject() {
  v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(isolate_);
  Local<v8::Context> context = isolate->GetCurrentContext();

  Local<v8::Object> counters_map = v8::Object::New(isolate);
371 372 373 374 375 376 377 378 379 380 381 382

  // Output is a JSON-encoded object of objects.
  //
  // The keys on the top level object are source bytecodes,
  // and corresponding value are objects. Keys on these last are the
  // destinations of the dispatch and the value associated is a counter for
  // the correspondent source-destination dispatch chain.
  //
  // Only non-zero counters are written to file, but an entry in the top-level
  // object is always present, even if the value is empty because all counters
  // for that source are zero.

383
  for (int from_index = 0; from_index < kNumberOfBytecodes; ++from_index) {
384
    Bytecode from_bytecode = Bytecodes::FromByte(from_index);
385 386 387 388 389
    Local<v8::Object> counters_row = v8::Object::New(isolate);

    for (int to_index = 0; to_index < kNumberOfBytecodes; ++to_index) {
      Bytecode to_bytecode = Bytecodes::FromByte(to_index);
      uintptr_t counter = GetDispatchCounter(from_bytecode, to_bytecode);
390 391

      if (counter > 0) {
392 393 394 395 396 397
        std::string to_name = Bytecodes::ToString(to_bytecode);
        Local<v8::String> to_name_object =
            v8::String::NewFromUtf8(isolate, to_name.c_str(),
                                    NewStringType::kNormal)
                .ToLocalChecked();
        Local<v8::Number> counter_object = v8::Number::New(isolate, counter);
398 399
        CHECK(counters_row
                  ->DefineOwnProperty(context, to_name_object, counter_object)
400
                  .IsJust());
401 402 403
      }
    }

404 405 406 407 408 409
    std::string from_name = Bytecodes::ToString(from_bytecode);
    Local<v8::String> from_name_object =
        v8::String::NewFromUtf8(isolate, from_name.c_str(),
                                NewStringType::kNormal)
            .ToLocalChecked();

410 411 412
    CHECK(
        counters_map->DefineOwnProperty(context, from_name_object, counters_row)
            .IsJust());
413 414
  }

415
  return counters_map;
416 417
}

418 419 420
}  // namespace interpreter
}  // namespace internal
}  // namespace v8