memory-optimizer.cc 17 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 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/memory-optimizer.h"

7
#include "src/base/logging.h"
8
#include "src/codegen/interface-descriptors.h"
9
#include "src/codegen/tick-counter.h"
10 11 12 13 14
#include "src/compiler/js-graph.h"
#include "src/compiler/linkage.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/compiler/node.h"
15
#include "src/roots/roots-inl.h"
16 17 18 19 20

namespace v8 {
namespace internal {
namespace compiler {

21 22 23
namespace {

bool CanAllocate(const Node* node) {
24
  switch (node->opcode()) {
25
    case IrOpcode::kAbortCSADcheck:
26 27 28 29
    case IrOpcode::kBitcastTaggedToWord:
    case IrOpcode::kBitcastWordToTagged:
    case IrOpcode::kComment:
    case IrOpcode::kDebugBreak:
30 31
    case IrOpcode::kDeoptimizeIf:
    case IrOpcode::kDeoptimizeUnless:
32
    case IrOpcode::kEffectPhi:
33 34
    case IrOpcode::kIfException:
    case IrOpcode::kLoad:
35
    case IrOpcode::kLoadImmutable:
36 37
    case IrOpcode::kLoadElement:
    case IrOpcode::kLoadField:
38
    case IrOpcode::kLoadFromObject:
39
    case IrOpcode::kLoadImmutableFromObject:
40 41 42
    case IrOpcode::kLoadLane:
    case IrOpcode::kLoadTransform:
    case IrOpcode::kMemoryBarrier:
43 44
    case IrOpcode::kProtectedLoad:
    case IrOpcode::kProtectedStore:
45
    case IrOpcode::kRetain:
46 47
    case IrOpcode::kStackPointerGreaterThan:
    case IrOpcode::kStaticAssert:
48
    // TODO(turbofan): Store nodes might do a bump-pointer allocation.
49 50 51
    //              We should introduce a special bump-pointer store node to
    //              differentiate that.
    case IrOpcode::kStore:
52 53
    case IrOpcode::kStoreElement:
    case IrOpcode::kStoreField:
54
    case IrOpcode::kStoreLane:
55
    case IrOpcode::kStoreToObject:
56
    case IrOpcode::kInitializeImmutableInObject:
57 58
    case IrOpcode::kUnalignedLoad:
    case IrOpcode::kUnalignedStore:
59
    case IrOpcode::kUnreachable:
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    case IrOpcode::kWord32AtomicAdd:
    case IrOpcode::kWord32AtomicAnd:
    case IrOpcode::kWord32AtomicCompareExchange:
    case IrOpcode::kWord32AtomicExchange:
    case IrOpcode::kWord32AtomicLoad:
    case IrOpcode::kWord32AtomicOr:
    case IrOpcode::kWord32AtomicPairAdd:
    case IrOpcode::kWord32AtomicPairAnd:
    case IrOpcode::kWord32AtomicPairCompareExchange:
    case IrOpcode::kWord32AtomicPairExchange:
    case IrOpcode::kWord32AtomicPairLoad:
    case IrOpcode::kWord32AtomicPairOr:
    case IrOpcode::kWord32AtomicPairStore:
    case IrOpcode::kWord32AtomicPairSub:
    case IrOpcode::kWord32AtomicPairXor:
    case IrOpcode::kWord32AtomicStore:
    case IrOpcode::kWord32AtomicSub:
    case IrOpcode::kWord32AtomicXor:
    case IrOpcode::kWord64AtomicAdd:
    case IrOpcode::kWord64AtomicAnd:
    case IrOpcode::kWord64AtomicCompareExchange:
    case IrOpcode::kWord64AtomicExchange:
    case IrOpcode::kWord64AtomicLoad:
    case IrOpcode::kWord64AtomicOr:
    case IrOpcode::kWord64AtomicStore:
    case IrOpcode::kWord64AtomicSub:
    case IrOpcode::kWord64AtomicXor:
87 88 89 90 91
      return false;

    case IrOpcode::kCall:
      return !(CallDescriptorOf(node->op())->flags() &
               CallDescriptor::kNoAllocate);
92 93 94
    default:
      break;
  }
95 96 97
  return true;
}

98
Node* SearchAllocatingNode(Node* start, Node* limit, Zone* temp_zone) {
99 100
  ZoneQueue<Node*> queue(temp_zone);
  ZoneSet<Node*> visited(temp_zone);
101 102
  visited.insert(limit);
  queue.push(start);
103 104 105 106 107 108 109

  while (!queue.empty()) {
    Node* const current = queue.front();
    queue.pop();
    if (visited.find(current) == visited.end()) {
      visited.insert(current);

110 111 112
      if (CanAllocate(current)) {
        return current;
      }
113 114 115 116 117 118

      for (int i = 0; i < current->op()->EffectInputCount(); ++i) {
        queue.push(NodeProperties::GetEffectInput(current, i));
      }
    }
  }
119 120 121 122 123 124 125 126 127 128 129 130
  return nullptr;
}

bool CanLoopAllocate(Node* loop_effect_phi, Zone* temp_zone) {
  Node* const control = NodeProperties::GetControlInput(loop_effect_phi);
  // Start the effect chain walk from the loop back edges.
  for (int i = 1; i < control->InputCount(); ++i) {
    if (SearchAllocatingNode(loop_effect_phi->InputAt(i), loop_effect_phi,
                             temp_zone) != nullptr) {
      return true;
    }
  }
131 132 133
  return false;
}

134 135 136 137 138 139 140 141 142 143
Node* EffectPhiForPhi(Node* phi) {
  Node* control = NodeProperties::GetControlInput(phi);
  for (Node* use : control->uses()) {
    if (use->opcode() == IrOpcode::kEffectPhi) {
      return use;
    }
  }
  return nullptr;
}

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
void WriteBarrierAssertFailed(Node* node, Node* object, const char* name,
                              Zone* temp_zone) {
  std::stringstream str;
  str << "MemoryOptimizer could not remove write barrier for node #"
      << node->id() << "\n";
  str << "  Run mksnapshot with --csa-trap-on-node=" << name << ","
      << node->id() << " to break in CSA code.\n";
  Node* object_position = object;
  if (object_position->opcode() == IrOpcode::kPhi) {
    object_position = EffectPhiForPhi(object_position);
  }
  Node* allocating_node = nullptr;
  if (object_position && object_position->op()->EffectOutputCount() > 0) {
    allocating_node = SearchAllocatingNode(node, object_position, temp_zone);
  }
  if (allocating_node) {
    str << "\n  There is a potentially allocating node in between:\n";
    str << "    " << *allocating_node << "\n";
    str << "  Run mksnapshot with --csa-trap-on-node=" << name << ","
        << allocating_node->id() << " to break there.\n";
    if (allocating_node->opcode() == IrOpcode::kCall) {
      str << "  If this is a never-allocating runtime call, you can add an "
             "exception to Runtime::MayAllocate.\n";
    }
  } else {
    str << "\n  It seems the store happened to something different than a "
           "direct "
           "allocation:\n";
    str << "    " << *object << "\n";
    str << "  Run mksnapshot with --csa-trap-on-node=" << name << ","
        << object->id() << " to break there.\n";
  }
  FATAL("%s", str.str().c_str());
}

179 180
}  // namespace

181
MemoryOptimizer::MemoryOptimizer(
182
    JSGraph* jsgraph, Zone* zone,
183 184
    MemoryLowering::AllocationFolding allocation_folding,
    const char* function_debug_name, TickCounter* tick_counter)
185
    : graph_assembler_(jsgraph, zone),
186 187
      memory_lowering_(jsgraph, zone, &graph_assembler_, allocation_folding,
                       WriteBarrierAssertFailed, function_debug_name),
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
      jsgraph_(jsgraph),
      empty_state_(AllocationState::Empty(zone)),
      pending_(zone),
      tokens_(zone),
      zone_(zone),
      tick_counter_(tick_counter) {}

void MemoryOptimizer::Optimize() {
  EnqueueUses(graph()->start(), empty_state());
  while (!tokens_.empty()) {
    Token const token = tokens_.front();
    tokens_.pop();
    VisitNode(token.node, token.state);
  }
  DCHECK(pending_.empty());
  DCHECK(tokens_.empty());
}

206
void MemoryOptimizer::VisitNode(Node* node, AllocationState const* state) {
207
  tick_counter_->TickAndMaybeEnterSafepoint();
208 209 210 211 212 213 214 215 216 217 218
  DCHECK(!node->IsDead());
  DCHECK_LT(0, node->op()->EffectInputCount());
  switch (node->opcode()) {
    case IrOpcode::kAllocate:
      // Allocate nodes were purged from the graph in effect-control
      // linearization.
      UNREACHABLE();
    case IrOpcode::kAllocateRaw:
      return VisitAllocateRaw(node, state);
    case IrOpcode::kCall:
      return VisitCall(node, state);
219
    case IrOpcode::kLoadFromObject:
220
    case IrOpcode::kLoadImmutableFromObject:
221
      return VisitLoadFromObject(node, state);
222 223 224 225
    case IrOpcode::kLoadElement:
      return VisitLoadElement(node, state);
    case IrOpcode::kLoadField:
      return VisitLoadField(node, state);
226
    case IrOpcode::kStoreToObject:
227
    case IrOpcode::kInitializeImmutableInObject:
228
      return VisitStoreToObject(node, state);
229 230 231 232 233 234 235 236 237 238 239 240
    case IrOpcode::kStoreElement:
      return VisitStoreElement(node, state);
    case IrOpcode::kStoreField:
      return VisitStoreField(node, state);
    case IrOpcode::kStore:
      return VisitStore(node, state);
    default:
      if (!CanAllocate(node)) {
        // These operations cannot trigger GC.
        return VisitOtherEffect(node, state);
      }
  }
241 242 243
  DCHECK_EQ(0, node->op()->EffectOutputCount());
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257
bool MemoryOptimizer::AllocationTypeNeedsUpdateToOld(Node* const node,
                                                     const Edge edge) {
  // Test to see if we need to update the AllocationType.
  if (node->opcode() == IrOpcode::kStoreField && edge.index() == 1) {
    Node* parent = node->InputAt(0);
    if (parent->opcode() == IrOpcode::kAllocateRaw &&
        AllocationTypeOf(parent->op()) == AllocationType::kOld) {
      return true;
    }
  }

  return false;
}

258 259 260 261 262 263 264 265 266
void MemoryOptimizer::ReplaceUsesAndKillNode(Node* node, Node* replacement) {
  // Replace all uses of node and kill the node to make sure we don't leave
  // dangling dead uses.
  DCHECK_NE(replacement, node);
  NodeProperties::ReplaceUses(node, replacement, graph_assembler_.effect(),
                              graph_assembler_.control());
  node->Kill();
}

267 268 269
void MemoryOptimizer::VisitAllocateRaw(Node* node,
                                       AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kAllocateRaw, node->opcode());
270 271
  const AllocateParameters& allocation = AllocateParametersOf(node->op());
  AllocationType allocation_type = allocation.allocation_type();
272

273 274 275 276
  // Propagate tenuring from outer allocations to inner allocations, i.e.
  // when we allocate an object in old space and store a newly allocated
  // child object into the pretenured object, then the newly allocated
  // child object also should get pretenured to old space.
277
  if (allocation_type == AllocationType::kOld) {
278 279 280
    for (Edge const edge : node->use_edges()) {
      Node* const user = edge.from();
      if (user->opcode() == IrOpcode::kStoreField && edge.index() == 0) {
281
        Node* child = user->InputAt(1);
282
        if (child->opcode() == IrOpcode::kAllocateRaw &&
283
            AllocationTypeOf(child->op()) == AllocationType::kYoung) {
284 285 286 287 288 289
          NodeProperties::ChangeOp(child, node->op());
          break;
        }
      }
    }
  } else {
290
    DCHECK_EQ(AllocationType::kYoung, allocation_type);
291 292
    for (Edge const edge : node->use_edges()) {
      Node* const user = edge.from();
293 294 295
      if (AllocationTypeNeedsUpdateToOld(user, edge)) {
        allocation_type = AllocationType::kOld;
        break;
296 297 298 299
      }
    }
  }

300
  Reduction reduction = memory_lowering()->ReduceAllocateRaw(
301
      node, allocation_type, allocation.allow_large_objects(), &state);
302 303
  CHECK(reduction.Changed() && reduction.replacement() != node);

304
  ReplaceUsesAndKillNode(node, reduction.replacement());
305

306
  EnqueueUses(state->effect(), state);
307 308
}

309 310
void MemoryOptimizer::VisitLoadFromObject(Node* node,
                                          AllocationState const* state) {
311 312
  DCHECK(node->opcode() == IrOpcode::kLoadFromObject ||
         node->opcode() == IrOpcode::kLoadImmutableFromObject);
313
  Reduction reduction = memory_lowering()->ReduceLoadFromObject(node);
314
  EnqueueUses(node, state);
315 316 317
  if (V8_MAP_PACKING_BOOL && reduction.replacement() != node) {
    ReplaceUsesAndKillNode(node, reduction.replacement());
  }
318 319 320 321
}

void MemoryOptimizer::VisitStoreToObject(Node* node,
                                         AllocationState const* state) {
322 323
  DCHECK(node->opcode() == IrOpcode::kStoreToObject ||
         node->opcode() == IrOpcode::kInitializeImmutableInObject);
324
  memory_lowering()->ReduceStoreToObject(node, state);
325 326 327 328 329 330
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitLoadElement(Node* node,
                                       AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kLoadElement, node->opcode());
331
  memory_lowering()->ReduceLoadElement(node);
332 333 334 335 336
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitLoadField(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kLoadField, node->opcode());
337 338 339 340
  Reduction reduction = memory_lowering()->ReduceLoadField(node);
  DCHECK(reduction.Changed());
  // In case of replacement, the replacement graph should not require futher
  // lowering, so we can proceed iterating the graph from the node uses.
341
  EnqueueUses(node, state);
342

343
  // Node can be replaced under two cases:
Samuel Groß's avatar
Samuel Groß committed
344 345
  //   1. V8_SANDBOXED_EXTERNAL_POINTERS_BOOL is enabled and loading an external
  //   pointer value.
346
  //   2. V8_MAP_PACKING_BOOL is enabled.
Samuel Groß's avatar
Samuel Groß committed
347
  DCHECK_IMPLIES(!V8_SANDBOXED_EXTERNAL_POINTERS_BOOL && !V8_MAP_PACKING_BOOL,
348
                 reduction.replacement() == node);
Samuel Groß's avatar
Samuel Groß committed
349
  if ((V8_SANDBOXED_EXTERNAL_POINTERS_BOOL || V8_MAP_PACKING_BOOL) &&
350 351
      reduction.replacement() != node) {
    ReplaceUsesAndKillNode(node, reduction.replacement());
352
  }
353 354 355 356 357
}

void MemoryOptimizer::VisitStoreElement(Node* node,
                                        AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStoreElement, node->opcode());
358
  memory_lowering()->ReduceStoreElement(node, state);
359 360 361 362 363 364
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitStoreField(Node* node,
                                      AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStoreField, node->opcode());
365
  memory_lowering()->ReduceStoreField(node, state);
366 367
  EnqueueUses(node, state);
}
368 369
void MemoryOptimizer::VisitStore(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStore, node->opcode());
370 371 372 373 374 375 376 377 378
  memory_lowering()->ReduceStore(node, state);
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitCall(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kCall, node->opcode());
  // If the call can allocate, we start with a fresh state.
  if (!(CallDescriptorOf(node->op())->flags() & CallDescriptor::kNoAllocate)) {
    state = empty_state();
379 380 381 382
  }
  EnqueueUses(node, state);
}

383 384 385 386 387 388 389 390 391 392
void MemoryOptimizer::VisitOtherEffect(Node* node,
                                       AllocationState const* state) {
  EnqueueUses(node, state);
}

MemoryOptimizer::AllocationState const* MemoryOptimizer::MergeStates(
    AllocationStates const& states) {
  // Check if all states are the same; or at least if all allocation
  // states belong to the same allocation group.
  AllocationState const* state = states.front();
393
  MemoryLowering::AllocationGroup* group = state->group();
394 395 396 397 398 399 400 401 402 403 404
  for (size_t i = 1; i < states.size(); ++i) {
    if (states[i] != state) state = nullptr;
    if (states[i]->group() != group) group = nullptr;
  }
  if (state == nullptr) {
    if (group != nullptr) {
      // We cannot fold any more allocations into this group, but we can still
      // eliminate write barriers on stores to this group.
      // TODO(bmeurer): We could potentially just create a Phi here to merge
      // the various tops; but we need to pay special attention not to create
      // an unschedulable graph.
405
      state = AllocationState::Closed(group, nullptr, zone());
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    } else {
      // The states are from different allocation groups.
      state = empty_state();
    }
  }
  return state;
}

void MemoryOptimizer::EnqueueMerge(Node* node, int index,
                                   AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kEffectPhi, node->opcode());
  int const input_count = node->InputCount() - 1;
  DCHECK_LT(0, input_count);
  Node* const control = node->InputAt(input_count);
  if (control->opcode() == IrOpcode::kLoop) {
421 422 423 424 425 426 427 428 429 430 431 432 433
    if (index == 0) {
      if (CanLoopAllocate(node, zone())) {
        // If the loop can allocate,  we start with an empty state at the
        // beginning.
        EnqueueUses(node, empty_state());
      } else {
        // If the loop cannot allocate, we can just propagate the state from
        // before the loop.
        EnqueueUses(node, state);
      }
    } else {
      // Do not revisit backedges.
    }
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
  } else {
    DCHECK_EQ(IrOpcode::kMerge, control->opcode());
    // Check if we already know about this pending merge.
    NodeId const id = node->id();
    auto it = pending_.find(id);
    if (it == pending_.end()) {
      // Insert a new pending merge.
      it = pending_.insert(std::make_pair(id, AllocationStates(zone()))).first;
    }
    // Add the next input state.
    it->second.push_back(state);
    // Check if states for all inputs are available by now.
    if (it->second.size() == static_cast<size_t>(input_count)) {
      // All inputs to this effect merge are done, merge the states given all
      // input constraints, drop the pending merge and enqueue uses of the
      // EffectPhi {node}.
      state = MergeStates(it->second);
      EnqueueUses(node, state);
      pending_.erase(it);
    }
  }
}

void MemoryOptimizer::EnqueueUses(Node* node, AllocationState const* state) {
  for (Edge const edge : node->use_edges()) {
    if (NodeProperties::IsEffectEdge(edge)) {
      EnqueueUse(edge.from(), edge.index(), state);
    }
  }
}

void MemoryOptimizer::EnqueueUse(Node* node, int index,
                                 AllocationState const* state) {
  if (node->opcode() == IrOpcode::kEffectPhi) {
    // An EffectPhi represents a merge of different effect chains, which
    // needs special handling depending on whether the merge is part of a
    // loop or just a normal control join.
    EnqueueMerge(node, index, state);
  } else {
    Token token = {node, state};
    tokens_.push(token);
  }
}

Graph* MemoryOptimizer::graph() const { return jsgraph()->graph(); }

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