implementation-visitor.cc 77 KB
Newer Older
1 2 3 4
// Copyright 2017 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.

5 6
#include <algorithm>

7
#include "src/torque/csa-generator.h"
8
#include "src/torque/declaration-visitor.h"
9
#include "src/torque/implementation-visitor.h"
10
#include "src/torque/parameter-difference.h"
11 12 13 14 15 16

namespace v8 {
namespace internal {
namespace torque {

VisitResult ImplementationVisitor::Visit(Expression* expr) {
17
  CurrentSourcePosition::Scope scope(expr->pos);
18 19 20 21 22 23 24
  switch (expr->kind) {
#define ENUM_ITEM(name)        \
  case AstNode::Kind::k##name: \
    return Visit(name::cast(expr));
    AST_EXPRESSION_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
25
      UNREACHABLE();
26 27 28
  }
}

29
const Type* ImplementationVisitor::Visit(Statement* stmt) {
30
  CurrentSourcePosition::Scope scope(stmt->pos);
31
  StackScope stack_scope(this);
32
  const Type* result;
33
  switch (stmt->kind) {
34 35 36 37
#define ENUM_ITEM(name)               \
  case AstNode::Kind::k##name:        \
    result = Visit(name::cast(stmt)); \
    break;
38 39 40
    AST_STATEMENT_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
    default:
41
      UNREACHABLE();
42
  }
43 44 45
  DCHECK_EQ(result == TypeOracle::GetNeverType(),
            assembler().CurrentBlockIsComplete());
  return result;
46 47
}

48 49 50
void ImplementationVisitor::BeginNamespaceFile(Namespace* nspace) {
  std::ostream& source = nspace->source_stream();
  std::ostream& header = nspace->header_stream();
51

52
  source << "#include \"src/objects/arguments.h\"\n";
53 54 55 56 57 58
  source << "#include \"src/builtins/builtins-utils-gen.h\"\n";
  source << "#include \"src/builtins/builtins.h\"\n";
  source << "#include \"src/code-factory.h\"\n";
  source << "#include \"src/elements-kind.h\"\n";
  source << "#include \"src/heap/factory-inl.h\"\n";
  source << "#include \"src/objects.h\"\n";
59
  source << "#include \"src/objects/bigint.h\"\n";
60

61
  for (Namespace* n : GlobalContext::Get().GetNamespaces()) {
62
    source << "#include \"torque-generated/builtins-" +
63 64 65
                  DashifyString(n->name()) + "-from-dsl-gen.h\"\n";
    if (n != GlobalContext::GetDefaultNamespace()) {
      source << "#include \"src/builtins/builtins-" + DashifyString(n->name()) +
66 67 68 69
                    "-gen.h\"\n";
    }
  }
  source << "\n";
70

71 72 73
  source << "namespace v8 {\n"
         << "namespace internal {\n"
         << "\n";
74

75
  std::string upper_name(nspace->name());
76 77 78 79
  transform(upper_name.begin(), upper_name.end(), upper_name.begin(),
            ::toupper);
  std::string headerDefine =
      std::string("V8_TORQUE_") + upper_name + "_FROM_DSL_BASE_H__";
80 81
  header << "#ifndef " << headerDefine << "\n";
  header << "#define " << headerDefine << "\n\n";
82 83 84 85 86
  header << "#include \"src/compiler/code-assembler.h\"\n";
  if (nspace != GlobalContext::GetDefaultNamespace()) {
    header << "#include \"src/code-stub-assembler.h\"\n";
  }
  header << "\n";
87

88 89 90
  header << "namespace v8 {\n"
         << "namespace internal {\n"
         << "\n";
91

92
  header << "class " << nspace->ExternalName() << " {\n";
93
  header << " public:\n";
94
  header << "  explicit " << nspace->ExternalName()
95 96
         << "(compiler::CodeAssemblerState* state) : state_(state), ca_(state) "
            "{ USE(state_, ca_); }\n";
97
}
98

99 100 101
void ImplementationVisitor::EndNamespaceFile(Namespace* nspace) {
  std::ostream& source = nspace->source_stream();
  std::ostream& header = nspace->header_stream();
102

103
  std::string upper_name(nspace->name());
104 105 106 107 108
  transform(upper_name.begin(), upper_name.end(), upper_name.begin(),
            ::toupper);
  std::string headerDefine =
      std::string("V8_TORQUE_") + upper_name + "_FROM_DSL_BASE_H__";

109 110 111
  source << "}  // namespace internal\n"
         << "}  // namespace v8\n"
         << "\n";
112

113 114 115 116
  header << " private:\n"
         << "  compiler::CodeAssemblerState* const state_;\n"
         << "  compiler::CodeAssembler ca_;"
         << "}; \n\n";
117 118 119 120
  header << "}  // namespace internal\n"
         << "}  // namespace v8\n"
         << "\n";
  header << "#endif  // " << headerDefine << "\n";
121 122
}

123
void ImplementationVisitor::Visit(NamespaceConstant* decl) {
124 125
  Signature signature{{}, base::nullopt, {{}, false}, 0, decl->type(), {}};
  const std::string& name = decl->name();
126

127 128
  BindingsManagersScope bindings_managers_scope;

129 130 131 132 133
  header_out() << "  ";
  GenerateFunctionDeclaration(header_out(), "", name, signature, {});
  header_out() << ";\n";

  GenerateFunctionDeclaration(source_out(),
134
                              CurrentNamespace()->ExternalName() + "::", name,
135 136 137 138 139
                              signature, {});
  source_out() << " {\n";

  DCHECK(!signature.return_type->IsVoidOrNever());

140 141
  assembler_ = CfgAssembler(Stack<const Type*>{});

142
  VisitResult expression_result = Visit(decl->body());
143 144 145
  VisitResult return_result =
      GenerateImplicitConvert(signature.return_type, expression_result);

146 147 148 149 150 151 152 153
  CSAGenerator csa_generator{assembler().Result(), source_out()};
  Stack<std::string> values = *csa_generator.EmitGraph(Stack<std::string>{});

  assembler_ = base::nullopt;

  source_out() << "return ";
  CSAGenerator::EmitCSAValue(return_result, values, source_out());
  source_out() << ";\n";
154 155 156
  source_out() << "}\n\n";
}

157 158 159 160 161 162
void ImplementationVisitor::Visit(TypeAlias* alias) {
  if (alias->IsRedeclaration()) return;
  const StructType* struct_type = StructType::DynamicCast(alias->type());
  if (!struct_type) return;
  const std::string& name = struct_type->name();
  header_out() << "  struct " << name << " {\n";
163 164 165 166
  for (auto& field : struct_type->fields()) {
    header_out() << "    " << field.type->GetGeneratedTypeName();
    header_out() << " " << field.name << ";\n";
  }
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  header_out() << "\n    std::tuple<";
  bool first = true;
  for (const Type* type : LowerType(struct_type)) {
    if (!first) {
      header_out() << ", ";
    }
    first = false;
    header_out() << type->GetGeneratedTypeName();
  }
  header_out() << "> Flatten() const {\n"
               << "      return std::tuple_cat(";
  first = true;
  for (auto& field : struct_type->fields()) {
    if (!first) {
      header_out() << ", ";
    }
    first = false;
    if (field.type->IsStructType()) {
      header_out() << field.name << ".Flatten()";
    } else {
      header_out() << "std::make_tuple(" << field.name << ")";
    }
  }
  header_out() << ");\n";
  header_out() << "    }\n";
  header_out() << "  };\n";
193 194
}

195 196 197 198 199
void ImplementationVisitor::Visit(Macro* macro) {
  if (macro->IsExternal()) return;
  CurrentScope::Scope current_scope(macro);
  const Signature& signature = macro->signature();
  const Type* return_type = macro->signature().return_type;
200 201 202
  bool can_return = return_type != TypeOracle::GetNeverType();
  bool has_return_value =
      can_return && return_type != TypeOracle::GetVoidType();
203

204
  CurrentCallable::Scope current_callable(macro);
205

206 207 208
  header_out() << "  ";
  GenerateMacroFunctionDeclaration(header_out(), "", macro);
  header_out() << ";\n";
209

210
  GenerateMacroFunctionDeclaration(
211
      source_out(), CurrentNamespace()->ExternalName() + "::", macro);
212
  source_out() << " {\n";
213

214 215
  Stack<std::string> lowered_parameters;
  Stack<const Type*> lowered_parameter_types;
216

217
  BindingsManagersScope bindings_managers_scope;
218

219 220 221 222 223 224 225 226 227 228 229 230
  BlockBindings<LocalValue> parameter_bindings(&ValueBindingsManager::Get());
  for (size_t i = 0; i < macro->signature().parameter_names.size(); ++i) {
    const std::string& name = macro->parameter_names()[i];
    std::string external_name = GetParameterVariableFromName(name);
    const Type* type = macro->signature().types()[i];
    if (type->IsConstexpr()) {
      parameter_bindings.Add(
          name, LocalValue{true, VisitResult(type, external_name)});
    } else {
      LowerParameter(type, external_name, &lowered_parameters);
      StackRange range = lowered_parameter_types.PushMany(LowerType(type));
      parameter_bindings.Add(name, LocalValue{true, VisitResult(type, range)});
231
    }
232
  }
233

234 235
  DCHECK_EQ(lowered_parameters.Size(), lowered_parameter_types.Size());
  assembler_ = CfgAssembler(lowered_parameter_types);
236

237 238 239 240 241
  BlockBindings<LocalLabel> label_bindings(&LabelBindingsManager::Get());
  for (const LabelDeclaration& label_info : signature.labels) {
    Stack<const Type*> label_input_stack;
    for (const Type* type : label_info.types) {
      label_input_stack.PushMany(LowerType(type));
242
    }
243 244 245
    Block* block = assembler().NewBlock(std::move(label_input_stack));
    label_bindings.Add(label_info.name, LocalLabel{block, label_info.types});
  }
246

247 248 249 250 251 252 253 254
  Block* macro_end;
  base::Optional<Binding<LocalLabel>> macro_end_binding;
  if (can_return) {
    macro_end = assembler().NewBlock(
        Stack<const Type*>{LowerType(signature.return_type)});
    macro_end_binding.emplace(&LabelBindingsManager::Get(), "_macro_end",
                              LocalLabel{macro_end, {signature.return_type}});
  }
255

256
  const Type* result = Visit(*macro->body());
257

258 259 260
  if (result->IsNever()) {
    if (!macro->signature().return_type->IsNever() && !macro->HasReturns()) {
      std::stringstream s;
261
      s << "macro " << macro->ReadableName()
262 263
        << " that never returns must have return type never";
      ReportError(s.str());
264
    }
265 266 267
  } else {
    if (macro->signature().return_type->IsNever()) {
      std::stringstream s;
268
      s << "macro " << macro->ReadableName()
269 270 271 272 273
        << " has implicit return at end of its declartion but return type "
           "never";
      ReportError(s.str());
    } else if (!macro->signature().return_type->IsVoid()) {
      std::stringstream s;
274
      s << "macro " << macro->ReadableName()
275 276
        << " expects to return a value but doesn't on all paths";
      ReportError(s.str());
277
    }
278 279 280 281
  }
  if (!result->IsNever()) {
    assembler().Goto(macro_end);
  }
282

283 284 285 286 287 288
  for (auto* label_binding : label_bindings.bindings()) {
    assembler().Bind(label_binding->block);
    std::vector<std::string> label_parameter_variables;
    for (size_t i = 0; i < label_binding->parameter_types.size(); ++i) {
      label_parameter_variables.push_back(
          ExternalLabelParameterName(label_binding->name(), i));
289
    }
290 291 292
    assembler().Emit(GotoExternalInstruction{
        ExternalLabelName(label_binding->name()), label_parameter_variables});
  }
293

294 295 296
  if (macro->HasReturns() || !result->IsNever()) {
    assembler().Bind(macro_end);
  }
297

298 299 300
  CSAGenerator csa_generator{assembler().Result(), source_out()};
  base::Optional<Stack<std::string>> values =
      csa_generator.EmitGraph(lowered_parameters);
301

302
  assembler_ = base::nullopt;
303

304 305 306 307
  if (has_return_value) {
    source_out() << "  return ";
    CSAGenerator::EmitCSAValue(GetAndClearReturnValue(), *values, source_out());
    source_out() << ";\n";
308
  }
309
  source_out() << "}\n\n";
310 311
}

312
namespace {
313

314
std::string AddParameter(size_t i, Builtin* builtin,
315
                         Stack<std::string>* parameters,
316 317
                         Stack<const Type*>* parameter_types,
                         BlockBindings<LocalValue>* parameter_bindings) {
318 319
  const std::string& name = builtin->signature().parameter_names[i];
  const Type* type = builtin->signature().types()[i];
320 321 322 323 324
  std::string external_name = "parameter" + std::to_string(i);
  parameters->Push(external_name);
  StackRange range = parameter_types->PushMany(LowerType(type));
  parameter_bindings->Add(name, LocalValue{true, VisitResult(type, range)});
  return external_name;
325
}
326

327 328
}  // namespace

329 330 331
void ImplementationVisitor::Visit(Builtin* builtin) {
  if (builtin->IsExternal()) return;
  CurrentScope::Scope current_scope(builtin);
332
  const std::string& name = builtin->ExternalName();
333
  const Signature& signature = builtin->signature();
334 335 336 337
  source_out() << "TF_BUILTIN(" << name << ", CodeStubAssembler) {\n"
               << "  compiler::CodeAssemblerState* state_ = state();"
               << "  compiler::CodeAssembler ca_(state());\n";

338
  CurrentCallable::Scope current_callable(builtin);
339

340 341 342
  Stack<const Type*> parameter_types;
  Stack<std::string> parameters;

343 344 345 346
  BindingsManagersScope bindings_managers_scope;

  BlockBindings<LocalValue> parameter_bindings(&ValueBindingsManager::Get());

347
  // Context
348
  std::string parameter0 = AddParameter(0, builtin, &parameters,
349
                                        &parameter_types, &parameter_bindings);
350
  source_out() << "  TNode<Context> " << parameter0
351
               << " = UncheckedCast<Context>(Parameter("
352
               << "Descriptor::kContext));\n";
353
  source_out() << "  USE(" << parameter0 << ");\n";
354 355

  size_t first = 1;
356
  if (builtin->IsVarArgsJavaScript()) {
357
    DCHECK(signature.parameter_types.var_args);
358
    source_out()
359 360
        << "  Node* argc = Parameter(Descriptor::kJSActualArgumentsCount);\n";
    source_out() << "  CodeStubArguments arguments_impl(this, "
361
                    "ChangeInt32ToIntPtr(argc));\n";
362
    std::string parameter1 = AddParameter(
363
        1, builtin, &parameters, &parameter_types, &parameter_bindings);
364 365

    source_out() << "  TNode<Object> " << parameter1
366
                 << " = arguments_impl.GetReceiver();\n";
367 368
    source_out() << "auto " << CSAGenerator::ARGUMENTS_VARIABLE_STRING
                 << " = &arguments_impl;\n";
369
    source_out() << "USE(arguments);\n";
370
    source_out() << "USE(" << parameter1 << ");\n";
371
    parameter_bindings.Add(
372
        *signature.arguments_variable,
373 374
        LocalValue{true,
                   VisitResult(TypeOracle::GetArgumentsType(), "arguments")});
375
    first = 2;
376 377
  }

378
  for (size_t i = 0; i < signature.parameter_names.size(); ++i) {
379
    if (i < first) continue;
380
    const std::string& parameter_name = signature.parameter_names[i];
381
    const Type* type = signature.types()[i];
382 383
    std::string var = AddParameter(i, builtin, &parameters, &parameter_types,
                                   &parameter_bindings);
384 385
    source_out() << "  " << type->GetGeneratedTypeName() << " " << var << " = "
                 << "UncheckedCast<" << type->GetGeneratedTNodeTypeName()
386 387 388 389 390 391
                 << ">(Parameter(Descriptor::k"
                 << CamelifyString(parameter_name) << "));\n";
    source_out() << "  USE(" << var << ");\n";
  }

  assembler_ = CfgAssembler(parameter_types);
392
  const Type* body_result = Visit(*builtin->body());
393 394 395 396 397 398 399
  if (body_result != TypeOracle::GetNeverType()) {
    ReportError("control reaches end of builtin, expected return of a value");
  }
  CSAGenerator csa_generator{assembler().Result(), source_out(),
                             builtin->kind()};
  csa_generator.EmitGraph(parameters);
  assembler_ = base::nullopt;
400
  source_out() << "}\n\n";
401 402
}

403
const Type* ImplementationVisitor::Visit(VarDeclarationStatement* stmt) {
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
  BlockBindings<LocalValue> block_bindings(&ValueBindingsManager::Get());
  return Visit(stmt, &block_bindings);
}

const Type* ImplementationVisitor::Visit(
    VarDeclarationStatement* stmt, BlockBindings<LocalValue>* block_bindings) {
  if (!stmt->const_qualified && !stmt->type) {
    ReportError(
        "variable declaration is missing type. Only 'const' bindings can "
        "infer the type.");
  }
  // const qualified variables are required to be initialized properly.
  if (stmt->const_qualified && !stmt->initializer) {
    ReportError("local constant \"", stmt->name, "\" is not initialized.");
  }

420
  base::Optional<const Type*> type;
421
  if (stmt->type) {
422
    type = Declarations::GetType(*stmt->type);
423 424 425 426 427
    if ((*type)->IsConstexpr() && !stmt->const_qualified) {
      ReportError(
          "cannot declare variable with constexpr type. Use 'const' instead.");
    }
  }
428 429
  base::Optional<VisitResult> init_result;
  if (stmt->initializer) {
430
    StackScope scope(this);
431
    init_result = Visit(*stmt->initializer);
432 433 434 435 436 437 438 439 440 441 442
    if (type) {
      init_result = GenerateImplicitConvert(*type, *init_result);
    }
    init_result = scope.Yield(*init_result);
  } else {
    DCHECK(type.has_value());
    if ((*type)->IsConstexpr()) {
      ReportError("constexpr variables need an initializer");
    }
    TypeVector lowered_types = LowerType(*type);
    for (const Type* type : lowered_types) {
443 444 445 446 447
      assembler().Emit(PushUninitializedInstruction{TypeOracle::GetTopType(
          "unitialized variable '" + stmt->name + "' of type " +
              type->ToString() + " originally defined at " +
              PositionAsString(stmt->pos),
          type)});
448 449 450
    }
    init_result =
        VisitResult(*type, assembler().TopRange(lowered_types.size()));
451
  }
452 453
  block_bindings->Add(stmt->name,
                      LocalValue{stmt->const_qualified, *init_result});
454
  return TypeOracle::GetVoidType();
455 456
}

457
const Type* ImplementationVisitor::Visit(TailCallStatement* stmt) {
458 459 460 461
  return Visit(stmt->call, true).type();
}

VisitResult ImplementationVisitor::Visit(ConditionalExpression* expr) {
462 463
  Block* true_block = assembler().NewBlock(assembler().CurrentStack());
  Block* false_block = assembler().NewBlock(assembler().CurrentStack());
464 465
  Block* done_block = assembler().NewBlock();
  Block* true_conversion_block = assembler().NewBlock();
466
  GenerateExpressionBranch(expr->condition, true_block, false_block);
467

468 469
  VisitResult left;
  VisitResult right;
470 471

  {
472 473 474 475
    // The code for both paths of the conditional need to be generated first
    // before evaluating the conditional expression because the common type of
    // the result of both the true and false of the condition needs to be known
    // to convert both branches to a common type.
476
    assembler().Bind(true_block);
477 478 479
    StackScope left_scope(this);
    left = Visit(expr->if_true);
    assembler().Goto(true_conversion_block);
480

481 482
    const Type* common_type;
    {
483
      assembler().Bind(false_block);
484 485 486 487 488
      StackScope right_scope(this);
      right = Visit(expr->if_false);
      common_type = GetCommonType(left.type(), right.type());
      right = right_scope.Yield(GenerateImplicitConvert(common_type, right));
      assembler().Goto(done_block);
489 490
    }

491 492 493
    assembler().Bind(true_conversion_block);
    left = left_scope.Yield(GenerateImplicitConvert(common_type, left));
    assembler().Goto(done_block);
494
  }
495 496 497 498

  assembler().Bind(done_block);
  CHECK_EQ(left, right);
  return left;
499 500 501
}

VisitResult ImplementationVisitor::Visit(LogicalOrExpression* expr) {
502
  VisitResult left_result;
503
  {
504 505 506
    Block* false_block = assembler().NewBlock(assembler().CurrentStack());
    Binding<LocalLabel> false_binding{&LabelBindingsManager::Get(),
                                      kFalseLabelName, LocalLabel{false_block}};
507
    left_result = Visit(expr->left);
508
    if (left_result.type()->IsBool()) {
509 510 511
      Block* true_block = LookupSimpleLabel(kTrueLabelName);
      assembler().Branch(true_block, false_block);
      assembler().Bind(false_block);
512
    } else if (left_result.type()->IsNever()) {
513
      assembler().Bind(false_block);
514 515 516 517
    } else if (!left_result.type()->IsConstexprBool()) {
      ReportError(
          "expected type bool, constexpr bool, or never on left-hand side of "
          "operator ||");
518 519
    }
  }
520

521
  if (left_result.type()->IsConstexprBool()) {
522 523 524 525 526 527
    VisitResult right_result = Visit(expr->right);
    if (!right_result.type()->IsConstexprBool()) {
      ReportError(
          "expected type constexpr bool on right-hand side of operator "
          "||");
    }
528 529 530
    return VisitResult(TypeOracle::GetConstexprBoolType(),
                       std::string("(") + left_result.constexpr_value() +
                           " || " + right_result.constexpr_value() + ")");
531
  }
532 533 534

  VisitResult right_result = Visit(expr->right);
  if (right_result.type()->IsBool()) {
535 536 537
    Block* true_block = LookupSimpleLabel(kTrueLabelName);
    Block* false_block = LookupSimpleLabel(kFalseLabelName);
    assembler().Branch(true_block, false_block);
538
    return VisitResult::NeverResult();
539 540 541 542 543
  } else if (!right_result.type()->IsNever()) {
    ReportError(
        "expected type bool or never on right-hand side of operator ||");
  }
  return right_result;
544 545 546
}

VisitResult ImplementationVisitor::Visit(LogicalAndExpression* expr) {
547
  VisitResult left_result;
548
  {
549 550 551
    Block* true_block = assembler().NewBlock(assembler().CurrentStack());
    Binding<LocalLabel> false_binding{&LabelBindingsManager::Get(),
                                      kTrueLabelName, LocalLabel{true_block}};
552
    left_result = Visit(expr->left);
553
    if (left_result.type()->IsBool()) {
554 555 556
      Block* false_block = LookupSimpleLabel(kFalseLabelName);
      assembler().Branch(true_block, false_block);
      assembler().Bind(true_block);
557
    } else if (left_result.type()->IsNever()) {
558
      assembler().Bind(true_block);
559 560 561 562
    } else if (!left_result.type()->IsConstexprBool()) {
      ReportError(
          "expected type bool, constexpr bool, or never on left-hand side of "
          "operator &&");
563 564
    }
  }
565

566
  if (left_result.type()->IsConstexprBool()) {
567 568 569 570 571 572
    VisitResult right_result = Visit(expr->right);
    if (!right_result.type()->IsConstexprBool()) {
      ReportError(
          "expected type constexpr bool on right-hand side of operator "
          "&&");
    }
573 574 575
    return VisitResult(TypeOracle::GetConstexprBoolType(),
                       std::string("(") + left_result.constexpr_value() +
                           " && " + right_result.constexpr_value() + ")");
576
  }
577 578 579

  VisitResult right_result = Visit(expr->right);
  if (right_result.type()->IsBool()) {
580 581 582
    Block* true_block = LookupSimpleLabel(kTrueLabelName);
    Block* false_block = LookupSimpleLabel(kFalseLabelName);
    assembler().Branch(true_block, false_block);
583
    return VisitResult::NeverResult();
584 585 586 587 588
  } else if (!right_result.type()->IsNever()) {
    ReportError(
        "expected type bool or never on right-hand side of operator &&");
  }
  return right_result;
589 590 591
}

VisitResult ImplementationVisitor::Visit(IncrementDecrementExpression* expr) {
592 593 594
  StackScope scope(this);
  LocationReference location_ref = GetLocationReference(expr->location);
  VisitResult current_value = GenerateFetchFromLocation(location_ref);
595
  VisitResult one = {TypeOracle::GetConstInt31Type(), "1"};
596 597
  Arguments args;
  args.parameters = {current_value, one};
598
  VisitResult assignment_value = GenerateCall(
599
      expr->op == IncrementDecrementOperator::kIncrement ? "+" : "-", args);
600 601
  GenerateAssignToLocation(location_ref, assignment_value);
  return scope.Yield(expr->postfix ? current_value : assignment_value);
602 603 604
}

VisitResult ImplementationVisitor::Visit(AssignmentExpression* expr) {
605
  StackScope scope(this);
606 607 608
  LocationReference location_ref = GetLocationReference(expr->location);
  VisitResult assignment_value;
  if (expr->op) {
609
    VisitResult location_value = GenerateFetchFromLocation(location_ref);
610 611
    assignment_value = Visit(expr->value);
    Arguments args;
612
    args.parameters = {location_value, assignment_value};
613
    assignment_value = GenerateCall(*expr->op, args);
614
    GenerateAssignToLocation(location_ref, assignment_value);
615 616
  } else {
    assignment_value = Visit(expr->value);
617
    GenerateAssignToLocation(location_ref, assignment_value);
618
  }
619
  return scope.Yield(assignment_value);
620 621 622 623 624 625
}

VisitResult ImplementationVisitor::Visit(NumberLiteralExpression* expr) {
  // TODO(tebbi): Do not silently loose precision; support 64bit literals.
  double d = std::stod(expr->number.c_str());
  int32_t i = static_cast<int32_t>(d);
626
  const Type* result_type = Declarations::LookupType(CONST_FLOAT64_TYPE_STRING);
627
  if (i == d) {
628
    if ((i >> 30) == (i >> 31)) {
629
      result_type = Declarations::LookupType(CONST_INT31_TYPE_STRING);
630
    } else {
631
      result_type = Declarations::LookupType(CONST_INT32_TYPE_STRING);
632 633
    }
  }
634
  return VisitResult{result_type, expr->number};
635 636
}

637 638 639
VisitResult ImplementationVisitor::Visit(AssumeTypeImpossibleExpression* expr) {
  VisitResult result = Visit(expr->expression);
  const Type* result_type =
640
      SubtractType(result.type(), Declarations::GetType(expr->excluded_type));
641 642 643
  if (result_type->IsNever()) {
    ReportError("unreachable code");
  }
644 645 646 647
  CHECK_EQ(LowerType(result_type), TypeVector{result_type});
  assembler().Emit(UnsafeCastInstruction{result_type});
  result.SetType(result_type);
  return result;
648 649
}

650
VisitResult ImplementationVisitor::Visit(StringLiteralExpression* expr) {
651 652 653
  return VisitResult{
      TypeOracle::GetConstStringType(),
      "\"" + expr->literal.substr(1, expr->literal.size() - 2) + "\""};
654 655
}

656
VisitResult ImplementationVisitor::GetBuiltinCode(Builtin* builtin) {
657
  if (builtin->IsExternal() || builtin->kind() != Builtin::kStub) {
658 659 660
    ReportError(
        "creating function pointers is only allowed for internal builtins with "
        "stub linkage");
661
  }
662
  const Type* type = TypeOracle::GetFunctionPointerType(
663
      builtin->signature().parameter_types.types,
664
      builtin->signature().return_type);
665
  assembler().Emit(PushCodePointerInstruction{builtin->ExternalName(), type});
666
  return VisitResult(type, assembler().TopRange(1));
667 668
}

669
VisitResult ImplementationVisitor::Visit(IdentifierExpression* expr) {
670 671
  StackScope scope(this);
  return scope.Yield(GenerateFetchFromLocation(GetLocationReference(expr)));
672 673
}

674
const Type* ImplementationVisitor::Visit(GotoStatement* stmt) {
675 676 677 678 679
  LocalLabel* label = LookupLabel(stmt->label);
  size_t parameter_count = label->parameter_types.size();
  if (stmt->arguments.size() != parameter_count) {
    ReportError("goto to label has incorrect number of parameters (expected ",
                parameter_count, " found ", stmt->arguments.size(), ")");
680 681 682
  }

  size_t i = 0;
683
  StackRange arguments = assembler().TopRange(0);
684
  for (Expression* e : stmt->arguments) {
685
    StackScope scope(this);
686
    VisitResult result = Visit(e);
687 688
    const Type* parameter_type = label->parameter_types[i++];
    result = GenerateImplicitConvert(parameter_type, result);
689
    arguments.Extend(scope.Yield(result).stack_range());
690 691
  }

692
  assembler().Goto(label->block, arguments.Size());
693
  return TypeOracle::GetNeverType();
694 695
}

696
const Type* ImplementationVisitor::Visit(IfStatement* stmt) {
697 698
  bool has_else = stmt->if_false.has_value();

699 700
  if (stmt->is_constexpr) {
    VisitResult expression_result = Visit(stmt->condition);
701

702
    if (!(expression_result.type() == TypeOracle::GetConstexprBoolType())) {
703
      std::stringstream stream;
704
      stream << "expression should return type constexpr bool "
705
             << "but returns type " << *expression_result.type();
706 707 708
      ReportError(stream.str());
    }

709 710 711 712 713 714 715 716
    Block* true_block = assembler().NewBlock();
    Block* false_block = assembler().NewBlock();
    Block* done_block = assembler().NewBlock();

    assembler().Emit(ConstexprBranchInstruction{
        expression_result.constexpr_value(), true_block, false_block});

    assembler().Bind(true_block);
717
    const Type* left_result = Visit(stmt->if_true);
718 719 720
    if (left_result == TypeOracle::GetVoidType()) {
      assembler().Goto(done_block);
    }
721

722 723
    assembler().Bind(false_block);
    const Type* right_result = TypeOracle::GetVoidType();
724
    if (has_else) {
725 726
      right_result = Visit(*stmt->if_false);
    }
727 728 729 730
    if (right_result == TypeOracle::GetVoidType()) {
      assembler().Goto(done_block);
    }

731 732 733 734 735 736
    if (left_result->IsNever() != right_result->IsNever()) {
      std::stringstream stream;
      stream << "either both or neither branches in a constexpr if statement "
                "must reach their end at"
             << PositionAsString(stmt->pos);
      ReportError(stream.str());
737 738
    }

739 740 741
    if (left_result != TypeOracle::GetNeverType()) {
      assembler().Bind(done_block);
    }
742
    return left_result;
743
  } else {
744 745 746 747 748 749
    Block* true_block = assembler().NewBlock(assembler().CurrentStack(),
                                             IsDeferred(stmt->if_true));
    Block* false_block =
        assembler().NewBlock(assembler().CurrentStack(),
                             stmt->if_false && IsDeferred(*stmt->if_false));
    GenerateExpressionBranch(stmt->condition, true_block, false_block);
750

751
    Block* done_block;
752 753
    bool live = false;
    if (has_else) {
754
      done_block = assembler().NewBlock();
755
    } else {
756
      done_block = false_block;
757 758
      live = true;
    }
759 760 761 762 763 764 765 766

    assembler().Bind(true_block);
    {
      const Type* result = Visit(stmt->if_true);
      if (result == TypeOracle::GetVoidType()) {
        live = true;
        assembler().Goto(done_block);
      }
767
    }
768 769 770 771 772 773 774 775 776 777

    if (has_else) {
      assembler().Bind(false_block);
      const Type* result = Visit(*stmt->if_false);
      if (result == TypeOracle::GetVoidType()) {
        live = true;
        assembler().Goto(done_block);
      }
    }

778
    if (live) {
779
      assembler().Bind(done_block);
780
    }
781
    return live ? TypeOracle::GetVoidType() : TypeOracle::GetNeverType();
782 783 784
  }
}

785
const Type* ImplementationVisitor::Visit(WhileStatement* stmt) {
786 787
  Block* body_block = assembler().NewBlock(assembler().CurrentStack());
  Block* exit_block = assembler().NewBlock(assembler().CurrentStack());
788

789 790 791 792
  Block* header_block = assembler().NewBlock();
  assembler().Goto(header_block);

  assembler().Bind(header_block);
793
  GenerateExpressionBranch(stmt->condition, body_block, exit_block);
794

795 796 797 798 799 800 801 802
  assembler().Bind(body_block);
  {
    BreakContinueActivator activator{exit_block, header_block};
    const Type* body_result = Visit(stmt->body);
    if (body_result != TypeOracle::GetNeverType()) {
      assembler().Goto(header_block);
    }
  }
803

804
  assembler().Bind(exit_block);
805
  return TypeOracle::GetVoidType();
806 807
}

808
const Type* ImplementationVisitor::Visit(BlockStatement* block) {
809
  BlockBindings<LocalValue> block_bindings(&ValueBindingsManager::Get());
810
  const Type* type = TypeOracle::GetVoidType();
811
  for (Statement* s : block->statements) {
812
    CurrentSourcePosition::Scope source_position(s->pos);
813
    if (type->IsNever()) {
814 815 816 817 818 819
      ReportError("statement after non-returning statement");
    }
    if (auto* var_declaration = VarDeclarationStatement::DynamicCast(s)) {
      type = Visit(var_declaration, &block_bindings);
    } else {
      type = Visit(s);
820 821 822 823 824
    }
  }
  return type;
}

825
const Type* ImplementationVisitor::Visit(DebugStatement* stmt) {
826
#if defined(DEBUG)
827 828 829
  assembler().Emit(PrintConstantStringInstruction{"halting because of '" +
                                                  stmt->reason + "' at " +
                                                  PositionAsString(stmt->pos)});
830
#endif
831 832 833
  assembler().Emit(AbortInstruction{stmt->never_continues
                                        ? AbortInstruction::Kind::kUnreachable
                                        : AbortInstruction::Kind::kDebugBreak});
834
  if (stmt->never_continues) {
835
    return TypeOracle::GetNeverType();
836
  } else {
837
    return TypeOracle::GetVoidType();
838 839 840
  }
}

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
namespace {

std::string FormatAssertSource(const std::string& str) {
  // Replace all whitespace characters with a space character.
  std::string str_no_newlines = str;
  std::replace_if(str_no_newlines.begin(), str_no_newlines.end(),
                  [](unsigned char c) { return isspace(c); }, ' ');

  // str might include indentation, squash multiple space characters into one.
  std::string result;
  std::unique_copy(str_no_newlines.begin(), str_no_newlines.end(),
                   std::back_inserter(result),
                   [](char a, char b) { return a == ' ' && b == ' '; });
  return result;
}

}  // namespace

859
const Type* ImplementationVisitor::Visit(AssertStatement* stmt) {
860
  bool do_check = !stmt->debug_only;
861
#if defined(DEBUG)
862 863 864 865 866 867 868 869 870 871 872 873
  do_check = true;
#endif
  if (do_check) {
    // CSA_ASSERT & co. are not used here on purpose for two reasons. First,
    // Torque allows and handles two types of expressions in the if protocol
    // automagically, ones that return TNode<BoolT> and those that use the
    // BranchIf(..., Label* true, Label* false) idiom. Because the machinery to
    // handle this is embedded in the expression handling and to it's not
    // possible to make the decision to use CSA_ASSERT or CSA_ASSERT_BRANCH
    // isn't trivial up-front. Secondly, on failure, the assert text should be
    // the corresponding Torque code, not the -gen.cc code, which would be the
    // case when using CSA_ASSERT_XXX.
874 875 876
    Block* true_block = assembler().NewBlock(assembler().CurrentStack());
    Block* false_block = assembler().NewBlock(assembler().CurrentStack(), true);
    GenerateExpressionBranch(stmt->expression, true_block, false_block);
877

878
    assembler().Bind(false_block);
879 880 881 882

    assembler().Emit(AbortInstruction{
        AbortInstruction::Kind::kAssertionFailure,
        "Torque assert '" + FormatAssertSource(stmt->source) + "' failed"});
883

884
    assembler().Bind(true_block);
885
  }
886
  return TypeOracle::GetVoidType();
887 888
}

889 890
const Type* ImplementationVisitor::Visit(ExpressionStatement* stmt) {
  const Type* type = Visit(stmt->expression).type();
891
  return type->IsNever() ? type : TypeOracle::GetVoidType();
892 893
}

894
const Type* ImplementationVisitor::Visit(ReturnStatement* stmt) {
895
  Callable* current_callable = CurrentCallable::Get();
896
  if (current_callable->signature().return_type->IsNever()) {
897
    std::stringstream s;
898
    s << "cannot return from a function with return type never";
899 900
    ReportError(s.str());
  }
901 902
  LocalLabel* end =
      current_callable->IsMacro() ? LookupLabel("_macro_end") : nullptr;
903 904 905 906
  if (current_callable->HasReturnValue()) {
    if (!stmt->value) {
      std::stringstream s;
      s << "return expression needs to be specified for a return type of "
907
        << *current_callable->signature().return_type;
908 909 910 911
      ReportError(s.str());
    }
    VisitResult expression_result = Visit(*stmt->value);
    VisitResult return_result = GenerateImplicitConvert(
912
        current_callable->signature().return_type, expression_result);
913
    if (current_callable->IsMacro()) {
914 915 916 917
      if (return_result.IsOnStack()) {
        StackRange return_value_range =
            GenerateLabelGoto(end, return_result.stack_range());
        SetReturnValue(VisitResult(return_result.type(), return_value_range));
918
      } else {
919 920
        GenerateLabelGoto(end);
        SetReturnValue(return_result);
921
      }
922 923
    } else if (current_callable->IsBuiltin()) {
      assembler().Emit(ReturnInstruction{});
924 925 926 927 928 929 930
    } else {
      UNREACHABLE();
    }
  } else {
    if (stmt->value) {
      std::stringstream s;
      s << "return expression can't be specified for a void or never return "
931
           "type";
932 933 934 935 936
      ReportError(s.str());
    }
    GenerateLabelGoto(end);
  }
  current_callable->IncrementReturns();
937
  return TypeOracle::GetNeverType();
938 939
}

940
const Type* ImplementationVisitor::Visit(ForOfLoopStatement* stmt) {
941
  VisitResult expression_result = Visit(stmt->iterable);
942 943 944
  VisitResult begin = stmt->begin
                          ? Visit(*stmt->begin)
                          : VisitResult(TypeOracle::GetConstInt31Type(), "0");
945

946 947 948
  VisitResult end = stmt->end
                        ? Visit(*stmt->end)
                        : GenerateCall(".length", {{expression_result}, {}});
949

950
  const Type* common_type = GetCommonType(begin.type(), end.type());
951
  VisitResult index = GenerateImplicitConvert(common_type, begin);
952

953 954 955
  Block* body_block = assembler().NewBlock();
  Block* increment_block = assembler().NewBlock(assembler().CurrentStack());
  Block* exit_block = assembler().NewBlock(assembler().CurrentStack());
956

957
  Block* header_block = assembler().NewBlock();
958

959
  assembler().Goto(header_block);
960

961
  assembler().Bind(header_block);
962

963
  BreakContinueActivator activator(exit_block, increment_block);
964 965 966 967 968 969 970 971 972 973 974 975 976 977

  {
    StackScope comparison_scope(this);
    VisitResult result = GenerateCall("<", {{index, end}, {}});
    if (result.type() != TypeOracle::GetBoolType()) {
      ReportError("operator < with arguments(", *index.type(), ", ",
                  *end.type(),
                  ")  used in for-of loop has to return type bool, but "
                  "returned type ",
                  *result.type());
    }
    comparison_scope.Yield(result);
  }
  assembler().Branch(body_block, exit_block);
978

979 980 981 982 983 984 985 986
  assembler().Bind(body_block);
  {
    VisitResult element_result;
    {
      StackScope element_scope(this);
      VisitResult result = GenerateCall("[]", {{expression_result, index}, {}});
      if (stmt->var_declaration->type) {
        const Type* declared_type =
987
            Declarations::GetType(*stmt->var_declaration->type);
988 989 990 991
        result = GenerateImplicitConvert(declared_type, result);
      }
      element_result = element_scope.Yield(result);
    }
992 993 994
    Binding<LocalValue> element_var_binding{&ValueBindingsManager::Get(),
                                            stmt->var_declaration->name,
                                            LocalValue{true, element_result}};
995 996 997
    Visit(stmt->body);
  }
  assembler().Goto(increment_block);
998

999 1000 1001 1002 1003
  assembler().Bind(increment_block);
  {
    Arguments increment_args;
    increment_args.parameters = {index, {TypeOracle::GetConstInt31Type(), "1"}};
    VisitResult increment_result = GenerateCall("+", increment_args);
1004

1005 1006 1007
    GenerateAssignToLocation(LocationReference::VariableAccess(index),
                             increment_result);
  }
1008

1009
  assembler().Goto(header_block);
1010

1011
  assembler().Bind(exit_block);
1012
  return TypeOracle::GetVoidType();
1013 1014
}

1015
VisitResult ImplementationVisitor::Visit(TryLabelExpression* expr) {
1016 1017 1018 1019
  size_t parameter_count = expr->label_block->parameters.names.size();
  std::vector<VisitResult> parameters;

  Block* label_block = nullptr;
1020
  Block* done_block = assembler().NewBlock();
1021
  VisitResult try_result;
1022 1023

  {
1024 1025 1026 1027 1028 1029 1030 1031
    CurrentSourcePosition::Scope source_position(expr->label_block->pos);
    if (expr->label_block->parameters.has_varargs) {
      ReportError("cannot use ... for label parameters");
    }
    Stack<const Type*> label_input_stack = assembler().CurrentStack();
    TypeVector parameter_types;
    for (size_t i = 0; i < parameter_count; ++i) {
      const Type* type =
1032
          Declarations::GetType(expr->label_block->parameters.types[i]);
1033 1034 1035
      parameter_types.push_back(type);
      if (type->IsConstexpr()) {
        ReportError("no constexpr type allowed for label arguments");
1036
      }
1037 1038
      StackRange range = label_input_stack.PushMany(LowerType(type));
      parameters.push_back(VisitResult(type, range));
1039
    }
1040 1041 1042 1043 1044 1045
    label_block = assembler().NewBlock(label_input_stack,
                                       IsDeferred(expr->label_block->body));

    Binding<LocalLabel> label_binding{&LabelBindingsManager::Get(),
                                      expr->label_block->label,
                                      LocalLabel{label_block, parameter_types}};
1046 1047

    // Visit try
1048 1049 1050 1051 1052
    StackScope stack_scope(this);
    try_result = Visit(expr->try_expression);
    if (try_result.type() != TypeOracle::GetNeverType()) {
      try_result = stack_scope.Yield(try_result);
      assembler().Goto(done_block);
1053 1054 1055
    }
  }

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
  // Visit and output the code for the label block. If the label block falls
  // through, then the try must not return a value. Also, if the try doesn't
  // fall through, but the label does, then overall the try-label block
  // returns type void.
  assembler().Bind(label_block);
  const Type* label_result;
  {
    BlockBindings<LocalValue> parameter_bindings(&ValueBindingsManager::Get());
    for (size_t i = 0; i < parameter_count; ++i) {
      parameter_bindings.Add(expr->label_block->parameters.names[i],
                             LocalValue{true, parameters[i]});
1067
    }
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

    label_result = Visit(expr->label_block->body);
  }
  if (!try_result.type()->IsVoidOrNever() && label_result->IsVoid()) {
    ReportError(
        "otherwise clauses cannot fall through in a non-void expression");
  }
  if (label_result != TypeOracle::GetNeverType()) {
    assembler().Goto(done_block);
  }
  if (label_result->IsVoid() && try_result.type()->IsNever()) {
    try_result =
        VisitResult(TypeOracle::GetVoidType(), try_result.stack_range());
1081 1082
  }

1083
  if (!try_result.type()->IsNever()) {
1084
    assembler().Bind(done_block);
1085 1086 1087 1088
  }
  return try_result;
}

1089 1090 1091 1092
VisitResult ImplementationVisitor::Visit(StatementExpression* expr) {
  return VisitResult{Visit(expr->statement), assembler().TopRange(0)};
}

1093
const Type* ImplementationVisitor::Visit(BreakStatement* stmt) {
1094 1095
  base::Optional<Binding<LocalLabel>*> break_label = TryLookupLabel("_break");
  if (!break_label) {
1096
    ReportError("break used outside of loop");
1097
  }
1098
  assembler().Goto((*break_label)->block);
1099
  return TypeOracle::GetNeverType();
1100 1101
}

1102
const Type* ImplementationVisitor::Visit(ContinueStatement* stmt) {
1103 1104 1105
  base::Optional<Binding<LocalLabel>*> continue_label =
      TryLookupLabel("_continue");
  if (!continue_label) {
1106
    ReportError("continue used outside of loop");
1107
  }
1108
  assembler().Goto((*continue_label)->block);
1109
  return TypeOracle::GetNeverType();
1110 1111
}

1112
const Type* ImplementationVisitor::Visit(ForLoopStatement* stmt) {
1113
  BlockBindings<LocalValue> loop_bindings(&ValueBindingsManager::Get());
1114

1115 1116 1117 1118
  if (stmt->var_declaration) Visit(*stmt->var_declaration, &loop_bindings);

  Block* body_block = assembler().NewBlock(assembler().CurrentStack());
  Block* exit_block = assembler().NewBlock(assembler().CurrentStack());
1119

1120 1121 1122
  Block* header_block = assembler().NewBlock();
  assembler().Goto(header_block);
  assembler().Bind(header_block);
1123

1124 1125
  // The continue label is where "continue" statements jump to. If no action
  // expression is provided, we jump directly to the header.
1126
  Block* continue_block = header_block;
1127

1128
  // The action label is only needed when an action expression was provided.
1129
  Block* action_block = nullptr;
1130
  if (stmt->action) {
1131
    action_block = assembler().NewBlock();
1132 1133

    // The action expression needs to be executed on a continue.
1134
    continue_block = action_block;
1135 1136 1137
  }

  if (stmt->test) {
1138
    GenerateExpressionBranch(*stmt->test, body_block, exit_block);
1139
  } else {
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    assembler().Goto(body_block);
  }

  assembler().Bind(body_block);
  {
    BreakContinueActivator activator(exit_block, continue_block);
    const Type* body_result = Visit(stmt->body);
    if (body_result != TypeOracle::GetNeverType()) {
      assembler().Goto(continue_block);
    }
1150 1151
  }

1152
  if (stmt->action) {
1153
    assembler().Bind(action_block);
1154 1155 1156 1157
    const Type* action_result = Visit(*stmt->action);
    if (action_result != TypeOracle::GetNeverType()) {
      assembler().Goto(header_block);
    }
1158 1159
  }

1160
  assembler().Bind(exit_block);
1161
  return TypeOracle::GetVoidType();
1162 1163 1164
}

void ImplementationVisitor::GenerateImplementation(const std::string& dir,
1165 1166
                                                   Namespace* nspace) {
  std::string new_source(nspace->source());
1167
  std::string base_file_name =
1168
      "builtins-" + DashifyString(nspace->name()) + "-from-dsl-gen";
1169 1170

  std::string source_file_name = dir + "/" + base_file_name + ".cc";
1171
  ReplaceFileContentsIfDifferent(source_file_name, new_source);
1172
  std::string new_header(nspace->header());
1173
  std::string header_file_name = dir + "/" + base_file_name + ".h";
1174 1175 1176 1177
  ReplaceFileContentsIfDifferent(header_file_name, new_header);
}

void ImplementationVisitor::GenerateMacroFunctionDeclaration(
1178
    std::ostream& o, const std::string& macro_prefix, Macro* macro) {
1179
  GenerateFunctionDeclaration(o, macro_prefix, macro->ExternalName(),
1180 1181 1182 1183 1184 1185
                              macro->signature(), macro->parameter_names());
}

void ImplementationVisitor::GenerateFunctionDeclaration(
    std::ostream& o, const std::string& macro_prefix, const std::string& name,
    const Signature& signature, const NameVector& parameter_names) {
1186
  if (GlobalContext::verbose()) {
1187
    std::cout << "generating source for declaration " << name << "\n";
1188 1189
  }

1190 1191 1192 1193
  if (signature.return_type->IsVoidOrNever()) {
    o << "void";
  } else {
    o << signature.return_type->GetGeneratedTypeName();
1194
  }
1195
  o << " " << macro_prefix << name << "(";
1196

1197 1198
  DCHECK_EQ(signature.types().size(), parameter_names.size());
  auto type_iterator = signature.types().begin();
1199
  bool first = true;
1200
  for (const std::string& name : parameter_names) {
1201 1202 1203
    if (!first) {
      o << ", ";
    }
1204
    const Type* parameter_type = *type_iterator;
1205
    const std::string& generated_type_name =
1206
        parameter_type->GetGeneratedTypeName();
1207
    o << generated_type_name << " " << ExternalParameterName(name);
1208 1209 1210 1211
    type_iterator++;
    first = false;
  }

1212
  for (const LabelDeclaration& label_info : signature.labels) {
1213 1214 1215
    if (!first) {
      o << ", ";
    }
1216
    o << "compiler::CodeAssemblerLabel* " << ExternalLabelName(label_info.name);
1217
    size_t i = 0;
1218
    for (const Type* type : label_info.types) {
1219
      std::string generated_type_name("compiler::TypedCodeAssemblerVariable<");
1220
      generated_type_name += type->GetGeneratedTNodeTypeName();
1221 1222
      generated_type_name += ">*";
      o << ", ";
1223 1224
      o << generated_type_name << " "
        << ExternalLabelParameterName(label_info.name, i);
1225
      ++i;
1226 1227 1228 1229 1230 1231
    }
  }

  o << ")";
}

1232 1233
namespace {

1234
void FailCallableLookup(const std::string& reason, const QualifiedName& name,
1235 1236
                        const Arguments& arguments,
                        const std::vector<Signature>& candidates) {
1237 1238 1239 1240 1241 1242
  std::stringstream stream;
  stream << "\n"
         << reason << ": \n  " << name << "("
         << arguments.parameters.GetTypeVector() << ")";
  if (arguments.labels.size() != 0) {
    stream << " labels ";
1243 1244 1245
    for (size_t i = 0; i < arguments.labels.size(); ++i) {
      stream << arguments.labels[i]->name() << "("
             << arguments.labels[i]->parameter_types << ")";
1246 1247 1248
    }
  }
  stream << "\ncandidates are:";
1249 1250 1251 1252
  for (const Signature& signature : candidates) {
    stream << "\n  " << name;
    PrintSignature(stream, signature, false);
  }
1253 1254 1255
  ReportError(stream.str());
}

1256 1257 1258 1259 1260 1261 1262 1263
Callable* GetOrCreateSpecialization(const SpecializationKey& key) {
  if (base::Optional<Callable*> specialization =
          key.generic->GetSpecialization(key.specialized_types)) {
    return *specialization;
  }
  return DeclarationVisitor().SpecializeImplicit(key);
}

1264 1265
}  // namespace

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
base::Optional<Binding<LocalValue>*> ImplementationVisitor::TryLookupLocalValue(
    const std::string& name) {
  return ValueBindingsManager::Get().TryLookup(name);
}

base::Optional<Binding<LocalLabel>*> ImplementationVisitor::TryLookupLabel(
    const std::string& name) {
  return LabelBindingsManager::Get().TryLookup(name);
}

Binding<LocalLabel>* ImplementationVisitor::LookupLabel(
    const std::string& name) {
  base::Optional<Binding<LocalLabel>*> label = TryLookupLabel(name);
  if (!label) ReportError("cannot find label ", name);
  return *label;
}

Block* ImplementationVisitor::LookupSimpleLabel(const std::string& name) {
  LocalLabel* label = LookupLabel(name);
  if (!label->parameter_types.empty()) {
    ReportError("label ", name,
                "was expected to have no parameters, but has parameters (",
                label->parameter_types, ")");
  }
  return label->block;
}

1293
Callable* ImplementationVisitor::LookupCall(
1294
    const QualifiedName& name, const Arguments& arguments,
1295
    const TypeVector& specialization_types) {
1296 1297
  Callable* result = nullptr;
  TypeVector parameter_types(arguments.parameters.GetTypeVector());
1298 1299 1300 1301 1302

  std::vector<Declarable*> overloads;
  std::vector<Signature> overload_signatures;
  for (Declarable* declarable : Declarations::Lookup(name)) {
    if (Generic* generic = Generic::DynamicCast(declarable)) {
1303 1304 1305 1306
      base::Optional<TypeVector> inferred_specialization_types =
          generic->InferSpecializationTypes(specialization_types,
                                            parameter_types);
      if (!inferred_specialization_types) continue;
1307 1308 1309
      overloads.push_back(generic);
      overload_signatures.push_back(
          DeclarationVisitor().MakeSpecializedSignature(
1310
              SpecializationKey{generic, *inferred_specialization_types}));
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    } else if (Callable* callable = Callable::DynamicCast(declarable)) {
      overloads.push_back(callable);
      overload_signatures.push_back(callable->signature());
    }
  }
  // Indices of candidates in overloads/overload_signatures.
  std::vector<size_t> candidates;
  for (size_t i = 0; i < overloads.size(); ++i) {
    const Signature& signature = overload_signatures[i];
    bool try_bool_context = arguments.labels.size() == 0 &&
                            signature.return_type == TypeOracle::GetNeverType();
    base::Optional<Binding<LocalLabel>*> true_label;
    base::Optional<Binding<LocalLabel>*> false_label;
    if (try_bool_context) {
      true_label = TryLookupLabel(kTrueLabelName);
      false_label = TryLookupLabel(kFalseLabelName);
    }
    if (IsCompatibleSignature(signature, parameter_types, arguments.labels) ||
        (true_label && false_label &&
         IsCompatibleSignature(signature, parameter_types,
                               {*true_label, *false_label}))) {
      candidates.push_back(i);
    }
  }

  if (overloads.empty()) {
    std::stringstream stream;
    stream << "no matching declaration found for " << name;
    ReportError(stream.str());
  } else if (candidates.empty()) {
    FailCallableLookup("cannot find suitable callable with name", name,
                       arguments, overload_signatures);
  }

  auto is_better_candidate = [&](size_t a, size_t b) {
    return ParameterDifference(overload_signatures[a].GetExplicitTypes(),
                               parameter_types)
        .StrictlyBetterThan(ParameterDifference(
            overload_signatures[b].GetExplicitTypes(), parameter_types));
  };

  size_t best = *std::min_element(candidates.begin(), candidates.end(),
                                  is_better_candidate);
  // This check is contained in libstdc++'s std::min_element.
  DCHECK(!is_better_candidate(best, best));
  for (size_t candidate : candidates) {
    if (candidate != best && !is_better_candidate(best, candidate)) {
      std::vector<Signature> candidate_signatures;
      for (size_t i : candidates) {
        candidate_signatures.push_back(overload_signatures[i]);
1361
      }
1362 1363
      FailCallableLookup("ambiguous callable", name, arguments,
                         candidate_signatures);
1364
    }
1365
  }
1366

1367 1368
  if (Generic* generic = Generic::DynamicCast(overloads[best])) {
    result = GetOrCreateSpecialization(
1369 1370
        SpecializationKey{generic, *generic->InferSpecializationTypes(
                                       specialization_types, parameter_types)});
1371
  } else {
1372
    result = Callable::cast(overloads[best]);
1373 1374 1375
  }

  size_t caller_size = parameter_types.size();
1376 1377
  size_t callee_size =
      result->signature().types().size() - result->signature().implicit_count;
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  if (caller_size != callee_size &&
      !result->signature().parameter_types.var_args) {
    std::stringstream stream;
    stream << "parameter count mismatch calling " << *result << " - expected "
           << std::to_string(callee_size) << ", found "
           << std::to_string(caller_size);
    ReportError(stream.str());
  }

  return result;
}

1390
const Type* ImplementationVisitor::GetCommonType(const Type* left,
1391
                                                 const Type* right) {
1392
  const Type* common_type;
1393
  if (IsAssignableFrom(left, right)) {
1394
    common_type = left;
1395
  } else if (IsAssignableFrom(right, left)) {
1396 1397
    common_type = right;
  } else {
1398
    common_type = TypeOracle::GetUnionType(left, right);
1399
  }
1400
  common_type = common_type->NonConstexprVersion();
1401 1402 1403 1404
  return common_type;
}

VisitResult ImplementationVisitor::GenerateCopy(const VisitResult& to_copy) {
1405 1406 1407 1408 1409
  if (to_copy.IsOnStack()) {
    return VisitResult(to_copy.type(),
                       assembler().Peek(to_copy.stack_range(), to_copy.type()));
  }
  return to_copy;
1410 1411
}

1412
VisitResult ImplementationVisitor::Visit(StructExpression* decl) {
1413 1414
  const Type* raw_type = Declarations::LookupType(
      QualifiedName(decl->namespace_qualification, decl->name));
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
  if (!raw_type->IsStructType()) {
    std::stringstream s;
    s << decl->name << " is not a struct but used like one ";
    ReportError(s.str());
  }
  const StructType* struct_type = StructType::cast(raw_type);
  if (struct_type->fields().size() != decl->expressions.size()) {
    std::stringstream s;
    s << "initializer count mismatch for struct " << decl->name << " (expected "
      << struct_type->fields().size() << ", found " << decl->expressions.size()
      << ")";
    ReportError(s.str());
  }
1428 1429 1430 1431 1432
  StackRange stack_range = assembler().TopRange(0);
  for (size_t i = 0; i < struct_type->fields().size(); ++i) {
    const NameAndType& field = struct_type->fields()[i];
    StackScope scope(this);
    VisitResult value = Visit(decl->expressions[i]);
1433
    value = GenerateImplicitConvert(field.type, value);
1434
    stack_range.Extend(scope.Yield(value).stack_range());
1435
  }
1436
  return VisitResult(struct_type, stack_range);
1437 1438
}

1439
LocationReference ImplementationVisitor::GetLocationReference(
1440
    Expression* location) {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
  switch (location->kind) {
    case AstNode::Kind::kIdentifierExpression:
      return GetLocationReference(static_cast<IdentifierExpression*>(location));
    case AstNode::Kind::kFieldAccessExpression:
      return GetLocationReference(
          static_cast<FieldAccessExpression*>(location));
    case AstNode::Kind::kElementAccessExpression:
      return GetLocationReference(
          static_cast<ElementAccessExpression*>(location));
    default:
1451
      return LocationReference::Temporary(Visit(location), "expression");
1452 1453 1454
  }
}

1455 1456
LocationReference ImplementationVisitor::GetLocationReference(
    FieldAccessExpression* expr) {
1457 1458 1459 1460 1461
  LocationReference reference = GetLocationReference(expr->object);
  if (reference.IsVariableAccess() &&
      reference.variable().type()->IsStructType()) {
    return LocationReference::VariableAccess(
        ProjectStructField(reference.variable(), expr->field));
1462
  }
1463 1464 1465 1466
  if (reference.IsTemporary() && reference.temporary().type()->IsStructType()) {
    return LocationReference::Temporary(
        ProjectStructField(reference.temporary(), expr->field),
        reference.temporary_description());
1467
  }
1468 1469
  return LocationReference::FieldAccess(GenerateFetchFromLocation(reference),
                                        expr->field);
1470 1471
}

1472 1473 1474 1475 1476
LocationReference ImplementationVisitor::GetLocationReference(
    ElementAccessExpression* expr) {
  VisitResult array = Visit(expr->array);
  VisitResult index = Visit(expr->index);
  return LocationReference::ArrayAccess(array, index);
1477 1478
}

1479 1480
LocationReference ImplementationVisitor::GetLocationReference(
    IdentifierExpression* expr) {
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  if (expr->namespace_qualification.empty()) {
    if (base::Optional<Binding<LocalValue>*> value =
            TryLookupLocalValue(expr->name)) {
      if (expr->generic_arguments.size() != 0) {
        ReportError("cannot have generic parameters on local name ",
                    expr->name);
      }
      if ((*value)->is_const) {
        return LocationReference::Temporary((*value)->value,
                                            "constant value " + expr->name);
      }
      return LocationReference::VariableAccess((*value)->value);
1493 1494 1495
    }
  }

1496
  QualifiedName name = QualifiedName(expr->namespace_qualification, expr->name);
1497 1498
  if (base::Optional<Builtin*> builtin = Declarations::TryLookupBuiltin(name)) {
    return LocationReference::Temporary(GetBuiltinCode(*builtin),
1499 1500 1501
                                        "builtin " + expr->name);
  }
  if (expr->generic_arguments.size() != 0) {
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
    Generic* generic = Declarations::LookupUniqueGeneric(name);
    Callable* specialization = GetOrCreateSpecialization(
        SpecializationKey{generic, GetTypeVector(expr->generic_arguments)});
    if (Builtin* builtin = Builtin::DynamicCast(specialization)) {
      DCHECK(!builtin->IsExternal());
      return LocationReference::Temporary(GetBuiltinCode(builtin),
                                          "builtin " + expr->name);
    } else {
      ReportError("cannot create function pointer for non-builtin ",
                  generic->name());
    }
1513
  }
1514
  Value* value = Declarations::LookupValue(name);
1515
  if (auto* constant = NamespaceConstant::DynamicCast(value)) {
1516 1517
    if (constant->type()->IsConstexpr()) {
      return LocationReference::Temporary(
1518 1519 1520
          VisitResult(constant->type(), constant->ExternalAssemblerName() +
                                            "(state_)." +
                                            constant->constant_name() + "()"),
1521
          "namespace constant " + expr->name);
1522
    }
1523
    assembler().Emit(NamespaceConstantInstruction{constant});
1524 1525 1526 1527
    StackRange stack_range =
        assembler().TopRange(LoweredSlotCount(constant->type()));
    return LocationReference::Temporary(
        VisitResult(constant->type(), stack_range),
1528
        "namespace constant " + expr->name);
1529
  }
1530 1531 1532
  ExternConstant* constant = ExternConstant::cast(value);
  return LocationReference::Temporary(constant->value(),
                                      "extern value " + expr->name);
1533 1534
}

1535 1536 1537 1538 1539 1540
VisitResult ImplementationVisitor::GenerateFetchFromLocation(
    const LocationReference& reference) {
  if (reference.IsTemporary()) {
    return GenerateCopy(reference.temporary());
  } else if (reference.IsVariableAccess()) {
    return GenerateCopy(reference.variable());
1541
  } else {
1542 1543 1544
    DCHECK(reference.IsCallAccess());
    return GenerateCall(reference.eval_function(),
                        Arguments{reference.call_arguments(), {}});
1545 1546 1547
  }
}

1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
void ImplementationVisitor::GenerateAssignToLocation(
    const LocationReference& reference, const VisitResult& assignment_value) {
  if (reference.IsCallAccess()) {
    Arguments arguments{reference.call_arguments(), {}};
    arguments.parameters.push_back(assignment_value);
    GenerateCall(reference.assign_function(), arguments);
  } else if (reference.IsVariableAccess()) {
    VisitResult variable = reference.variable();
    VisitResult converted_value =
        GenerateImplicitConvert(variable.type(), assignment_value);
    assembler().Poke(variable.stack_range(), converted_value.stack_range(),
                     variable.type());
1560
  } else {
1561 1562
    DCHECK(reference.IsTemporary());
    ReportError("cannot assign to ", reference.temporary_description());
1563 1564 1565
  }
}

1566
VisitResult ImplementationVisitor::GeneratePointerCall(
1567
    Expression* callee, const Arguments& arguments, bool is_tailcall) {
1568
  StackScope scope(this);
1569 1570 1571 1572 1573
  TypeVector parameter_types(arguments.parameters.GetTypeVector());
  VisitResult callee_result = Visit(callee);
  if (!callee_result.type()->IsFunctionPointerType()) {
    std::stringstream stream;
    stream << "Expected a function pointer type but found "
1574
           << *callee_result.type();
1575 1576 1577 1578 1579
    ReportError(stream.str());
  }
  const FunctionPointerType* type =
      FunctionPointerType::cast(callee_result.type());

1580 1581 1582
  if (type->parameter_types().size() != parameter_types.size()) {
    std::stringstream stream;
    stream << "parameter count mismatch calling function pointer with Type: "
1583
           << *type << " - expected "
1584 1585 1586 1587 1588 1589
           << std::to_string(type->parameter_types().size()) << ", found "
           << std::to_string(parameter_types.size());
    ReportError(stream.str());
  }

  ParameterTypes types{type->parameter_types(), false};
1590 1591 1592
  Signature sig;
  sig.parameter_types = types;
  if (!IsCompatibleSignature(sig, parameter_types, {})) {
1593 1594 1595 1596 1597 1598 1599
    std::stringstream stream;
    stream << "parameters do not match function pointer signature. Expected: ("
           << type->parameter_types() << ") but got: (" << parameter_types
           << ")";
    ReportError(stream.str());
  }

1600 1601
  callee_result = GenerateCopy(callee_result);
  StackRange arg_range = assembler().TopRange(0);
1602 1603
  for (size_t current = 0; current < arguments.parameters.size(); ++current) {
    const Type* to_type = type->parameter_types()[current];
1604 1605 1606
    arg_range.Extend(
        GenerateImplicitConvert(to_type, arguments.parameters[current])
            .stack_range());
1607 1608
  }

1609 1610
  assembler().Emit(
      CallBuiltinPointerInstruction{is_tailcall, type, arg_range.Size()});
1611

1612 1613
  if (is_tailcall) {
    return VisitResult::NeverResult();
1614
  }
1615 1616
  DCHECK_EQ(1, LoweredSlotCount(type->return_type()));
  return scope.Yield(VisitResult(type->return_type(), assembler().TopRange(1)));
1617 1618
}

1619
VisitResult ImplementationVisitor::GenerateCall(
1620
    const QualifiedName& callable_name, Arguments arguments,
1621 1622 1623
    const TypeVector& specialization_types, bool is_tailcall) {
  Callable* callable =
      LookupCall(callable_name, arguments, specialization_types);
1624

1625
  // Operators used in a branching context can also be function calls that never
1626
  // return but have a True and False label
1627 1628
  if (arguments.labels.size() == 0 &&
      callable->signature().labels.size() == 2) {
1629
    Binding<LocalLabel>* true_label = LookupLabel(kTrueLabelName);
1630
    arguments.labels.push_back(true_label);
1631
    Binding<LocalLabel>* false_label = LookupLabel(kFalseLabelName);
1632 1633 1634
    arguments.labels.push_back(false_label);
  }

1635
  const Type* return_type = callable->signature().return_type;
1636

1637 1638 1639
  std::vector<VisitResult> converted_arguments;
  StackRange argument_range = assembler().TopRange(0);
  std::vector<std::string> constexpr_arguments;
1640 1641 1642 1643

  for (size_t current = 0; current < callable->signature().implicit_count;
       ++current) {
    std::string implicit_name = callable->signature().parameter_names[current];
1644 1645 1646
    base::Optional<Binding<LocalValue>*> val =
        TryLookupLocalValue(implicit_name);
    if (!val) {
1647 1648
      ReportError("implicit parameter '", implicit_name,
                  "' required for call to '", callable_name,
1649 1650 1651
                  "' is not defined");
    }
    VisitResult converted = GenerateImplicitConvert(
1652
        callable->signature().parameter_types.types[current], (*val)->value);
1653 1654 1655 1656 1657 1658 1659 1660
    converted_arguments.push_back(converted);
    if (converted.IsOnStack()) {
      argument_range.Extend(converted.stack_range());
    } else {
      constexpr_arguments.push_back(converted.constexpr_value());
    }
  }

1661
  for (size_t current = 0; current < arguments.parameters.size(); ++current) {
1662 1663 1664 1665 1666 1667
    size_t current_after_implicit =
        current + callable->signature().implicit_count;
    const Type* to_type =
        (current_after_implicit >= callable->signature().types().size())
            ? TypeOracle::GetObjectType()
            : callable->signature().types()[current_after_implicit];
1668
    VisitResult converted =
1669
        GenerateImplicitConvert(to_type, arguments.parameters[current]);
1670 1671 1672
    converted_arguments.push_back(converted);
    if (converted.IsOnStack()) {
      argument_range.Extend(converted.stack_range());
1673
    } else {
1674
      constexpr_arguments.push_back(converted.constexpr_value());
1675 1676
    }
  }
1677

1678
  if (GlobalContext::verbose()) {
1679
    std::cout << "generating code for call to " << callable_name << "\n";
1680 1681
  }

1682
  size_t label_count = callable->signature().labels.size();
1683 1684
  if (label_count != arguments.labels.size()) {
    std::stringstream s;
1685 1686 1687
    s << "unexpected number of otherwise labels for "
      << callable->ReadableName() << " (expected "
      << std::to_string(label_count) << " found "
1688
      << std::to_string(arguments.labels.size()) << ")";
1689 1690
    ReportError(s.str());
  }
1691

1692
  if (callable->IsTransitioning()) {
1693
    if (!CurrentCallable::Get()->IsTransitioning()) {
1694
      std::stringstream s;
1695
      s << *CurrentCallable::Get()
1696 1697 1698 1699 1700 1701
        << " isn't marked transitioning but calls the transitioning "
        << *callable;
      ReportError(s.str());
    }
  }

1702
  if (auto* builtin = Builtin::DynamicCast(callable)) {
1703 1704 1705 1706
    base::Optional<Block*> catch_block = GetCatchBlock();
    assembler().Emit(CallBuiltinInstruction{
        is_tailcall, builtin, argument_range.Size(), catch_block});
    GenerateCatchBlock(catch_block);
1707 1708 1709 1710 1711 1712 1713 1714
    if (is_tailcall) {
      return VisitResult::NeverResult();
    } else {
      size_t slot_count = LoweredSlotCount(return_type);
      DCHECK_LE(slot_count, 1);
      // TODO(tebbi): Actually, builtins have to return a value, so we should
      // assert slot_count == 1 here.
      return VisitResult(return_type, assembler().TopRange(slot_count));
1715
    }
1716 1717 1718
  } else if (auto* macro = Macro::DynamicCast(callable)) {
    if (is_tailcall) {
      ReportError("can't tail call a macro");
1719
    }
1720 1721 1722
    if (return_type->IsConstexpr()) {
      DCHECK_EQ(0, arguments.labels.size());
      std::stringstream result;
1723
      result << "(" << macro->external_assembler_name() << "(state_)."
1724
             << macro->ExternalName() << "(";
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
      bool first = true;
      for (VisitResult arg : arguments.parameters) {
        DCHECK(!arg.IsOnStack());
        if (!first) {
          result << ", ";
        }
        first = false;
        result << arg.constexpr_value();
      }
      result << "))";
      return VisitResult(return_type, result.str());
    } else if (arguments.labels.empty() &&
               return_type != TypeOracle::GetNeverType()) {
1738 1739 1740 1741
      base::Optional<Block*> catch_block = GetCatchBlock();
      assembler().Emit(
          CallCsaMacroInstruction{macro, constexpr_arguments, catch_block});
      GenerateCatchBlock(catch_block);
1742 1743 1744 1745 1746 1747
      size_t return_slot_count = LoweredSlotCount(return_type);
      return VisitResult(return_type, assembler().TopRange(return_slot_count));
    } else {
      base::Optional<Block*> return_continuation;
      if (return_type != TypeOracle::GetNeverType()) {
        return_continuation = assembler().NewBlock();
1748 1749
      }

1750 1751 1752 1753 1754
      std::vector<Block*> label_blocks;

      for (size_t i = 0; i < label_count; ++i) {
        label_blocks.push_back(assembler().NewBlock());
      }
1755
      base::Optional<Block*> catch_block = GetCatchBlock();
1756
      assembler().Emit(CallCsaMacroAndBranchInstruction{
1757 1758 1759
          macro, constexpr_arguments, return_continuation, label_blocks,
          catch_block});
      GenerateCatchBlock(catch_block);
1760 1761

      for (size_t i = 0; i < label_count; ++i) {
1762
        Binding<LocalLabel>* label = arguments.labels[i];
1763 1764
        size_t callee_label_parameters =
            callable->signature().labels[i].types.size();
1765
        if (label->parameter_types.size() != callee_label_parameters) {
1766 1767 1768
          std::stringstream s;
          s << "label " << label->name()
            << " doesn't have the right number of parameters (found "
1769
            << std::to_string(label->parameter_types.size()) << " expected "
1770 1771 1772 1773 1774
            << std::to_string(callee_label_parameters) << ")";
          ReportError(s.str());
        }
        assembler().Bind(label_blocks[i]);
        assembler().Goto(
1775
            label->block,
1776 1777 1778 1779
            LowerParameterTypes(callable->signature().labels[i].types).size());

        size_t j = 0;
        for (auto t : callable->signature().labels[i].types) {
1780 1781 1782 1783
          const Type* parameter_type = label->parameter_types[j];
          if (parameter_type != t) {
            ReportError("mismatch of label parameters (expected ", *t, " got ",
                        parameter_type, " for parameter ", i + 1, ")");
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
          }
          j++;
        }
      }

      if (return_continuation) {
        assembler().Bind(*return_continuation);
        size_t return_slot_count = LoweredSlotCount(return_type);
        return VisitResult(return_type,
                           assembler().TopRange(return_slot_count));
      } else {
        return VisitResult::NeverResult();
      }
    }
  } else if (auto* runtime_function = RuntimeFunction::DynamicCast(callable)) {
1799 1800 1801 1802
    base::Optional<Block*> catch_block = GetCatchBlock();
    assembler().Emit(CallRuntimeInstruction{
        is_tailcall, runtime_function, argument_range.Size(), catch_block});
    GenerateCatchBlock(catch_block);
1803
    if (is_tailcall || return_type == TypeOracle::GetNeverType()) {
1804 1805 1806 1807 1808 1809 1810 1811
      return VisitResult::NeverResult();
    } else {
      size_t slot_count = LoweredSlotCount(return_type);
      DCHECK_LE(slot_count, 1);
      // TODO(tebbi): Actually, runtime functions have to return a value, so
      // we should assert slot_count == 1 here.
      return VisitResult(return_type, assembler().TopRange(slot_count));
    }
1812 1813 1814 1815 1816
  } else if (auto* intrinsic = Intrinsic::DynamicCast(callable)) {
    assembler().Emit(CallIntrinsicInstruction{intrinsic, constexpr_arguments});
    size_t return_slot_count =
        LoweredSlotCount(intrinsic->signature().return_type);
    return VisitResult(return_type, assembler().TopRange(return_slot_count));
1817 1818
  } else {
    UNREACHABLE();
1819 1820 1821 1822 1823
  }
}

VisitResult ImplementationVisitor::Visit(CallExpression* expr,
                                         bool is_tailcall) {
1824
  StackScope scope(this);
1825
  Arguments arguments;
1826 1827
  QualifiedName name =
      QualifiedName(expr->callee->namespace_qualification, expr->callee->name);
1828
  TypeVector specialization_types =
1829
      GetTypeVector(expr->callee->generic_arguments);
1830 1831 1832 1833 1834
  bool has_template_arguments = !specialization_types.empty();
  for (Expression* arg : expr->arguments)
    arguments.parameters.push_back(Visit(arg));
  arguments.labels = LabelsFromIdentifiers(expr->labels);
  VisitResult result;
1835 1836
  if (!has_template_arguments && name.namespace_qualification.empty() &&
      TryLookupLocalValue(name.name)) {
1837
    return scope.Yield(
1838
        GeneratePointerCall(expr->callee, arguments, is_tailcall));
1839
  } else {
1840 1841
    return scope.Yield(
        GenerateCall(name, arguments, specialization_types, is_tailcall));
1842 1843 1844
  }
}

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
VisitResult ImplementationVisitor::Visit(IntrinsicCallExpression* expr) {
  StackScope scope(this);
  Arguments arguments;
  TypeVector specialization_types = GetTypeVector(expr->generic_arguments);
  for (Expression* arg : expr->arguments)
    arguments.parameters.push_back(Visit(arg));
  return scope.Yield(
      GenerateCall(expr->name, arguments, specialization_types, false));
}

1855
void ImplementationVisitor::GenerateBranch(const VisitResult& condition,
1856 1857
                                           Block* true_block,
                                           Block* false_block) {
1858 1859
  DCHECK_EQ(condition,
            VisitResult(TypeOracle::GetBoolType(), assembler().TopRange(1)));
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
  assembler().Branch(true_block, false_block);
}

void ImplementationVisitor::GenerateExpressionBranch(Expression* expression,
                                                     Block* true_block,
                                                     Block* false_block) {
  // Conditional expressions can either explicitly return a bit
  // type, or they can be backed by macros that don't return but
  // take a true and false label. By declaring the labels before
  // visiting the conditional expression, those label-based
  // macro conditionals will be able to find them through normal
  // label lookups.
  Binding<LocalLabel> true_binding{&LabelBindingsManager::Get(), kTrueLabelName,
                                   LocalLabel{true_block}};
  Binding<LocalLabel> false_binding{&LabelBindingsManager::Get(),
                                    kFalseLabelName, LocalLabel{false_block}};
  StackScope stack_scope(this);
1877
  VisitResult expression_result = Visit(expression);
1878 1879 1880 1881
  if (!expression_result.type()->IsNever()) {
    expression_result = stack_scope.Yield(
        GenerateImplicitConvert(TypeOracle::GetBoolType(), expression_result));
    GenerateBranch(expression_result, true_block, false_block);
1882 1883 1884 1885
  }
}

VisitResult ImplementationVisitor::GenerateImplicitConvert(
1886
    const Type* destination_type, VisitResult source) {
1887
  StackScope scope(this);
1888 1889 1890 1891
  if (source.type() == TypeOracle::GetNeverType()) {
    ReportError("it is not allowed to use a value of type never");
  }

1892
  if (destination_type == source.type()) {
1893
    return scope.Yield(GenerateCopy(source));
1894
  }
1895

1896 1897
  if (TypeOracle::IsImplicitlyConvertableFrom(destination_type,
                                              source.type())) {
1898 1899
    return scope.Yield(GenerateCall(kFromConstexprMacroName, {{source}, {}},
                                    {destination_type}, false));
1900
  } else if (IsAssignableFrom(destination_type, source.type())) {
1901
    source.SetType(destination_type);
1902
    return scope.Yield(GenerateCopy(source));
1903 1904
  } else {
    std::stringstream s;
1905 1906
    s << "cannot use expression of type " << *source.type()
      << " as a value of type " << *destination_type;
1907 1908 1909 1910
    ReportError(s.str());
  }
}

1911
StackRange ImplementationVisitor::GenerateLabelGoto(
1912 1913
    LocalLabel* label, base::Optional<StackRange> arguments) {
  return assembler().Goto(label->block, arguments ? arguments->Size() : 0);
1914 1915
}

1916
std::vector<Binding<LocalLabel>*> ImplementationVisitor::LabelsFromIdentifiers(
1917
    const std::vector<std::string>& names) {
1918
  std::vector<Binding<LocalLabel>*> result;
1919
  result.reserve(names.size());
1920
  for (const auto& name : names) {
1921
    result.push_back(LookupLabel(name));
1922 1923 1924 1925
  }
  return result;
}

1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
StackRange ImplementationVisitor::LowerParameter(
    const Type* type, const std::string& parameter_name,
    Stack<std::string>* lowered_parameters) {
  if (type->IsStructType()) {
    const StructType* struct_type = StructType::cast(type);
    StackRange range = lowered_parameters->TopRange(0);
    for (auto& field : struct_type->fields()) {
      StackRange parameter_range = LowerParameter(
          field.type, parameter_name + "." + field.name, lowered_parameters);
      range.Extend(parameter_range);
    }
    return range;
  } else {
    lowered_parameters->Push(parameter_name);
    return lowered_parameters->TopRange(1);
  }
}

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
std::string ImplementationVisitor::ExternalLabelName(
    const std::string& label_name) {
  return "label_" + label_name;
}

std::string ImplementationVisitor::ExternalLabelParameterName(
    const std::string& label_name, size_t i) {
  return "label_" + label_name + "_parameter_" + std::to_string(i);
}

std::string ImplementationVisitor::ExternalParameterName(
    const std::string& name) {
  return std::string("p_") + name;
}

DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::ValueBindingsManager);
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::LabelBindingsManager);
1961
DEFINE_CONTEXTUAL_VARIABLE(ImplementationVisitor::CurrentCallable);
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981

bool IsCompatibleSignature(const Signature& sig, const TypeVector& types,
                           const std::vector<Binding<LocalLabel>*>& labels) {
  auto i = sig.parameter_types.types.begin() + sig.implicit_count;
  if ((sig.parameter_types.types.size() - sig.implicit_count) > types.size())
    return false;
  // TODO(danno): The test below is actually insufficient. The labels'
  // parameters must be checked too. ideally, the named part of
  // LabelDeclarationVector would be factored out so that the label count and
  // parameter types could be passed separately.
  if (sig.labels.size() != labels.size()) return false;
  for (auto current : types) {
    if (i == sig.parameter_types.types.end()) {
      if (!sig.parameter_types.var_args) return false;
      if (!IsAssignableFrom(TypeOracle::GetObjectType(), current)) return false;
    } else {
      if (!IsAssignableFrom(*i++, current)) return false;
    }
  }
  return true;
1982 1983
}

1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
base::Optional<Block*> ImplementationVisitor::GetCatchBlock() {
  base::Optional<Block*> catch_block;
  if (base::Optional<Binding<LocalLabel>*> catch_handler =
          TryLookupLabel("_catch")) {
    catch_block = assembler().NewBlock(base::nullopt, true);
  }
  return catch_block;
}

void ImplementationVisitor::GenerateCatchBlock(
    base::Optional<Block*> catch_block) {
  if (catch_block) {
    base::Optional<Binding<LocalLabel>*> catch_handler =
        TryLookupLabel("_catch");
    if (assembler().CurrentBlockIsComplete()) {
      assembler().Bind(*catch_block);
      assembler().Goto((*catch_handler)->block, 1);
    } else {
      CfgAssemblerScopedTemporaryBlock temp(&assembler(), *catch_block);
      assembler().Goto((*catch_handler)->block, 1);
    }
  }
}

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
void ImplementationVisitor::VisitAllDeclarables() {
  const std::vector<std::unique_ptr<Declarable>>& all_declarables =
      GlobalContext::AllDeclarables();
  // This has to be an index-based loop because all_declarables can be extended
  // during the loop.
  for (size_t i = 0; i < all_declarables.size(); ++i) {
    Visit(all_declarables[i].get());
  }
}

void ImplementationVisitor::Visit(Declarable* declarable) {
  CurrentScope::Scope current_scope(declarable->ParentScope());
  CurrentSourcePosition::Scope current_source_position(declarable->pos());
  switch (declarable->kind()) {
    case Declarable::kMacro:
      return Visit(Macro::cast(declarable));
    case Declarable::kBuiltin:
      return Visit(Builtin::cast(declarable));
    case Declarable::kTypeAlias:
      return Visit(TypeAlias::cast(declarable));
2028 2029
    case Declarable::kNamespaceConstant:
      return Visit(NamespaceConstant::cast(declarable));
2030
    case Declarable::kRuntimeFunction:
2031
    case Declarable::kIntrinsic:
2032
    case Declarable::kExternConstant:
2033
    case Declarable::kNamespace:
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
    case Declarable::kGeneric:
      return;
  }
}

void ImplementationVisitor::GenerateBuiltinDefinitions(std::string& file_name) {
  std::stringstream new_contents_stream;
  new_contents_stream
      << "#ifndef V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
         "#define V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n"
         "\n"
         "#define BUILTIN_LIST_FROM_DSL(CPP, API, TFJ, TFC, TFS, TFH, ASM) "
         "\\\n";
  for (auto& declarable : GlobalContext::AllDeclarables()) {
    Builtin* builtin = Builtin::DynamicCast(declarable.get());
    if (!builtin || builtin->IsExternal()) continue;
    int firstParameterIndex = 1;
    bool declareParameters = true;
    if (builtin->IsStub()) {
2053
      new_contents_stream << "TFS(" << builtin->ExternalName();
2054
    } else {
2055
      new_contents_stream << "TFJ(" << builtin->ExternalName();
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
      if (builtin->IsVarArgsJavaScript()) {
        new_contents_stream
            << ", SharedFunctionInfo::kDontAdaptArgumentsSentinel";
        declareParameters = false;
      } else {
        assert(builtin->IsFixedArgsJavaScript());
        // FixedArg javascript builtins need to offer the parameter
        // count.
        assert(builtin->parameter_names().size() >= 2);
        new_contents_stream << ", " << (builtin->parameter_names().size() - 2);
        // And the receiver is explicitly declared.
        new_contents_stream << ", kReceiver";
        firstParameterIndex = 2;
      }
    }
    if (declareParameters) {
      int index = 0;
      for (const auto& parameter : builtin->parameter_names()) {
        if (index >= firstParameterIndex) {
          new_contents_stream << ", k" << CamelifyString(parameter);
        }
        index++;
      }
    }
    new_contents_stream << ") \\\n";
  }
  new_contents_stream << "\n";

  new_contents_stream
      << "#define TORQUE_FUNCTION_POINTER_TYPE_TO_BUILTIN_MAP(V) \\\n";
  for (const FunctionPointerType* type :
       TypeOracle::AllFunctionPointerTypes()) {
    Builtin* example_builtin =
        Declarations::FindSomeInternalBuiltinWithType(type);
    if (!example_builtin) {
      CurrentSourcePosition::Scope current_source_position(
          SourcePosition{CurrentSourceFile::Get(), -1, -1});
      ReportError("unable to find any builtin with type \"", *type, "\"");
    }
    new_contents_stream << "  V(" << type->function_pointer_type_id() << ","
2096
                        << example_builtin->ExternalName() << ")\\\n";
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
  }
  new_contents_stream << "\n";

  new_contents_stream
      << "#endif  // V8_BUILTINS_BUILTIN_DEFINITIONS_FROM_DSL_H_\n";

  std::string new_contents(new_contents_stream.str());
  ReplaceFileContentsIfDifferent(file_name, new_contents);
}

2107 2108 2109
}  // namespace torque
}  // namespace internal
}  // namespace v8