memory-optimizer.cc 16.5 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::kAbortCSAAssert:
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 36
    case IrOpcode::kLoadElement:
    case IrOpcode::kLoadField:
37
    case IrOpcode::kLoadFromObject:
38
    case IrOpcode::kPoisonedLoad:
39 40
    case IrOpcode::kProtectedLoad:
    case IrOpcode::kProtectedStore:
41
    case IrOpcode::kRetain:
42 43
    case IrOpcode::kStackPointerGreaterThan:
    case IrOpcode::kStaticAssert:
44 45 46 47
    // TODO(tebbi): Store nodes might do a bump-pointer allocation.
    //              We should introduce a special bump-pointer store node to
    //              differentiate that.
    case IrOpcode::kStore:
48 49
    case IrOpcode::kStoreElement:
    case IrOpcode::kStoreField:
50
    case IrOpcode::kStoreToObject:
51 52 53
    case IrOpcode::kTaggedPoisonOnSpeculation:
    case IrOpcode::kUnalignedLoad:
    case IrOpcode::kUnalignedStore:
54
    case IrOpcode::kUnreachable:
55
    case IrOpcode::kUnsafePointerAdd:
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    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:
74
    case IrOpcode::kWord32PoisonOnSpeculation:
75 76 77 78 79 80 81 82 83
    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:
84
    case IrOpcode::kWord64PoisonOnSpeculation:
85 86 87 88 89
      return false;

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

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

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

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

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

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

142 143 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
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());
}

177 178
}  // namespace

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

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

241 242 243 244 245 246 247 248 249 250 251 252 253 254
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;
}

255 256 257
void MemoryOptimizer::VisitAllocateRaw(Node* node,
                                       AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kAllocateRaw, node->opcode());
258 259
  const AllocateParameters& allocation = AllocateParametersOf(node->op());
  AllocationType allocation_type = allocation.allocation_type();
260

261 262 263 264
  // 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.
265
  if (allocation_type == AllocationType::kOld) {
266 267 268
    for (Edge const edge : node->use_edges()) {
      Node* const user = edge.from();
      if (user->opcode() == IrOpcode::kStoreField && edge.index() == 0) {
269
        Node* child = user->InputAt(1);
270
        if (child->opcode() == IrOpcode::kAllocateRaw &&
271
            AllocationTypeOf(child->op()) == AllocationType::kYoung) {
272 273 274 275 276 277
          NodeProperties::ChangeOp(child, node->op());
          break;
        }
      }
    }
  } else {
278
    DCHECK_EQ(AllocationType::kYoung, allocation_type);
279 280
    for (Edge const edge : node->use_edges()) {
      Node* const user = edge.from();
281 282 283
      if (AllocationTypeNeedsUpdateToOld(user, edge)) {
        allocation_type = AllocationType::kOld;
        break;
284 285 286 287
      }
    }
  }

288
  Reduction reduction = memory_lowering()->ReduceAllocateRaw(
289
      node, allocation_type, allocation.allow_large_objects(), &state);
290 291 292 293 294
  CHECK(reduction.Changed() && reduction.replacement() != node);

  // Replace all uses of node and kill the node to make sure we don't leave
  // dangling dead uses.
  NodeProperties::ReplaceUses(node, reduction.replacement(),
295 296
                              graph_assembler_.effect(),
                              graph_assembler_.control());
297 298
  node->Kill();

299
  EnqueueUses(state->effect(), state);
300 301
}

302 303 304
void MemoryOptimizer::VisitLoadFromObject(Node* node,
                                          AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kLoadFromObject, node->opcode());
305
  memory_lowering()->ReduceLoadFromObject(node);
306 307 308 309 310 311
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitStoreToObject(Node* node,
                                         AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStoreToObject, node->opcode());
312
  memory_lowering()->ReduceStoreToObject(node, state);
313 314 315 316 317 318
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitLoadElement(Node* node,
                                       AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kLoadElement, node->opcode());
319
  memory_lowering()->ReduceLoadElement(node);
320 321 322 323 324
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitLoadField(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kLoadField, node->opcode());
325 326 327 328
  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.
329
  EnqueueUses(node, state);
330 331 332 333 334 335 336 337 338 339 340 341

  // Node can be replaced only when V8_HEAP_SANDBOX_BOOL is enabled and
  // when loading an external pointer value.
  DCHECK_IMPLIES(!V8_HEAP_SANDBOX_BOOL, reduction.replacement() == node);
  if (V8_HEAP_SANDBOX_BOOL && reduction.replacement() != node) {
    // Replace all uses of node and kill the node to make sure we don't leave
    // dangling dead uses.
    NodeProperties::ReplaceUses(node, reduction.replacement(),
                                graph_assembler_.effect(),
                                graph_assembler_.control());
    node->Kill();
  }
342 343 344 345 346
}

void MemoryOptimizer::VisitStoreElement(Node* node,
                                        AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStoreElement, node->opcode());
347
  memory_lowering()->ReduceStoreElement(node, state);
348 349 350 351 352 353
  EnqueueUses(node, state);
}

void MemoryOptimizer::VisitStoreField(Node* node,
                                      AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStoreField, node->opcode());
354
  memory_lowering()->ReduceStoreField(node, state);
355 356
  EnqueueUses(node, state);
}
357 358
void MemoryOptimizer::VisitStore(Node* node, AllocationState const* state) {
  DCHECK_EQ(IrOpcode::kStore, node->opcode());
359 360 361 362 363 364 365 366 367
  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();
368 369 370 371
  }
  EnqueueUses(node, state);
}

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