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::kDynamicCheckMapsWithDeoptUnless:
33
    case IrOpcode::kEffectPhi:
34 35
    case IrOpcode::kIfException:
    case IrOpcode::kLoad:
36
    case IrOpcode::kLoadImmutable:
37 38
    case IrOpcode::kLoadElement:
    case IrOpcode::kLoadField:
39
    case IrOpcode::kLoadFromObject:
40
    case IrOpcode::kLoadImmutableFromObject:
41 42 43
    case IrOpcode::kLoadLane:
    case IrOpcode::kLoadTransform:
    case IrOpcode::kMemoryBarrier:
44 45
    case IrOpcode::kProtectedLoad:
    case IrOpcode::kProtectedStore:
46
    case IrOpcode::kRetain:
47 48
    case IrOpcode::kStackPointerGreaterThan:
    case IrOpcode::kStaticAssert:
49
    // TODO(turbofan): Store nodes might do a bump-pointer allocation.
50 51 52
    //              We should introduce a special bump-pointer store node to
    //              differentiate that.
    case IrOpcode::kStore:
53 54
    case IrOpcode::kStoreElement:
    case IrOpcode::kStoreField:
55
    case IrOpcode::kStoreLane:
56
    case IrOpcode::kStoreToObject:
57
    case IrOpcode::kInitializeImmutableInObject:
58 59
    case IrOpcode::kUnalignedLoad:
    case IrOpcode::kUnalignedStore:
60
    case IrOpcode::kUnreachable:
61
    case IrOpcode::kUnsafePointerAdd:
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 87 88
    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:
89 90 91 92 93
      return false;

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

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

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

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

      for (int i = 0; i < current->op()->EffectInputCount(); ++i) {
        queue.push(NodeProperties::GetEffectInput(current, i));
      }
    }
  }
121 122 123 124 125 126 127 128 129 130 131 132
  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;
    }
  }
133 134 135
  return false;
}

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

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 179 180
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());
}

181 182
}  // namespace

183
MemoryOptimizer::MemoryOptimizer(
184
    JSGraph* jsgraph, Zone* zone,
185 186
    MemoryLowering::AllocationFolding allocation_folding,
    const char* function_debug_name, TickCounter* tick_counter)
187
    : graph_assembler_(jsgraph, zone),
188 189
      memory_lowering_(jsgraph, zone, &graph_assembler_, allocation_folding,
                       WriteBarrierAssertFailed, function_debug_name),
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
      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());
}

208
void MemoryOptimizer::VisitNode(Node* node, AllocationState const* state) {
209
  tick_counter_->TickAndMaybeEnterSafepoint();
210 211 212 213 214 215 216 217 218 219 220
  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);
221
    case IrOpcode::kLoadFromObject:
222
    case IrOpcode::kLoadImmutableFromObject:
223
      return VisitLoadFromObject(node, state);
224 225 226 227
    case IrOpcode::kLoadElement:
      return VisitLoadElement(node, state);
    case IrOpcode::kLoadField:
      return VisitLoadField(node, state);
228
    case IrOpcode::kStoreToObject:
229
    case IrOpcode::kInitializeImmutableInObject:
230
      return VisitStoreToObject(node, state);
231 232 233 234 235 236 237 238 239 240 241 242
    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);
      }
  }
243 244 245
  DCHECK_EQ(0, node->op()->EffectOutputCount());
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259
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;
}

260 261 262 263 264 265 266 267 268
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();
}

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

275 276 277 278
  // 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.
279
  if (allocation_type == AllocationType::kOld) {
280 281 282
    for (Edge const edge : node->use_edges()) {
      Node* const user = edge.from();
      if (user->opcode() == IrOpcode::kStoreField && edge.index() == 0) {
283
        Node* child = user->InputAt(1);
284
        if (child->opcode() == IrOpcode::kAllocateRaw &&
285
            AllocationTypeOf(child->op()) == AllocationType::kYoung) {
286 287 288 289 290 291
          NodeProperties::ChangeOp(child, node->op());
          break;
        }
      }
    }
  } else {
292
    DCHECK_EQ(AllocationType::kYoung, allocation_type);
293 294
    for (Edge const edge : node->use_edges()) {
      Node* const user = edge.from();
295 296 297
      if (AllocationTypeNeedsUpdateToOld(user, edge)) {
        allocation_type = AllocationType::kOld;
        break;
298 299 300 301
      }
    }
  }

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

306
  ReplaceUsesAndKillNode(node, reduction.replacement());
307

308
  EnqueueUses(state->effect(), state);
309 310
}

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

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

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

void MemoryOptimizer::VisitLoadField(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kLoadField, node->opcode());
339 340 341 342
  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.
343
  EnqueueUses(node, state);
344

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

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

void MemoryOptimizer::VisitStoreField(Node* node,
                                      AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStoreField, node->opcode());
367
  memory_lowering()->ReduceStoreField(node, state);
368 369
  EnqueueUses(node, state);
}
370 371
void MemoryOptimizer::VisitStore(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStore, node->opcode());
372 373 374 375 376 377 378 379 380
  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();
381 382 383 384
  }
  EnqueueUses(node, state);
}

385 386 387 388 389 390 391 392 393 394
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();
395
  MemoryLowering::AllocationGroup* group = state->group();
396 397 398 399 400 401 402 403 404 405 406
  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.
407
      state = AllocationState::Closed(group, nullptr, zone());
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    } 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) {
423 424 425 426 427 428 429 430 431 432 433 434 435
    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.
    }
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 483 484
  } 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