code-assembler.cc 35.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// 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/compiler/code-assembler.h"

#include <ostream>

#include "src/code-factory.h"
#include "src/compiler/graph.h"
#include "src/compiler/instruction-selector.h"
#include "src/compiler/linkage.h"
13
#include "src/compiler/node-matchers.h"
14 15 16 17 18 19 20 21
#include "src/compiler/pipeline.h"
#include "src/compiler/raw-machine-assembler.h"
#include "src/compiler/schedule.h"
#include "src/frames.h"
#include "src/interface-descriptors.h"
#include "src/interpreter/bytecodes.h"
#include "src/machine-type.h"
#include "src/macro-assembler.h"
22
#include "src/objects-inl.h"
23
#include "src/utils.h"
24
#include "src/zone/zone.h"
25

26 27 28 29 30
#define REPEAT_1_TO_2(V, T) V(T) V(T, T)
#define REPEAT_1_TO_3(V, T) REPEAT_1_TO_2(V, T) V(T, T, T)
#define REPEAT_1_TO_4(V, T) REPEAT_1_TO_3(V, T) V(T, T, T, T)
#define REPEAT_1_TO_5(V, T) REPEAT_1_TO_4(V, T) V(T, T, T, T, T)
#define REPEAT_1_TO_6(V, T) REPEAT_1_TO_5(V, T) V(T, T, T, T, T, T)
31 32 33
#define REPEAT_1_TO_7(V, T) REPEAT_1_TO_6(V, T) V(T, T, T, T, T, T, T)
#define REPEAT_1_TO_8(V, T) REPEAT_1_TO_7(V, T) V(T, T, T, T, T, T, T, T)
#define REPEAT_1_TO_9(V, T) REPEAT_1_TO_8(V, T) V(T, T, T, T, T, T, T, T, T)
34 35 36
#define REPEAT_1_TO_10(V, T) REPEAT_1_TO_9(V, T) V(T, T, T, T, T, T, T, T, T, T)
#define REPEAT_1_TO_11(V, T) \
  REPEAT_1_TO_10(V, T) V(T, T, T, T, T, T, T, T, T, T, T)
37 38
#define REPEAT_1_TO_12(V, T) \
  REPEAT_1_TO_11(V, T) V(T, T, T, T, T, T, T, T, T, T, T, T)
39

40 41 42 43
namespace v8 {
namespace internal {
namespace compiler {

44 45 46 47
CodeAssemblerState::CodeAssemblerState(
    Isolate* isolate, Zone* zone, const CallInterfaceDescriptor& descriptor,
    Code::Flags flags, const char* name, size_t result_size)
    : CodeAssemblerState(
48 49 50 51 52 53 54
          isolate, zone,
          Linkage::GetStubCallDescriptor(
              isolate, zone, descriptor, descriptor.GetStackParameterCount(),
              CallDescriptor::kNoFlags, Operator::kNoProperties,
              MachineType::AnyTagged(), result_size),
          flags, name) {}

55 56 57 58 59 60 61 62 63 64 65 66 67 68
CodeAssemblerState::CodeAssemblerState(Isolate* isolate, Zone* zone,
                                       int parameter_count, Code::Flags flags,
                                       const char* name)
    : CodeAssemblerState(isolate, zone,
                         Linkage::GetJSCallDescriptor(
                             zone, false, parameter_count,
                             Code::ExtractKindFromFlags(flags) == Code::BUILTIN
                                 ? CallDescriptor::kPushArgumentCount
                                 : CallDescriptor::kNoFlags),
                         flags, name) {}

CodeAssemblerState::CodeAssemblerState(Isolate* isolate, Zone* zone,
                                       CallDescriptor* call_descriptor,
                                       Code::Flags flags, const char* name)
69 70 71
    : raw_assembler_(new RawMachineAssembler(
          isolate, new (zone) Graph(zone), call_descriptor,
          MachineType::PointerRepresentation(),
72 73
          InstructionSelector::SupportedMachineOperatorFlags(),
          InstructionSelector::AlignmentRequirements())),
74 75 76 77 78
      flags_(flags),
      name_(name),
      code_generated_(false),
      variables_(zone) {}

79 80
CodeAssemblerState::~CodeAssemblerState() {}

81 82 83 84
int CodeAssemblerState::parameter_count() const {
  return static_cast<int>(raw_assembler_->call_descriptor()->ParameterCount());
}

85 86
CodeAssembler::~CodeAssembler() {}

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#if DEBUG
void CodeAssemblerState::PrintCurrentBlock(std::ostream& os) {
  raw_assembler_->PrintCurrentBlock(os);
}
#endif

void CodeAssemblerState::SetInitialDebugInformation(const char* msg,
                                                    const char* file,
                                                    int line) {
#if DEBUG
  AssemblerDebugInfo debug_info = {msg, file, line};
  raw_assembler_->SetInitialDebugInformation(debug_info);
#endif  // DEBUG
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
class BreakOnNodeDecorator final : public GraphDecorator {
 public:
  explicit BreakOnNodeDecorator(NodeId node_id) : node_id_(node_id) {}

  void Decorate(Node* node) final {
    if (node->id() == node_id_) {
      base::OS::DebugBreak();
    }
  }

 private:
  NodeId node_id_;
};

void CodeAssembler::BreakOnNode(int node_id) {
  Graph* graph = raw_assembler()->graph();
  Zone* zone = graph->zone();
  GraphDecorator* decorator =
      new (zone) BreakOnNodeDecorator(static_cast<NodeId>(node_id));
  graph->AddDecorator(decorator);
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137
void CodeAssembler::RegisterCallGenerationCallbacks(
    const CodeAssemblerCallback& call_prologue,
    const CodeAssemblerCallback& call_epilogue) {
  // The callback can be registered only once.
  DCHECK(!state_->call_prologue_);
  DCHECK(!state_->call_epilogue_);
  state_->call_prologue_ = call_prologue;
  state_->call_epilogue_ = call_epilogue;
}

void CodeAssembler::UnregisterCallGenerationCallbacks() {
  state_->call_prologue_ = nullptr;
  state_->call_epilogue_ = nullptr;
}
138

139 140 141 142 143 144 145 146 147 148 149
void CodeAssembler::CallPrologue() {
  if (state_->call_prologue_) {
    state_->call_prologue_();
  }
}

void CodeAssembler::CallEpilogue() {
  if (state_->call_epilogue_) {
    state_->call_epilogue_();
  }
}
150

151
// static
152
Handle<Code> CodeAssembler::GenerateCode(CodeAssemblerState* state) {
153
  DCHECK(!state->code_generated_);
154

155 156
  RawMachineAssembler* rasm = state->raw_assembler_.get();
  Schedule* schedule = rasm->Export();
157
  Handle<Code> code = Pipeline::GenerateCodeForCodeStub(
158
      rasm->isolate(), rasm->call_descriptor(), rasm->graph(), schedule,
159
      state->flags_, state->name_);
160

161
  state->code_generated_ = true;
162 163 164
  return code;
}

165
bool CodeAssembler::Is64() const { return raw_assembler()->machine()->Is64(); }
166 167

bool CodeAssembler::IsFloat64RoundUpSupported() const {
168
  return raw_assembler()->machine()->Float64RoundUp().IsSupported();
169 170 171
}

bool CodeAssembler::IsFloat64RoundDownSupported() const {
172
  return raw_assembler()->machine()->Float64RoundDown().IsSupported();
173 174
}

175 176 177 178
bool CodeAssembler::IsFloat64RoundTiesEvenSupported() const {
  return raw_assembler()->machine()->Float64RoundTiesEven().IsSupported();
}

179
bool CodeAssembler::IsFloat64RoundTruncateSupported() const {
180
  return raw_assembler()->machine()->Float64RoundTruncate().IsSupported();
181 182
}

183 184 185 186 187 188 189 190 191 192 193 194 195
bool CodeAssembler::IsInt32AbsWithOverflowSupported() const {
  return raw_assembler()->machine()->Int32AbsWithOverflow().IsSupported();
}

bool CodeAssembler::IsInt64AbsWithOverflowSupported() const {
  return raw_assembler()->machine()->Int64AbsWithOverflow().IsSupported();
}

bool CodeAssembler::IsIntPtrAbsWithOverflowSupported() const {
  return Is64() ? IsInt64AbsWithOverflowSupported()
                : IsInt32AbsWithOverflowSupported();
}

196
Node* CodeAssembler::Int32Constant(int32_t value) {
197
  return raw_assembler()->Int32Constant(value);
198 199
}

200
Node* CodeAssembler::Int64Constant(int64_t value) {
201
  return raw_assembler()->Int64Constant(value);
202 203
}

204
Node* CodeAssembler::IntPtrConstant(intptr_t value) {
205
  return raw_assembler()->IntPtrConstant(value);
206 207 208
}

Node* CodeAssembler::NumberConstant(double value) {
209
  return raw_assembler()->NumberConstant(value);
210 211 212
}

Node* CodeAssembler::SmiConstant(Smi* value) {
213
  return BitcastWordToTaggedSigned(IntPtrConstant(bit_cast<intptr_t>(value)));
214 215
}

216 217 218 219
Node* CodeAssembler::SmiConstant(int value) {
  return SmiConstant(Smi::FromInt(value));
}

220
Node* CodeAssembler::HeapConstant(Handle<HeapObject> object) {
221
  return raw_assembler()->HeapConstant(object);
222 223
}

224 225 226 227
Node* CodeAssembler::CStringConstant(const char* str) {
  return HeapConstant(factory()->NewStringFromAsciiChecked(str, TENURED));
}

228
Node* CodeAssembler::BooleanConstant(bool value) {
229
  return raw_assembler()->BooleanConstant(value);
230 231 232
}

Node* CodeAssembler::ExternalConstant(ExternalReference address) {
233
  return raw_assembler()->ExternalConstant(address);
234 235 236
}

Node* CodeAssembler::Float64Constant(double value) {
237
  return raw_assembler()->Float64Constant(value);
238 239 240 241 242 243
}

Node* CodeAssembler::NaNConstant() {
  return LoadRoot(Heap::kNanValueRootIndex);
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
bool CodeAssembler::ToInt32Constant(Node* node, int32_t& out_value) {
  Int64Matcher m(node);
  if (m.HasValue() &&
      m.IsInRange(std::numeric_limits<int32_t>::min(),
                  std::numeric_limits<int32_t>::max())) {
    out_value = static_cast<int32_t>(m.Value());
    return true;
  }

  return false;
}

bool CodeAssembler::ToInt64Constant(Node* node, int64_t& out_value) {
  Int64Matcher m(node);
  if (m.HasValue()) out_value = m.Value();
  return m.HasValue();
}

262 263 264 265 266 267 268 269 270 271 272 273 274 275
bool CodeAssembler::ToSmiConstant(Node* node, Smi*& out_value) {
  if (node->opcode() == IrOpcode::kBitcastWordToTaggedSigned) {
    node = node->InputAt(0);
  } else {
    return false;
  }
  IntPtrMatcher m(node);
  if (m.HasValue()) {
    out_value = Smi::cast(bit_cast<Object*>(m.Value()));
    return true;
  }
  return false;
}

276
bool CodeAssembler::ToIntPtrConstant(Node* node, intptr_t& out_value) {
277 278 279 280
  if (node->opcode() == IrOpcode::kBitcastWordToTaggedSigned ||
      node->opcode() == IrOpcode::kBitcastWordToTagged) {
    node = node->InputAt(0);
  }
281 282 283 284 285
  IntPtrMatcher m(node);
  if (m.HasValue()) out_value = m.Value();
  return m.HasValue();
}

286
Node* CodeAssembler::Parameter(int value) {
287
  return raw_assembler()->Parameter(value);
288 289
}

290 291 292 293 294 295 296
Node* CodeAssembler::GetJSContextParameter() {
  CallDescriptor* desc = raw_assembler()->call_descriptor();
  DCHECK(desc->IsJSFunctionCall());
  return Parameter(Linkage::GetJSCallContextParamIndex(
      static_cast<int>(desc->JSParameterCount())));
}

297
void CodeAssembler::Return(Node* value) {
298
  return raw_assembler()->Return(value);
299 300
}

301 302 303 304 305 306 307 308
void CodeAssembler::Return(Node* value1, Node* value2) {
  return raw_assembler()->Return(value1, value2);
}

void CodeAssembler::Return(Node* value1, Node* value2, Node* value3) {
  return raw_assembler()->Return(value1, value2, value3);
}

309
void CodeAssembler::PopAndReturn(Node* pop, Node* value) {
310
  return raw_assembler()->PopAndReturn(pop, value);
311 312
}

313 314 315 316 317 318 319 320
void CodeAssembler::ReturnIf(Node* condition, Node* value) {
  Label if_return(this), if_continue(this);
  Branch(condition, &if_return, &if_continue);
  Bind(&if_return);
  Return(value);
  Bind(&if_continue);
}

321
void CodeAssembler::DebugBreak() { raw_assembler()->DebugBreak(); }
322

323 324 325 326 327
void CodeAssembler::Unreachable() {
  DebugBreak();
  raw_assembler()->Unreachable();
}

328 329 330 331 332 333 334 335 336 337 338
void CodeAssembler::Comment(const char* format, ...) {
  if (!FLAG_code_comments) return;
  char buffer[4 * KB];
  StringBuilder builder(buffer, arraysize(buffer));
  va_list arguments;
  va_start(arguments, format);
  builder.AddFormattedList(format, arguments);
  va_end(arguments);

  // Copy the string before recording it in the assembler to avoid
  // issues when the stack allocated buffer goes out of scope.
339 340 341 342
  const int prefix_len = 2;
  int length = builder.position() + 1;
  char* copy = reinterpret_cast<char*>(malloc(length + prefix_len));
  MemCopy(copy + prefix_len, builder.Finalize(), length);
343 344
  copy[0] = ';';
  copy[1] = ' ';
345
  raw_assembler()->Comment(copy);
346 347
}

348
void CodeAssembler::Bind(Label* label) { return label->Bind(); }
349

350 351 352 353 354 355
#if DEBUG
void CodeAssembler::Bind(Label* label, AssemblerDebugInfo debug_info) {
  return label->Bind(debug_info);
}
#endif  // DEBUG

356
Node* CodeAssembler::LoadFramePointer() {
357
  return raw_assembler()->LoadFramePointer();
358 359 360
}

Node* CodeAssembler::LoadParentFramePointer() {
361
  return raw_assembler()->LoadParentFramePointer();
362 363 364
}

Node* CodeAssembler::LoadStackPointer() {
365
  return raw_assembler()->LoadStackPointer();
366 367 368 369
}

#define DEFINE_CODE_ASSEMBLER_BINARY_OP(name)   \
  Node* CodeAssembler::name(Node* a, Node* b) { \
370
    return raw_assembler()->name(a, b);         \
371 372 373 374
  }
CODE_ASSEMBLER_BINARY_OP_LIST(DEFINE_CODE_ASSEMBLER_BINARY_OP)
#undef DEFINE_CODE_ASSEMBLER_BINARY_OP

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
Node* CodeAssembler::IntPtrAdd(Node* left, Node* right) {
  intptr_t left_constant;
  bool is_left_constant = ToIntPtrConstant(left, left_constant);
  intptr_t right_constant;
  bool is_right_constant = ToIntPtrConstant(right, right_constant);
  if (is_left_constant) {
    if (is_right_constant) {
      return IntPtrConstant(left_constant + right_constant);
    }
    if (left_constant == 0) {
      return right;
    }
  } else if (is_right_constant) {
    if (right_constant == 0) {
      return left;
    }
  }
  return raw_assembler()->IntPtrAdd(left, right);
}

Node* CodeAssembler::IntPtrSub(Node* left, Node* right) {
  intptr_t left_constant;
  bool is_left_constant = ToIntPtrConstant(left, left_constant);
  intptr_t right_constant;
  bool is_right_constant = ToIntPtrConstant(right, right_constant);
  if (is_left_constant) {
    if (is_right_constant) {
      return IntPtrConstant(left_constant - right_constant);
    }
  } else if (is_right_constant) {
    if (right_constant == 0) {
      return left;
    }
  }
  return raw_assembler()->IntPtrSub(left, right);
}

412
Node* CodeAssembler::WordShl(Node* value, int shift) {
413
  return (shift != 0) ? raw_assembler()->WordShl(value, IntPtrConstant(shift))
oth's avatar
oth committed
414
                      : value;
415 416
}

417
Node* CodeAssembler::WordShr(Node* value, int shift) {
418
  return (shift != 0) ? raw_assembler()->WordShr(value, IntPtrConstant(shift))
oth's avatar
oth committed
419 420 421 422
                      : value;
}

Node* CodeAssembler::Word32Shr(Node* value, int shift) {
423
  return (shift != 0) ? raw_assembler()->Word32Shr(value, Int32Constant(shift))
oth's avatar
oth committed
424
                      : value;
425 426
}

427
Node* CodeAssembler::ChangeUint32ToWord(Node* value) {
428 429
  if (raw_assembler()->machine()->Is64()) {
    value = raw_assembler()->ChangeUint32ToUint64(value);
430 431 432 433
  }
  return value;
}

434
Node* CodeAssembler::ChangeInt32ToIntPtr(Node* value) {
435 436
  if (raw_assembler()->machine()->Is64()) {
    value = raw_assembler()->ChangeInt32ToInt64(value);
437 438 439 440
  }
  return value;
}

441 442 443 444 445 446 447
Node* CodeAssembler::ChangeFloat64ToUintPtr(Node* value) {
  if (raw_assembler()->machine()->Is64()) {
    return raw_assembler()->ChangeFloat64ToUint64(value);
  }
  return raw_assembler()->ChangeFloat64ToUint32(value);
}

448
Node* CodeAssembler::RoundIntPtrToFloat64(Node* value) {
449 450
  if (raw_assembler()->machine()->Is64()) {
    return raw_assembler()->RoundInt64ToFloat64(value);
451
  }
452
  return raw_assembler()->ChangeInt32ToFloat64(value);
453 454
}

455
#define DEFINE_CODE_ASSEMBLER_UNARY_OP(name) \
456
  Node* CodeAssembler::name(Node* a) { return raw_assembler()->name(a); }
457 458 459
CODE_ASSEMBLER_UNARY_OP_LIST(DEFINE_CODE_ASSEMBLER_UNARY_OP)
#undef DEFINE_CODE_ASSEMBLER_UNARY_OP

460
Node* CodeAssembler::Load(MachineType rep, Node* base) {
461
  return raw_assembler()->Load(rep, base);
462 463
}

464 465
Node* CodeAssembler::Load(MachineType rep, Node* base, Node* offset) {
  return raw_assembler()->Load(rep, base, offset);
466 467
}

468 469
Node* CodeAssembler::AtomicLoad(MachineType rep, Node* base, Node* offset) {
  return raw_assembler()->AtomicLoad(rep, base, offset);
470 471
}

472 473 474 475 476 477 478 479 480 481
Node* CodeAssembler::LoadRoot(Heap::RootListIndex root_index) {
  if (isolate()->heap()->RootCanBeTreatedAsConstant(root_index)) {
    Handle<Object> root = isolate()->heap()->root_handle(root_index);
    if (root->IsSmi()) {
      return SmiConstant(Smi::cast(*root));
    } else {
      return HeapConstant(Handle<HeapObject>::cast(root));
    }
  }

482
  Node* roots_array_start =
483
      ExternalConstant(ExternalReference::roots_array_start(isolate()));
484 485
  return Load(MachineType::AnyTagged(), roots_array_start,
              IntPtrConstant(root_index * kPointerSize));
486 487
}

488 489 490
Node* CodeAssembler::Store(Node* base, Node* value) {
  return raw_assembler()->Store(MachineRepresentation::kTagged, base, value,
                                kFullWriteBarrier);
491 492
}

493 494 495
Node* CodeAssembler::Store(Node* base, Node* offset, Node* value) {
  return raw_assembler()->Store(MachineRepresentation::kTagged, base, offset,
                                value, kFullWriteBarrier);
496 497
}

498 499 500 501 502 503
Node* CodeAssembler::StoreWithMapWriteBarrier(Node* base, Node* offset,
                                              Node* value) {
  return raw_assembler()->Store(MachineRepresentation::kTagged, base, offset,
                                value, kMapWriteBarrier);
}

504 505
Node* CodeAssembler::StoreNoWriteBarrier(MachineRepresentation rep, Node* base,
                                         Node* value) {
506
  return raw_assembler()->Store(rep, base, value, kNoWriteBarrier);
507 508 509
}

Node* CodeAssembler::StoreNoWriteBarrier(MachineRepresentation rep, Node* base,
510 511
                                         Node* offset, Node* value) {
  return raw_assembler()->Store(rep, base, offset, value, kNoWriteBarrier);
512 513
}

514
Node* CodeAssembler::AtomicStore(MachineRepresentation rep, Node* base,
515 516
                                 Node* offset, Node* value) {
  return raw_assembler()->AtomicStore(rep, base, offset, value);
517 518
}

519 520 521 522 523 524 525 526 527 528 529 530
#define ATOMIC_FUNCTION(name)                                        \
  Node* CodeAssembler::Atomic##name(MachineType type, Node* base,    \
                                    Node* offset, Node* value) {     \
    return raw_assembler()->Atomic##name(type, base, offset, value); \
  }
ATOMIC_FUNCTION(Exchange);
ATOMIC_FUNCTION(Add);
ATOMIC_FUNCTION(Sub);
ATOMIC_FUNCTION(And);
ATOMIC_FUNCTION(Or);
ATOMIC_FUNCTION(Xor);
#undef ATOMIC_FUNCTION
531

532 533 534 535 536 537 538
Node* CodeAssembler::AtomicCompareExchange(MachineType type, Node* base,
                                           Node* offset, Node* old_value,
                                           Node* new_value) {
  return raw_assembler()->AtomicCompareExchange(type, base, offset, old_value,
                                                new_value);
}

539 540 541 542 543 544 545 546
Node* CodeAssembler::StoreRoot(Heap::RootListIndex root_index, Node* value) {
  DCHECK(Heap::RootCanBeWrittenAfterInitialization(root_index));
  Node* roots_array_start =
      ExternalConstant(ExternalReference::roots_array_start(isolate()));
  return StoreNoWriteBarrier(MachineRepresentation::kTagged, roots_array_start,
                             IntPtrConstant(root_index * kPointerSize), value);
}

547
Node* CodeAssembler::Retain(Node* value) {
548
  return raw_assembler()->Retain(value);
549 550
}

551
Node* CodeAssembler::Projection(int index, Node* value) {
552
  return raw_assembler()->Projection(index, value);
553 554
}

555 556 557 558 559 560 561
void CodeAssembler::GotoIfException(Node* node, Label* if_exception,
                                    Variable* exception_var) {
  Label success(this), exception(this, Label::kDeferred);
  success.MergeVariables();
  exception.MergeVariables();
  DCHECK(!node->op()->HasProperty(Operator::kNoThrow));

562
  raw_assembler()->Continuations(node, success.label_, exception.label_);
563 564

  Bind(&exception);
565 566
  const Operator* op = raw_assembler()->common()->IfException();
  Node* exception_value = raw_assembler()->AddNode(op, node, node);
567 568 569 570 571 572 573 574
  if (exception_var != nullptr) {
    exception_var->Bind(exception_value);
  }
  Goto(if_exception);

  Bind(&success);
}

575 576 577
template <class... TArgs>
Node* CodeAssembler::CallRuntime(Runtime::FunctionId function, Node* context,
                                 TArgs... args) {
578 579 580 581 582 583 584 585 586 587 588 589 590
  int argc = static_cast<int>(sizeof...(args));
  CallDescriptor* desc = Linkage::GetRuntimeCallDescriptor(
      zone(), function, argc, Operator::kNoProperties,
      CallDescriptor::kNoFlags);
  int return_count = static_cast<int>(desc->ReturnCount());

  Node* centry =
      HeapConstant(CodeFactory::RuntimeCEntry(isolate(), return_count));
  Node* ref = ExternalConstant(ExternalReference(function, isolate()));
  Node* arity = Int32Constant(argc);

  Node* nodes[] = {centry, args..., ref, arity, context};

591
  CallPrologue();
592
  Node* return_value = raw_assembler()->CallN(desc, arraysize(nodes), nodes);
593 594 595 596
  CallEpilogue();
  return return_value;
}

597
// Instantiate CallRuntime() for argument counts used by CSA-generated code
598 599 600
#define INSTANTIATE(...)                                       \
  template V8_EXPORT_PRIVATE Node* CodeAssembler::CallRuntime( \
      Runtime::FunctionId, __VA_ARGS__);
601
REPEAT_1_TO_7(INSTANTIATE, Node*)
602
#undef INSTANTIATE
603

604 605 606 607 608 609 610 611
template <class... TArgs>
Node* CodeAssembler::TailCallRuntime(Runtime::FunctionId function,
                                     Node* context, TArgs... args) {
  int argc = static_cast<int>(sizeof...(args));
  CallDescriptor* desc = Linkage::GetRuntimeCallDescriptor(
      zone(), function, argc, Operator::kNoProperties,
      CallDescriptor::kSupportsTailCalls);
  int return_count = static_cast<int>(desc->ReturnCount());
612

613 614 615 616
  Node* centry =
      HeapConstant(CodeFactory::RuntimeCEntry(isolate(), return_count));
  Node* ref = ExternalConstant(ExternalReference(function, isolate()));
  Node* arity = Int32Constant(argc);
617

618
  Node* nodes[] = {centry, args..., ref, arity, context};
619

620
  return raw_assembler()->TailCallN(desc, arraysize(nodes), nodes);
621 622
}

623
// Instantiate TailCallRuntime() for argument counts used by CSA-generated code
624 625 626 627 628
#define INSTANTIATE(...)                                           \
  template V8_EXPORT_PRIVATE Node* CodeAssembler::TailCallRuntime( \
      Runtime::FunctionId, __VA_ARGS__);
REPEAT_1_TO_7(INSTANTIATE, Node*)
#undef INSTANTIATE
629

630 631 632 633 634 635
template <class... TArgs>
Node* CodeAssembler::CallStubR(const CallInterfaceDescriptor& descriptor,
                               size_t result_size, Node* target, Node* context,
                               TArgs... args) {
  Node* nodes[] = {target, args..., context};
  return CallStubN(descriptor, result_size, arraysize(nodes), nodes);
636 637
}

638
// Instantiate CallStubR() for argument counts used by CSA-generated code.
639 640 641
#define INSTANTIATE(...)                                     \
  template V8_EXPORT_PRIVATE Node* CodeAssembler::CallStubR( \
      const CallInterfaceDescriptor& descriptor, size_t, Node*, __VA_ARGS__);
642
REPEAT_1_TO_8(INSTANTIATE, Node*)
643
#undef INSTANTIATE
644

645 646 647 648 649 650 651 652 653 654 655 656
Node* CodeAssembler::CallStubN(const CallInterfaceDescriptor& descriptor,
                               size_t result_size, int input_count,
                               Node* const* inputs) {
  // 2 is for target and context.
  DCHECK_LE(2, input_count);
  int argc = input_count - 2;
  DCHECK_LE(descriptor.GetParameterCount(), argc);
  // Extra arguments not mentioned in the descriptor are passed on the stack.
  int stack_parameter_count = argc - descriptor.GetRegisterParameterCount();
  DCHECK_LE(descriptor.GetStackParameterCount(), stack_parameter_count);
  CallDescriptor* desc = Linkage::GetStubCallDescriptor(
      isolate(), zone(), descriptor, stack_parameter_count,
657 658 659
      CallDescriptor::kNoFlags, Operator::kNoProperties,
      MachineType::AnyTagged(), result_size);

660 661 662 663
  CallPrologue();
  Node* return_value = raw_assembler()->CallN(desc, input_count, inputs);
  CallEpilogue();
  return return_value;
664 665
}

666
template <class... TArgs>
667
Node* CodeAssembler::TailCallStub(const CallInterfaceDescriptor& descriptor,
668 669 670 671
                                  Node* target, Node* context, TArgs... args) {
  DCHECK_EQ(descriptor.GetParameterCount(), sizeof...(args));
  size_t result_size = 1;
  CallDescriptor* desc = Linkage::GetStubCallDescriptor(
672 673 674 675
      isolate(), zone(), descriptor, descriptor.GetStackParameterCount(),
      CallDescriptor::kSupportsTailCalls, Operator::kNoProperties,
      MachineType::AnyTagged(), result_size);

676
  Node* nodes[] = {target, args..., context};
677
  CHECK_EQ(descriptor.GetParameterCount() + 2, arraysize(nodes));
678
  return raw_assembler()->TailCallN(desc, arraysize(nodes), nodes);
679 680
}

681
// Instantiate TailCallStub() for argument counts used by CSA-generated code
682 683 684
#define INSTANTIATE(...)                                        \
  template V8_EXPORT_PRIVATE Node* CodeAssembler::TailCallStub( \
      const CallInterfaceDescriptor& descriptor, Node*, __VA_ARGS__);
685
REPEAT_1_TO_12(INSTANTIATE, Node*)
686
#undef INSTANTIATE
687

688
template <class... TArgs>
689
Node* CodeAssembler::TailCallBytecodeDispatch(
690 691 692 693 694 695
    const CallInterfaceDescriptor& descriptor, Node* target, TArgs... args) {
  DCHECK_EQ(descriptor.GetParameterCount(), sizeof...(args));
  CallDescriptor* desc = Linkage::GetBytecodeDispatchCallDescriptor(
      isolate(), zone(), descriptor, descriptor.GetStackParameterCount());

  Node* nodes[] = {target, args...};
696
  CHECK_EQ(descriptor.GetParameterCount() + 1, arraysize(nodes));
697
  return raw_assembler()->TailCallN(desc, arraysize(nodes), nodes);
698 699
}

700 701
// Instantiate TailCallBytecodeDispatch() for argument counts used by
// CSA-generated code
702 703 704 705
template V8_EXPORT_PRIVATE Node* CodeAssembler::TailCallBytecodeDispatch(
    const CallInterfaceDescriptor& descriptor, Node* target, Node*, Node*,
    Node*, Node*);

706 707 708 709 710 711
Node* CodeAssembler::CallCFunctionN(Signature<MachineType>* signature,
                                    int input_count, Node* const* inputs) {
  CallDescriptor* desc = Linkage::GetSimplifiedCDescriptor(zone(), signature);
  return raw_assembler()->CallN(desc, input_count, inputs);
}

712 713 714 715
Node* CodeAssembler::CallCFunction2(MachineType return_type,
                                    MachineType arg0_type,
                                    MachineType arg1_type, Node* function,
                                    Node* arg0, Node* arg1) {
716 717
  return raw_assembler()->CallCFunction2(return_type, arg0_type, arg1_type,
                                         function, arg0, arg1);
718 719
}

720 721 722 723 724 725 726 727 728
Node* CodeAssembler::CallCFunction3(MachineType return_type,
                                    MachineType arg0_type,
                                    MachineType arg1_type,
                                    MachineType arg2_type, Node* function,
                                    Node* arg0, Node* arg1, Node* arg2) {
  return raw_assembler()->CallCFunction3(return_type, arg0_type, arg1_type,
                                         arg2_type, function, arg0, arg1, arg2);
}

729
void CodeAssembler::Goto(Label* label) {
730
  label->MergeVariables();
731
  raw_assembler()->Goto(label->label_);
732 733 734 735 736 737 738 739
}

void CodeAssembler::GotoIf(Node* condition, Label* true_label) {
  Label false_label(this);
  Branch(condition, true_label, &false_label);
  Bind(&false_label);
}

740
void CodeAssembler::GotoIfNot(Node* condition, Label* false_label) {
741 742 743 744 745
  Label true_label(this);
  Branch(condition, &true_label, false_label);
  Bind(&true_label);
}

746 747
void CodeAssembler::Branch(Node* condition, Label* true_label,
                           Label* false_label) {
748 749
  true_label->MergeVariables();
  false_label->MergeVariables();
750 751
  return raw_assembler()->Branch(condition, true_label->label_,
                                 false_label->label_);
752 753 754
}

void CodeAssembler::Switch(Node* index, Label* default_label,
755
                           const int32_t* case_values, Label** case_labels,
756 757 758 759 760 761 762 763 764
                           size_t case_count) {
  RawMachineLabel** labels =
      new (zone()->New(sizeof(RawMachineLabel*) * case_count))
          RawMachineLabel*[case_count];
  for (size_t i = 0; i < case_count; ++i) {
    labels[i] = case_labels[i]->label_;
    case_labels[i]->MergeVariables();
    default_label->MergeVariables();
  }
765 766
  return raw_assembler()->Switch(index, default_label->label_, case_values,
                                 labels, case_count);
767 768
}

769 770 771 772 773 774 775 776 777 778 779
bool CodeAssembler::UnalignedLoadSupported(const MachineType& machineType,
                                           uint8_t alignment) const {
  return raw_assembler()->machine()->UnalignedLoadSupported(machineType,
                                                            alignment);
}
bool CodeAssembler::UnalignedStoreSupported(const MachineType& machineType,
                                            uint8_t alignment) const {
  return raw_assembler()->machine()->UnalignedStoreSupported(machineType,
                                                             alignment);
}

780
// RawMachineAssembler delegate helpers:
781
Isolate* CodeAssembler::isolate() const { return raw_assembler()->isolate(); }
782 783 784

Factory* CodeAssembler::factory() const { return isolate()->factory(); }

785 786 787 788 789
Zone* CodeAssembler::zone() const { return raw_assembler()->zone(); }

RawMachineAssembler* CodeAssembler::raw_assembler() const {
  return state_->raw_assembler_.get();
}
790 791 792 793 794

// The core implementation of Variable is stored through an indirection so
// that it can outlive the often block-scoped Variable declarations. This is
// needed to ensure that variable binding and merging through phis can
// properly be verified.
795
class CodeAssemblerVariable::Impl : public ZoneObject {
796
 public:
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
  explicit Impl(MachineRepresentation rep)
      :
#if DEBUG
        debug_info_(AssemblerDebugInfo(nullptr, nullptr, -1)),
#endif
        value_(nullptr),
        rep_(rep) {
  }

#if DEBUG
  AssemblerDebugInfo debug_info() const { return debug_info_; }
  void set_debug_info(AssemblerDebugInfo debug_info) {
    debug_info_ = debug_info;
  }

  AssemblerDebugInfo debug_info_;
#endif  // DEBUG
814 815 816 817
  Node* value_;
  MachineRepresentation rep_;
};

818 819 820
CodeAssemblerVariable::CodeAssemblerVariable(CodeAssembler* assembler,
                                             MachineRepresentation rep)
    : impl_(new (assembler->zone()) Impl(rep)), state_(assembler->state()) {
821
  state_->variables_.insert(impl_);
822 823
}

824 825 826 827 828 829 830
CodeAssemblerVariable::CodeAssemblerVariable(CodeAssembler* assembler,
                                             MachineRepresentation rep,
                                             Node* initial_value)
    : CodeAssemblerVariable(assembler, rep) {
  Bind(initial_value);
}

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
#if DEBUG
CodeAssemblerVariable::CodeAssemblerVariable(CodeAssembler* assembler,
                                             AssemblerDebugInfo debug_info,
                                             MachineRepresentation rep)
    : impl_(new (assembler->zone()) Impl(rep)), state_(assembler->state()) {
  impl_->set_debug_info(debug_info);
  state_->variables_.insert(impl_);
}

CodeAssemblerVariable::CodeAssemblerVariable(CodeAssembler* assembler,
                                             AssemblerDebugInfo debug_info,
                                             MachineRepresentation rep,
                                             Node* initial_value)
    : CodeAssemblerVariable(assembler, debug_info, rep) {
  impl_->set_debug_info(debug_info);
  Bind(initial_value);
}
#endif  // DEBUG

850 851 852
CodeAssemblerVariable::~CodeAssemblerVariable() {
  state_->variables_.erase(impl_);
}
853

854
void CodeAssemblerVariable::Bind(Node* value) { impl_->value_ = value; }
855

856
Node* CodeAssemblerVariable::value() const {
857 858 859 860 861 862 863 864 865 866 867 868
#if DEBUG
  if (!IsBound()) {
    std::stringstream str;
    str << "#Use of unbound variable:"
        << "#\n    Variable:      " << *this;
    if (state_) {
      str << "#\n    Current Block: ";
      state_->PrintCurrentBlock(str);
    }
    FATAL(str.str().c_str());
  }
#endif  // DEBUG
869 870 871
  return impl_->value_;
}

872
MachineRepresentation CodeAssemblerVariable::rep() const { return impl_->rep_; }
873

874
bool CodeAssemblerVariable::IsBound() const { return impl_->value_ != nullptr; }
875

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
std::ostream& operator<<(std::ostream& os,
                         const CodeAssemblerVariable::Impl& impl) {
#if DEBUG
  AssemblerDebugInfo info = impl.debug_info();
  if (info.name) os << "V" << info;
#endif  // DEBUG
  return os;
}

std::ostream& operator<<(std::ostream& os,
                         const CodeAssemblerVariable& variable) {
  os << *variable.impl_;
  return os;
}

891 892
CodeAssemblerLabel::CodeAssemblerLabel(CodeAssembler* assembler,
                                       size_t vars_count,
893
                                       CodeAssemblerVariable* const* vars,
894
                                       CodeAssemblerLabel::Type type)
895 896
    : bound_(false),
      merge_count_(0),
897
      state_(assembler->state()),
898
      label_(nullptr) {
899 900 901 902
  void* buffer = assembler->zone()->New(sizeof(RawMachineLabel));
  label_ = new (buffer)
      RawMachineLabel(type == kDeferred ? RawMachineLabel::kDeferred
                                        : RawMachineLabel::kNonDeferred);
903 904
  for (size_t i = 0; i < vars_count; ++i) {
    variable_phis_[vars[i]->impl_] = nullptr;
905 906 907
  }
}

908 909
CodeAssemblerLabel::~CodeAssemblerLabel() { label_->~RawMachineLabel(); }

910
void CodeAssemblerLabel::MergeVariables() {
911
  ++merge_count_;
912
  for (CodeAssemblerVariable::Impl* var : state_->variables_) {
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    size_t count = 0;
    Node* node = var->value_;
    if (node != nullptr) {
      auto i = variable_merges_.find(var);
      if (i != variable_merges_.end()) {
        i->second.push_back(node);
        count = i->second.size();
      } else {
        count = 1;
        variable_merges_[var] = std::vector<Node*>(1, node);
      }
    }
    // If the following asserts, then you've jumped to a label without a bound
    // variable along that path that expects to merge its value into a phi.
    DCHECK(variable_phis_.find(var) == variable_phis_.end() ||
           count == merge_count_);
    USE(count);

    // If the label is already bound, we already know the set of variables to
    // merge and phi nodes have already been created.
    if (bound_) {
      auto phi = variable_phis_.find(var);
      if (phi != variable_phis_.end()) {
        DCHECK_NOT_NULL(phi->second);
937
        state_->raw_assembler_->AppendPhiInput(phi->second, node);
938 939 940 941 942 943 944 945 946
      } else {
        auto i = variable_merges_.find(var);
        if (i != variable_merges_.end()) {
          // If the following assert fires, then you've declared a variable that
          // has the same bound value along all paths up until the point you
          // bound this label, but then later merged a path with a new value for
          // the variable after the label bind (it's not possible to add phis to
          // the bound label after the fact, just make sure to list the variable
          // in the label's constructor's list of merged variables).
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
#if DEBUG
          if (find_if(i->second.begin(), i->second.end(),
                      [node](Node* e) -> bool { return node != e; }) !=
              i->second.end()) {
            std::stringstream str;
            str << "Unmerged variable found when jumping to block. \n"
                << "#    Variable:      " << *var;
            if (bound_) {
              str << "\n#    Target block:  " << *label_->block();
            }
            str << "\n#    Current Block: ";
            state_->PrintCurrentBlock(str);
            FATAL(str.str().c_str());
          }
#endif  // DEBUG
962 963 964 965 966 967
        }
      }
    }
  }
}

968 969 970 971 972 973 974 975
#if DEBUG
void CodeAssemblerLabel::Bind(AssemblerDebugInfo debug_info) {
  DCHECK(!bound_);
  state_->raw_assembler_->Bind(label_, debug_info);
  UpdateVariablesAfterBind();
}
#endif  // DEBUG

976
void CodeAssemblerLabel::Bind() {
977
  DCHECK(!bound_);
978
  state_->raw_assembler_->Bind(label_);
979 980
  UpdateVariablesAfterBind();
}
981

982
void CodeAssemblerLabel::UpdateVariablesAfterBind() {
983 984
  // Make sure that all variables that have changed along any path up to this
  // point are marked as merge variables.
985
  for (auto var : state_->variables_) {
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    Node* shared_value = nullptr;
    auto i = variable_merges_.find(var);
    if (i != variable_merges_.end()) {
      for (auto value : i->second) {
        DCHECK(value != nullptr);
        if (value != shared_value) {
          if (shared_value == nullptr) {
            shared_value = value;
          } else {
            variable_phis_[var] = nullptr;
          }
        }
      }
    }
  }

  for (auto var : variable_phis_) {
1003
    CodeAssemblerVariable::Impl* var_impl = var.first;
1004
    auto i = variable_merges_.find(var_impl);
1005
    // If the following asserts fire, then a variable that has been marked as
1006 1007 1008 1009
    // being merged at the label--either by explicitly marking it so in the
    // label constructor or by having seen different bound values at branches
    // into the label--doesn't have a bound value along all of the paths that
    // have been merged into the label up to this point.
1010 1011
    DCHECK(i != variable_merges_.end());
    DCHECK_EQ(i->second.size(), merge_count_);
1012
    Node* phi = state_->raw_assembler_->Phi(
1013 1014 1015 1016 1017 1018
        var.first->rep_, static_cast<int>(merge_count_), &(i->second[0]));
    variable_phis_[var_impl] = phi;
  }

  // Bind all variables to a merge phi, the common value along all paths or
  // null.
1019
  for (auto var : state_->variables_) {
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
    auto i = variable_phis_.find(var);
    if (i != variable_phis_.end()) {
      var->value_ = i->second;
    } else {
      auto j = variable_merges_.find(var);
      if (j != variable_merges_.end() && j->second.size() == merge_count_) {
        var->value_ = j->second.back();
      } else {
        var->value_ = nullptr;
      }
    }
  }

  bound_ = true;
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8