move-optimizer.cc 18.9 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/compiler/backend/move-optimizer.h"
6

7
#include "src/codegen/register-configuration.h"
8

9 10 11 12
namespace v8 {
namespace internal {
namespace compiler {

13
namespace {
14

15 16 17 18
struct MoveKey {
  InstructionOperand source;
  InstructionOperand destination;
};
19 20 21

struct MoveKeyCompare {
  bool operator()(const MoveKey& a, const MoveKey& b) const {
22 23
    if (a.source.EqualsCanonicalized(b.source)) {
      return a.destination.CompareCanonicalized(b.destination);
24
    }
25
    return a.source.CompareCanonicalized(b.source);
26 27 28
  }
};

29
using MoveMap = ZoneMap<MoveKey, unsigned, MoveKeyCompare>;
30

31 32
class OperandSet {
 public:
33 34 35 36
  explicit OperandSet(ZoneVector<InstructionOperand>* buffer)
      : set_(buffer), fp_reps_(0) {
    buffer->clear();
  }
37 38

  void InsertOp(const InstructionOperand& op) {
39 40
    set_->push_back(op);

41
    if (!kSimpleFPAliasing && op.IsFPRegister())
42
      fp_reps_ |= RepresentationBit(LocationOperand::cast(op).representation());
43 44
  }

45 46 47 48 49 50 51
  bool Contains(const InstructionOperand& op) const {
    for (const InstructionOperand& elem : *set_) {
      if (elem.EqualsCanonicalized(op)) return true;
    }
    return false;
  }

52
  bool ContainsOpOrAlias(const InstructionOperand& op) const {
53
    if (Contains(op)) return true;
54 55 56 57 58 59

    if (!kSimpleFPAliasing && op.IsFPRegister()) {
      // Platforms where FP registers have complex aliasing need extra checks.
      const LocationOperand& loc = LocationOperand::cast(op);
      MachineRepresentation rep = loc.representation();
      // If haven't encountered mixed rep FP registers, skip the extra checks.
60
      if (!HasMixedFPReps(fp_reps_ | RepresentationBit(rep))) return false;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

      // Check register against aliasing registers of other FP representations.
      MachineRepresentation other_rep1, other_rep2;
      switch (rep) {
        case MachineRepresentation::kFloat32:
          other_rep1 = MachineRepresentation::kFloat64;
          other_rep2 = MachineRepresentation::kSimd128;
          break;
        case MachineRepresentation::kFloat64:
          other_rep1 = MachineRepresentation::kFloat32;
          other_rep2 = MachineRepresentation::kSimd128;
          break;
        case MachineRepresentation::kSimd128:
          other_rep1 = MachineRepresentation::kFloat32;
          other_rep2 = MachineRepresentation::kFloat64;
          break;
        default:
          UNREACHABLE();
          break;
      }
81
      const RegisterConfiguration* config = RegisterConfiguration::Default();
82 83 84 85 86
      int base = -1;
      int aliases =
          config->GetAliases(rep, loc.register_code(), other_rep1, &base);
      DCHECK(aliases > 0 || (aliases == 0 && base == -1));
      while (aliases--) {
87 88
        if (Contains(AllocatedOperand(LocationOperand::REGISTER, other_rep1,
                                      base + aliases))) {
89
          return true;
90
        }
91 92 93 94
      }
      aliases = config->GetAliases(rep, loc.register_code(), other_rep2, &base);
      DCHECK(aliases > 0 || (aliases == 0 && base == -1));
      while (aliases--) {
95 96
        if (Contains(AllocatedOperand(LocationOperand::REGISTER, other_rep2,
                                      base + aliases))) {
97
          return true;
98
        }
99 100 101 102 103 104 105
      }
    }
    return false;
  }

 private:
  static bool HasMixedFPReps(int reps) {
106
    return reps && !base::bits::IsPowerOfTwo(reps);
107 108
  }

109
  ZoneVector<InstructionOperand>* set_;
110 111
  int fp_reps_;
};
112

mtrofin's avatar
mtrofin committed
113
int FindFirstNonEmptySlot(const Instruction* instr) {
114 115
  int i = Instruction::FIRST_GAP_POSITION;
  for (; i <= Instruction::LAST_GAP_POSITION; i++) {
mtrofin's avatar
mtrofin committed
116
    ParallelMove* moves = instr->parallel_moves()[i];
117
    if (moves == nullptr) continue;
mtrofin's avatar
mtrofin committed
118
    for (MoveOperands* move : *moves) {
119 120
      if (!move->IsRedundant()) return i;
      move->Eliminate();
121
    }
122
    moves->clear();  // Clear this redundant move.
123 124 125 126
  }
  return i;
}

127
}  // namespace
128 129 130 131

MoveOptimizer::MoveOptimizer(Zone* local_zone, InstructionSequence* code)
    : local_zone_(local_zone),
      code_(code),
132 133 134
      local_vector_(local_zone),
      operand_buffer1(local_zone),
      operand_buffer2(local_zone) {}
135 136

void MoveOptimizer::Run() {
137 138 139
  for (Instruction* instruction : code()->instructions()) {
    CompressGaps(instruction);
  }
140
  for (InstructionBlock* block : code()->instruction_blocks()) {
141 142
    CompressBlock(block);
  }
143
  for (InstructionBlock* block : code()->instruction_blocks()) {
144
    if (block->PredecessorCount() <= 1) continue;
145 146
    if (!block->IsDeferred()) {
      bool has_only_deferred = true;
mtrofin's avatar
mtrofin committed
147
      for (RpoNumber& pred_id : block->predecessors()) {
148 149 150 151
        if (!code()->InstructionBlockAt(pred_id)->IsDeferred()) {
          has_only_deferred = false;
          break;
        }
152
      }
153 154 155 156 157
      // This would pull down common moves. If the moves occur in deferred
      // blocks, and the closest common successor is not deferred, we lose the
      // optimization of just spilling/filling in deferred blocks, when the
      // current block is not deferred.
      if (has_only_deferred) continue;
158
    }
159 160
    OptimizeMerge(block);
  }
161
  for (Instruction* gap : code()->instructions()) {
162 163 164 165
    FinalizeMoves(gap);
  }
}

166 167 168 169
void MoveOptimizer::RemoveClobberedDestinations(Instruction* instruction) {
  if (instruction->IsCall()) return;
  ParallelMove* moves = instruction->parallel_moves()[0];
  if (moves == nullptr) return;
170

171 172 173
  DCHECK(instruction->parallel_moves()[1] == nullptr ||
         instruction->parallel_moves()[1]->empty());

174 175
  OperandSet outputs(&operand_buffer1);
  OperandSet inputs(&operand_buffer2);
176 177 178 179

  // Outputs and temps are treated together as potentially clobbering a
  // destination operand.
  for (size_t i = 0; i < instruction->OutputCount(); ++i) {
180
    outputs.InsertOp(*instruction->OutputAt(i));
181 182
  }
  for (size_t i = 0; i < instruction->TempCount(); ++i) {
183
    outputs.InsertOp(*instruction->TempAt(i));
184 185 186 187
  }

  // Input operands block elisions.
  for (size_t i = 0; i < instruction->InputCount(); ++i) {
188
    inputs.InsertOp(*instruction->InputAt(i));
189 190 191 192
  }

  // Elide moves made redundant by the instruction.
  for (MoveOperands* move : *moves) {
193 194
    if (outputs.ContainsOpOrAlias(move->destination()) &&
        !inputs.ContainsOpOrAlias(move->destination())) {
195 196 197 198 199 200
      move->Eliminate();
    }
  }

  // The ret instruction makes any assignment before it unnecessary, except for
  // the one for its input.
201
  if (instruction->IsRet() || instruction->IsTailCall()) {
202
    for (MoveOperands* move : *moves) {
203
      if (!inputs.ContainsOpOrAlias(move->destination())) {
204 205 206 207 208 209 210 211 212 213 214 215
        move->Eliminate();
      }
    }
  }
}

void MoveOptimizer::MigrateMoves(Instruction* to, Instruction* from) {
  if (from->IsCall()) return;

  ParallelMove* from_moves = from->parallel_moves()[0];
  if (from_moves == nullptr || from_moves->empty()) return;

216 217
  OperandSet dst_cant_be(&operand_buffer1);
  OperandSet src_cant_be(&operand_buffer2);
218 219 220 221

  // If an operand is an input to the instruction, we cannot move assignments
  // where it appears on the LHS.
  for (size_t i = 0; i < from->InputCount(); ++i) {
222
    dst_cant_be.InsertOp(*from->InputAt(i));
223 224 225 226 227 228 229 230
  }
  // If an operand is output to the instruction, we cannot move assignments
  // where it appears on the RHS, because we would lose its value before the
  // instruction.
  // Same for temp operands.
  // The output can't appear on the LHS because we performed
  // RemoveClobberedDestinations for the "from" instruction.
  for (size_t i = 0; i < from->OutputCount(); ++i) {
231
    src_cant_be.InsertOp(*from->OutputAt(i));
232 233
  }
  for (size_t i = 0; i < from->TempCount(); ++i) {
234
    src_cant_be.InsertOp(*from->TempAt(i));
235 236 237 238 239 240 241
  }
  for (MoveOperands* move : *from_moves) {
    if (move->IsRedundant()) continue;
    // Assume dest has a value "V". If we have a "dest = y" move, then we can't
    // move "z = dest", because z would become y rather than "V".
    // We assume CompressMoves has happened before this, which means we don't
    // have more than one assignment to dest.
242
    src_cant_be.InsertOp(move->destination());
243 244 245 246 247 248 249
  }

  ZoneSet<MoveKey, MoveKeyCompare> move_candidates(local_zone());
  // We start with all the moves that don't have conflicting source or
  // destination operands are eligible for being moved down.
  for (MoveOperands* move : *from_moves) {
    if (move->IsRedundant()) continue;
250
    if (!dst_cant_be.ContainsOpOrAlias(move->destination())) {
251 252 253 254 255 256 257 258 259 260 261 262 263 264
      MoveKey key = {move->source(), move->destination()};
      move_candidates.insert(key);
    }
  }
  if (move_candidates.empty()) return;

  // Stabilize the candidate set.
  bool changed = false;
  do {
    changed = false;
    for (auto iter = move_candidates.begin(); iter != move_candidates.end();) {
      auto current = iter;
      ++iter;
      InstructionOperand src = current->source;
265 266
      if (src_cant_be.ContainsOpOrAlias(src)) {
        src_cant_be.InsertOp(current->destination);
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        move_candidates.erase(current);
        changed = true;
      }
    }
  } while (changed);

  ParallelMove to_move(local_zone());
  for (MoveOperands* move : *from_moves) {
    if (move->IsRedundant()) continue;
    MoveKey key = {move->source(), move->destination()};
    if (move_candidates.find(key) != move_candidates.end()) {
      to_move.AddMove(move->source(), move->destination(), code_zone());
      move->Eliminate();
    }
  }
  if (to_move.empty()) return;

  ParallelMove* dest =
      to->GetOrCreateParallelMove(Instruction::GapPosition::START, code_zone());

  CompressMoves(&to_move, dest);
  DCHECK(dest->empty());
  for (MoveOperands* m : to_move) {
    dest->push_back(m);
  }
}

void MoveOptimizer::CompressMoves(ParallelMove* left, MoveOpVector* right) {
295 296
  if (right == nullptr) return;

297 298 299
  MoveOpVector& eliminated = local_vector();
  DCHECK(eliminated.empty());

300
  if (!left->empty()) {
301 302
    // Modify the right moves in place and collect moves that will be killed by
    // merging the two gaps.
mtrofin's avatar
mtrofin committed
303
    for (MoveOperands* move : *right) {
304
      if (move->IsRedundant()) continue;
305
      left->PrepareInsertAfter(move, &eliminated);
306
    }
307
    // Eliminate dead moves.
308
    for (MoveOperands* to_eliminate : eliminated) {
309 310
      to_eliminate->Eliminate();
    }
311
    eliminated.clear();
312 313
  }
  // Add all possibly modified moves from right side.
mtrofin's avatar
mtrofin committed
314
  for (MoveOperands* move : *right) {
315 316
    if (move->IsRedundant()) continue;
    left->push_back(move);
317 318
  }
  // Nuke right.
319
  right->clear();
320
  DCHECK(eliminated.empty());
321 322
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
void MoveOptimizer::CompressGaps(Instruction* instruction) {
  int i = FindFirstNonEmptySlot(instruction);
  bool has_moves = i <= Instruction::LAST_GAP_POSITION;
  USE(has_moves);

  if (i == Instruction::LAST_GAP_POSITION) {
    std::swap(instruction->parallel_moves()[Instruction::FIRST_GAP_POSITION],
              instruction->parallel_moves()[Instruction::LAST_GAP_POSITION]);
  } else if (i == Instruction::FIRST_GAP_POSITION) {
    CompressMoves(
        instruction->parallel_moves()[Instruction::FIRST_GAP_POSITION],
        instruction->parallel_moves()[Instruction::LAST_GAP_POSITION]);
  }
  // We either have no moves, or, after swapping or compressing, we have
  // all the moves in the first gap position, and none in the second/end gap
  // position.
  ParallelMove* first =
      instruction->parallel_moves()[Instruction::FIRST_GAP_POSITION];
  ParallelMove* last =
      instruction->parallel_moves()[Instruction::LAST_GAP_POSITION];
  USE(first);
  USE(last);

  DCHECK(!has_moves ||
         (first != nullptr && (last == nullptr || last->empty())));
}
349

350
void MoveOptimizer::CompressBlock(InstructionBlock* block) {
351 352
  int first_instr_index = block->first_instruction_index();
  int last_instr_index = block->last_instruction_index();
353

354 355 356 357 358 359 360 361 362 363 364 365
  // Start by removing gap assignments where the output of the subsequent
  // instruction appears on LHS, as long as they are not needed by its input.
  Instruction* prev_instr = code()->instructions()[first_instr_index];
  RemoveClobberedDestinations(prev_instr);

  for (int index = first_instr_index + 1; index <= last_instr_index; ++index) {
    Instruction* instr = code()->instructions()[index];
    // Migrate to the gap of prev_instr eligible moves from instr.
    MigrateMoves(instr, prev_instr);
    // Remove gap assignments clobbered by instr's output.
    RemoveClobberedDestinations(instr);
    prev_instr = instr;
366
  }
367 368
}

mtrofin's avatar
mtrofin committed
369 370
const Instruction* MoveOptimizer::LastInstruction(
    const InstructionBlock* block) const {
371
  return code()->instructions()[block->last_instruction_index()];
372 373 374
}

void MoveOptimizer::OptimizeMerge(InstructionBlock* block) {
375
  DCHECK_LT(1, block->PredecessorCount());
376 377
  // Ensure that the last instruction in all incoming blocks don't contain
  // things that would prevent moving gap moves across them.
mtrofin's avatar
mtrofin committed
378 379
  for (RpoNumber& pred_index : block->predecessors()) {
    const InstructionBlock* pred = code()->InstructionBlockAt(pred_index);
380 381 382 383 384 385

    // If the predecessor has more than one successor, we shouldn't attempt to
    // move down to this block (one of the successors) any of the gap moves,
    // because their effect may be necessary to the other successors.
    if (pred->SuccessorCount() > 1) return;

mtrofin's avatar
mtrofin committed
386 387
    const Instruction* last_instr =
        code()->instructions()[pred->last_instruction_index()];
388 389 390 391
    if (last_instr->IsCall()) return;
    if (last_instr->TempCount() != 0) return;
    if (last_instr->OutputCount() != 0) return;
    for (size_t i = 0; i < last_instr->InputCount(); ++i) {
mtrofin's avatar
mtrofin committed
392
      const InstructionOperand* op = last_instr->InputAt(i);
393 394 395
      if (!op->IsConstant() && !op->IsImmediate()) return;
    }
  }
396
  // TODO(dcarney): pass a ZoneStats down for this?
397 398 399
  MoveMap move_map(local_zone());
  size_t correct_counts = 0;
  // Accumulate set of shared moves.
mtrofin's avatar
mtrofin committed
400 401 402
  for (RpoNumber& pred_index : block->predecessors()) {
    const InstructionBlock* pred = code()->InstructionBlockAt(pred_index);
    const Instruction* instr = LastInstruction(pred);
403
    if (instr->parallel_moves()[0] == nullptr ||
404
        instr->parallel_moves()[0]->empty()) {
405 406
      return;
    }
mtrofin's avatar
mtrofin committed
407
    for (const MoveOperands* move : *instr->parallel_moves()[0]) {
408
      if (move->IsRedundant()) continue;
mtrofin's avatar
mtrofin committed
409 410
      InstructionOperand src = move->source();
      InstructionOperand dst = move->destination();
411 412 413 414 415 416 417 418 419 420
      MoveKey key = {src, dst};
      auto res = move_map.insert(std::make_pair(key, 1));
      if (!res.second) {
        res.first->second++;
        if (res.first->second == block->PredecessorCount()) {
          correct_counts++;
        }
      }
    }
  }
421 422
  if (move_map.empty() || correct_counts == 0) return;

423
  // Find insertion point.
424
  Instruction* instr = code()->instructions()[block->first_instruction_index()];
425 426 427 428

  if (correct_counts != move_map.size()) {
    // Moves that are unique to each predecessor won't be pushed to the common
    // successor.
429
    OperandSet conflicting_srcs(&operand_buffer1);
430 431 432 433
    for (auto iter = move_map.begin(), end = move_map.end(); iter != end;) {
      auto current = iter;
      ++iter;
      if (current->second != block->PredecessorCount()) {
434
        InstructionOperand dest = current->first.destination;
435 436 437 438
        // Not all the moves in all the gaps are the same. Maybe some are. If
        // there are such moves, we could move them, but the destination of the
        // moves staying behind can't appear as a source of a common move,
        // because the move staying behind will clobber this destination.
439
        conflicting_srcs.InsertOp(dest);
440 441 442 443 444 445 446 447 448 449 450 451 452
        move_map.erase(current);
      }
    }

    bool changed = false;
    do {
      // If a common move can't be pushed to the common successor, then its
      // destination also can't appear as source to any move being pushed.
      changed = false;
      for (auto iter = move_map.begin(), end = move_map.end(); iter != end;) {
        auto current = iter;
        ++iter;
        DCHECK_EQ(block->PredecessorCount(), current->second);
453 454
        if (conflicting_srcs.ContainsOpOrAlias(current->first.source)) {
          conflicting_srcs.InsertOp(current->first.destination);
455 456 457 458 459 460 461 462 463
          move_map.erase(current);
          changed = true;
        }
      }
    } while (changed);
  }

  if (move_map.empty()) return;

464
  DCHECK_NOT_NULL(instr);
465
  bool gap_initialized = true;
466 467
  if (instr->parallel_moves()[0] != nullptr &&
      !instr->parallel_moves()[0]->empty()) {
468 469
    // Will compress after insertion.
    gap_initialized = false;
470
    std::swap(instr->parallel_moves()[0], instr->parallel_moves()[1]);
471
  }
mtrofin's avatar
mtrofin committed
472
  ParallelMove* moves = instr->GetOrCreateParallelMove(
473
      static_cast<Instruction::GapPosition>(0), code_zone());
474 475
  // Delete relevant entries in predecessors and move everything to block.
  bool first_iteration = true;
mtrofin's avatar
mtrofin committed
476 477 478
  for (RpoNumber& pred_index : block->predecessors()) {
    const InstructionBlock* pred = code()->InstructionBlockAt(pred_index);
    for (MoveOperands* move : *LastInstruction(pred)->parallel_moves()[0]) {
479 480
      if (move->IsRedundant()) continue;
      MoveKey key = {move->source(), move->destination()};
481
      auto it = move_map.find(key);
482 483 484 485 486
      if (it != move_map.end()) {
        if (first_iteration) {
          moves->AddMove(move->source(), move->destination());
        }
        move->Eliminate();
487 488 489 490 491 492
      }
    }
    first_iteration = false;
  }
  // Compress.
  if (!gap_initialized) {
493
    CompressMoves(instr->parallel_moves()[0], instr->parallel_moves()[1]);
494
  }
495
  CompressBlock(block);
496 497
}

498 499 500
namespace {

bool IsSlot(const InstructionOperand& op) {
501
  return op.IsStackSlot() || op.IsFPStackSlot();
502 503 504
}

bool LoadCompare(const MoveOperands* a, const MoveOperands* b) {
505 506
  if (!a->source().EqualsCanonicalized(b->source())) {
    return a->source().CompareCanonicalized(b->source());
507
  }
508 509
  if (IsSlot(a->destination()) && !IsSlot(b->destination())) return false;
  if (!IsSlot(a->destination()) && IsSlot(b->destination())) return true;
510
  return a->destination().CompareCanonicalized(b->destination());
511 512 513 514
}

}  // namespace

515 516
// Split multiple loads of the same constant or stack slot off into the second
// slot and keep remaining moves in the first slot.
517
void MoveOptimizer::FinalizeMoves(Instruction* instr) {
518
  MoveOpVector& loads = local_vector();
519
  DCHECK(loads.empty());
520

521 522
  ParallelMove* parallel_moves = instr->parallel_moves()[0];
  if (parallel_moves == nullptr) return;
523
  // Find all the loads.
524
  for (MoveOperands* move : *parallel_moves) {
525 526
    if (move->IsRedundant()) continue;
    if (move->source().IsConstant() || IsSlot(move->source())) {
527
      loads.push_back(move);
528
    }
529 530 531 532 533 534
  }
  if (loads.empty()) return;
  // Group the loads by source, moving the preferred destination to the
  // beginning of the group.
  std::sort(loads.begin(), loads.end(), LoadCompare);
  MoveOperands* group_begin = nullptr;
mtrofin's avatar
mtrofin committed
535
  for (MoveOperands* load : loads) {
536
    // New group.
537
    if (group_begin == nullptr ||
538
        !load->source().EqualsCanonicalized(group_begin->source())) {
539 540
      group_begin = load;
      continue;
541
    }
542 543 544
    // Nothing to be gained from splitting here.
    if (IsSlot(group_begin->destination())) continue;
    // Insert new move into slot 1.
mtrofin's avatar
mtrofin committed
545
    ParallelMove* slot_1 = instr->GetOrCreateParallelMove(
546 547 548
        static_cast<Instruction::GapPosition>(1), code_zone());
    slot_1->AddMove(group_begin->destination(), load->destination());
    load->Eliminate();
549
  }
550
  loads.clear();
551 552 553 554 555
}

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