blob: 4a6b835e80d02725134e344b8d2a5c9c441eb3fd [file] [log] [blame]
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "register_allocator.h"
18
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000019#include <iostream>
Ian Rogersc7dd2952014-10-21 23:31:19 -070020#include <sstream>
21
Ian Rogerse77493c2014-08-20 15:08:45 -070022#include "base/bit_vector-inl.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010023#include "code_generator.h"
24#include "ssa_liveness_analysis.h"
25
26namespace art {
27
28static constexpr size_t kMaxLifetimePosition = -1;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010029static constexpr size_t kDefaultNumberOfSpillSlots = 4;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010030
Nicolas Geoffray840e5462015-01-07 16:01:24 +000031// For simplicity, we implement register pairs as (reg, reg + 1).
32// Note that this is a requirement for double registers on ARM, since we
33// allocate SRegister.
34static int GetHighForLowRegister(int reg) { return reg + 1; }
35static bool IsLowRegister(int reg) { return (reg & 1) == 0; }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000036static bool IsLowOfUnalignedPairInterval(LiveInterval* low) {
37 return GetHighForLowRegister(low->GetRegister()) != low->GetHighInterval()->GetRegister();
38}
Nicolas Geoffray840e5462015-01-07 16:01:24 +000039
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010040RegisterAllocator::RegisterAllocator(ArenaAllocator* allocator,
41 CodeGenerator* codegen,
42 const SsaLivenessAnalysis& liveness)
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010043 : allocator_(allocator),
44 codegen_(codegen),
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010045 liveness_(liveness),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010046 unhandled_core_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
47 unhandled_fp_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
Nicolas Geoffray39468442014-09-02 15:17:15 +010048 unhandled_(nullptr),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010049 handled_(allocator->Adapter(kArenaAllocRegisterAllocator)),
50 active_(allocator->Adapter(kArenaAllocRegisterAllocator)),
51 inactive_(allocator->Adapter(kArenaAllocRegisterAllocator)),
52 physical_core_register_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
53 physical_fp_register_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
54 temp_intervals_(allocator->Adapter(kArenaAllocRegisterAllocator)),
55 int_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
56 long_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
57 float_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
58 double_spill_slots_(allocator->Adapter(kArenaAllocRegisterAllocator)),
David Brazdil77a48ae2015-09-15 12:34:04 +000059 catch_phi_spill_slots_(0),
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010060 safepoints_(allocator->Adapter(kArenaAllocRegisterAllocator)),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010061 processing_core_registers_(false),
62 number_of_registers_(-1),
63 registers_array_(nullptr),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010064 blocked_core_registers_(codegen->GetBlockedCoreRegisters()),
65 blocked_fp_registers_(codegen->GetBlockedFloatingPointRegisters()),
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +010066 reserved_out_slots_(0),
Mark Mendellf85a9ca2015-01-13 09:20:58 -050067 maximum_number_of_live_core_registers_(0),
68 maximum_number_of_live_fp_registers_(0) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010069 temp_intervals_.reserve(4);
70 int_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
71 long_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
72 float_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
73 double_spill_slots_.reserve(kDefaultNumberOfSpillSlots);
74
David Brazdil58282f42016-01-14 12:45:10 +000075 codegen->SetupBlockedRegisters();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010076 physical_core_register_intervals_.resize(codegen->GetNumberOfCoreRegisters(), nullptr);
77 physical_fp_register_intervals_.resize(codegen->GetNumberOfFloatingPointRegisters(), nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +010078 // Always reserve for the current method and the graph's max out registers.
79 // TODO: compute it instead.
Mathieu Chartiere401d142015-04-22 13:56:20 -070080 // ArtMethod* takes 2 vregs for 64 bits.
81 reserved_out_slots_ = InstructionSetPointerSize(codegen->GetInstructionSet()) / kVRegSize +
82 codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010083}
84
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000085bool RegisterAllocator::CanAllocateRegistersFor(const HGraph& graph ATTRIBUTE_UNUSED,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010086 InstructionSet instruction_set) {
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020087 return instruction_set == kArm
88 || instruction_set == kArm64
89 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -070090 || instruction_set == kMips64
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020091 || instruction_set == kThumb2
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000092 || instruction_set == kX86
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020093 || instruction_set == kX86_64;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010094}
95
96static bool ShouldProcess(bool processing_core_registers, LiveInterval* interval) {
Nicolas Geoffray39468442014-09-02 15:17:15 +010097 if (interval == nullptr) return false;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010098 bool is_core_register = (interval->GetType() != Primitive::kPrimDouble)
99 && (interval->GetType() != Primitive::kPrimFloat);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100100 return processing_core_registers == is_core_register;
101}
102
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100103void RegisterAllocator::AllocateRegisters() {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100104 AllocateRegistersInternal();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100105 Resolve();
106
107 if (kIsDebugBuild) {
108 processing_core_registers_ = true;
109 ValidateInternal(true);
110 processing_core_registers_ = false;
111 ValidateInternal(true);
Nicolas Geoffray59768572014-12-01 09:50:04 +0000112 // Check that the linear order is still correct with regards to lifetime positions.
113 // Since only parallel moves have been inserted during the register allocation,
114 // these checks are mostly for making sure these moves have been added correctly.
115 size_t current_liveness = 0;
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100116 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray59768572014-12-01 09:50:04 +0000117 HBasicBlock* block = it.Current();
118 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
119 HInstruction* instruction = inst_it.Current();
120 DCHECK_LE(current_liveness, instruction->GetLifetimePosition());
121 current_liveness = instruction->GetLifetimePosition();
122 }
123 for (HInstructionIterator inst_it(block->GetInstructions());
124 !inst_it.Done();
125 inst_it.Advance()) {
126 HInstruction* instruction = inst_it.Current();
127 DCHECK_LE(current_liveness, instruction->GetLifetimePosition()) << instruction->DebugName();
128 current_liveness = instruction->GetLifetimePosition();
129 }
130 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100131 }
132}
133
David Brazdil77a48ae2015-09-15 12:34:04 +0000134void RegisterAllocator::BlockRegister(Location location, size_t start, size_t end) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100135 int reg = location.reg();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100136 DCHECK(location.IsRegister() || location.IsFpuRegister());
137 LiveInterval* interval = location.IsRegister()
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100138 ? physical_core_register_intervals_[reg]
139 : physical_fp_register_intervals_[reg];
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100140 Primitive::Type type = location.IsRegister()
141 ? Primitive::kPrimInt
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000142 : Primitive::kPrimFloat;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100143 if (interval == nullptr) {
144 interval = LiveInterval::MakeFixedInterval(allocator_, reg, type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100145 if (location.IsRegister()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100146 physical_core_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100147 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100148 physical_fp_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100149 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100150 }
151 DCHECK(interval->GetRegister() == reg);
152 interval->AddRange(start, end);
153}
154
David Brazdil77a48ae2015-09-15 12:34:04 +0000155void RegisterAllocator::BlockRegisters(size_t start, size_t end, bool caller_save_only) {
156 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
157 if (!caller_save_only || !codegen_->IsCoreCalleeSaveRegister(i)) {
158 BlockRegister(Location::RegisterLocation(i), start, end);
159 }
160 }
161 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
162 if (!caller_save_only || !codegen_->IsFloatingPointCalleeSaveRegister(i)) {
163 BlockRegister(Location::FpuRegisterLocation(i), start, end);
164 }
165 }
166}
167
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100168void RegisterAllocator::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100169 // Iterate post-order, to ensure the list is sorted, and the last added interval
170 // is the one with the lowest start position.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100171 for (HLinearPostOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100172 HBasicBlock* block = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800173 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
174 back_it.Advance()) {
175 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100176 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800177 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
178 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100179 }
David Brazdil77a48ae2015-09-15 12:34:04 +0000180
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000181 if (block->IsCatchBlock() ||
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +0000182 (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000183 // By blocking all registers at the top of each catch block or irreducible loop, we force
184 // intervals belonging to the live-in set of the catch/header block to be spilled.
185 // TODO(ngeoffray): Phis in this block could be allocated in register.
David Brazdil77a48ae2015-09-15 12:34:04 +0000186 size_t position = block->GetLifetimeStart();
187 BlockRegisters(position, position + 1);
188 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100189 }
190
Nicolas Geoffray39468442014-09-02 15:17:15 +0100191 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100192 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
193 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100194 processing_core_registers_ = true;
195 unhandled_ = &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100196 for (LiveInterval* fixed : physical_core_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100197 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700198 // Fixed interval is added to inactive_ instead of unhandled_.
199 // It's also the only type of inactive interval whose start position
200 // can be after the current interval during linear scan.
201 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100202 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100203 }
204 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100205 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100206
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100207 inactive_.clear();
208 active_.clear();
209 handled_.clear();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100210
211 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100212 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
213 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100214 processing_core_registers_ = false;
215 unhandled_ = &unhandled_fp_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100216 for (LiveInterval* fixed : physical_fp_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100217 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700218 // Fixed interval is added to inactive_ instead of unhandled_.
219 // It's also the only type of inactive interval whose start position
220 // can be after the current interval during linear scan.
221 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100222 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100223 }
224 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100225 LinearScan();
226}
227
228void RegisterAllocator::ProcessInstruction(HInstruction* instruction) {
229 LocationSummary* locations = instruction->GetLocations();
230 size_t position = instruction->GetLifetimePosition();
231
232 if (locations == nullptr) return;
233
234 // Create synthesized intervals for temporaries.
235 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
236 Location temp = locations->GetTemp(i);
Nicolas Geoffray52839d12014-11-07 17:47:25 +0000237 if (temp.IsRegister() || temp.IsFpuRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100238 BlockRegister(temp, position, position + 1);
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000239 // Ensure that an explicit temporary register is marked as being allocated.
240 codegen_->AddAllocatedRegister(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100241 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100242 DCHECK(temp.IsUnallocated());
Roland Levillain5368c212014-11-27 15:03:41 +0000243 switch (temp.GetPolicy()) {
244 case Location::kRequiresRegister: {
245 LiveInterval* interval =
246 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimInt);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100247 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000248 interval->AddTempUse(instruction, i);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100249 unhandled_core_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000250 break;
251 }
252
253 case Location::kRequiresFpuRegister: {
254 LiveInterval* interval =
255 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimDouble);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100256 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000257 interval->AddTempUse(instruction, i);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000258 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100259 interval->AddHighInterval(/* is_temp */ true);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000260 LiveInterval* high = interval->GetHighInterval();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100261 temp_intervals_.push_back(high);
262 unhandled_fp_intervals_.push_back(high);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000263 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100264 unhandled_fp_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000265 break;
266 }
267
268 default:
269 LOG(FATAL) << "Unexpected policy for temporary location "
270 << temp.GetPolicy();
271 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100272 }
273 }
274
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100275 bool core_register = (instruction->GetType() != Primitive::kPrimDouble)
276 && (instruction->GetType() != Primitive::kPrimFloat);
277
Alexandre Rames8158f282015-08-07 10:26:17 +0100278 if (locations->NeedsSafepoint()) {
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000279 if (codegen_->IsLeafMethod()) {
280 // TODO: We do this here because we do not want the suspend check to artificially
281 // create live registers. We should find another place, but this is currently the
282 // simplest.
283 DCHECK(instruction->IsSuspendCheckEntry());
284 instruction->GetBlock()->RemoveInstruction(instruction);
285 return;
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100286 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100287 safepoints_.push_back(instruction);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100288 if (locations->OnlyCallsOnSlowPath()) {
289 // We add a synthesized range at this position to record the live registers
290 // at this position. Ideally, we could just update the safepoints when locations
291 // are updated, but we currently need to know the full stack size before updating
292 // locations (because of parameters and the fact that we don't have a frame pointer).
293 // And knowing the full stack size requires to know the maximum number of live
294 // registers at calls in slow paths.
295 // By adding the following interval in the algorithm, we can compute this
296 // maximum before updating locations.
297 LiveInterval* interval = LiveInterval::MakeSlowPathInterval(allocator_, instruction);
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000298 interval->AddRange(position, position + 1);
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000299 AddSorted(&unhandled_core_intervals_, interval);
300 AddSorted(&unhandled_fp_intervals_, interval);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100301 }
302 }
303
304 if (locations->WillCall()) {
David Brazdil77a48ae2015-09-15 12:34:04 +0000305 BlockRegisters(position, position + 1, /* caller_save_only */ true);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100306 }
307
Vladimir Marko372f10e2016-05-17 16:30:10 +0100308 for (size_t i = 0; i < locations->GetInputCount(); ++i) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100309 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100310 if (input.IsRegister() || input.IsFpuRegister()) {
311 BlockRegister(input, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000312 } else if (input.IsPair()) {
313 BlockRegister(input.ToLow(), position, position + 1);
314 BlockRegister(input.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100315 }
316 }
317
Nicolas Geoffray39468442014-09-02 15:17:15 +0100318 LiveInterval* current = instruction->GetLiveInterval();
319 if (current == nullptr) return;
320
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100321 ArenaVector<LiveInterval*>& unhandled = core_register
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100322 ? unhandled_core_intervals_
323 : unhandled_fp_intervals_;
324
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100325 DCHECK(unhandled.empty() || current->StartsBeforeOrAt(unhandled.back()));
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000326
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000327 if (codegen_->NeedsTwoRegisters(current->GetType())) {
328 current->AddHighInterval();
329 }
330
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100331 for (size_t safepoint_index = safepoints_.size(); safepoint_index > 0; --safepoint_index) {
332 HInstruction* safepoint = safepoints_[safepoint_index - 1u];
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100333 size_t safepoint_position = safepoint->GetLifetimePosition();
334
335 // Test that safepoints are ordered in the optimal way.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100336 DCHECK(safepoint_index == safepoints_.size() ||
337 safepoints_[safepoint_index]->GetLifetimePosition() < safepoint_position);
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100338
339 if (safepoint_position == current->GetStart()) {
340 // The safepoint is for this instruction, so the location of the instruction
341 // does not need to be saved.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100342 DCHECK_EQ(safepoint_index, safepoints_.size());
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100343 DCHECK_EQ(safepoint, instruction);
344 continue;
345 } else if (current->IsDeadAt(safepoint_position)) {
346 break;
347 } else if (!current->Covers(safepoint_position)) {
348 // Hole in the interval.
349 continue;
350 }
351 current->AddSafepoint(safepoint);
352 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100353 current->ResetSearchCache();
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100354
Nicolas Geoffray39468442014-09-02 15:17:15 +0100355 // Some instructions define their output in fixed register/stack slot. We need
356 // to ensure we know these locations before doing register allocation. For a
357 // given register, we create an interval that covers these locations. The register
358 // will be unavailable at these locations when trying to allocate one for an
359 // interval.
360 //
361 // The backwards walking ensures the ranges are ordered on increasing start positions.
362 Location output = locations->Out();
Calin Juravled0d48522014-11-04 16:40:20 +0000363 if (output.IsUnallocated() && output.GetPolicy() == Location::kSameAsFirstInput) {
364 Location first = locations->InAt(0);
365 if (first.IsRegister() || first.IsFpuRegister()) {
366 current->SetFrom(position + 1);
367 current->SetRegister(first.reg());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000368 } else if (first.IsPair()) {
369 current->SetFrom(position + 1);
370 current->SetRegister(first.low());
371 LiveInterval* high = current->GetHighInterval();
372 high->SetRegister(first.high());
373 high->SetFrom(position + 1);
Calin Juravled0d48522014-11-04 16:40:20 +0000374 }
375 } else if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100376 // Shift the interval's start by one to account for the blocked register.
377 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100378 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100379 BlockRegister(output, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000380 } else if (output.IsPair()) {
381 current->SetFrom(position + 1);
382 current->SetRegister(output.low());
383 LiveInterval* high = current->GetHighInterval();
384 high->SetRegister(output.high());
385 high->SetFrom(position + 1);
386 BlockRegister(output.ToLow(), position, position + 1);
387 BlockRegister(output.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100388 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
389 current->SetSpillSlot(output.GetStackIndex());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000390 } else {
391 DCHECK(output.IsUnallocated() || output.IsConstant());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100392 }
393
David Brazdil77a48ae2015-09-15 12:34:04 +0000394 if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
395 AllocateSpillSlotForCatchPhi(instruction->AsPhi());
396 }
397
Nicolas Geoffray39468442014-09-02 15:17:15 +0100398 // If needed, add interval to the list of unhandled intervals.
399 if (current->HasSpillSlot() || instruction->IsConstant()) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100400 // Split just before first register use.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100401 size_t first_register_use = current->FirstRegisterUse();
402 if (first_register_use != kNoLifetime) {
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +0100403 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000404 // Don't add directly to `unhandled`, it needs to be sorted and the start
Nicolas Geoffray39468442014-09-02 15:17:15 +0100405 // of this new interval might be after intervals already in the list.
406 AddSorted(&unhandled, split);
407 } else {
408 // Nothing to do, we won't allocate a register for this value.
409 }
410 } else {
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000411 // Don't add directly to `unhandled`, temp or safepoint intervals
412 // for this instruction may have been added, and those can be
413 // processed first.
414 AddSorted(&unhandled, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100415 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100416}
417
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100418class AllRangesIterator : public ValueObject {
419 public:
420 explicit AllRangesIterator(LiveInterval* interval)
421 : current_interval_(interval),
422 current_range_(interval->GetFirstRange()) {}
423
424 bool Done() const { return current_interval_ == nullptr; }
425 LiveRange* CurrentRange() const { return current_range_; }
426 LiveInterval* CurrentInterval() const { return current_interval_; }
427
428 void Advance() {
429 current_range_ = current_range_->GetNext();
430 if (current_range_ == nullptr) {
431 current_interval_ = current_interval_->GetNextSibling();
432 if (current_interval_ != nullptr) {
433 current_range_ = current_interval_->GetFirstRange();
434 }
435 }
436 }
437
438 private:
439 LiveInterval* current_interval_;
440 LiveRange* current_range_;
441
442 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
443};
444
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100445bool RegisterAllocator::ValidateInternal(bool log_fatal_on_failure) const {
446 // To simplify unit testing, we eagerly create the array of intervals, and
447 // call the helper method.
Vladimir Markof6a35de2016-03-21 12:01:50 +0000448 ArenaVector<LiveInterval*> intervals(allocator_->Adapter(kArenaAllocRegisterAllocatorValidate));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100449 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
450 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
451 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100452 intervals.push_back(instruction->GetLiveInterval());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100453 }
454 }
455
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100456 const ArenaVector<LiveInterval*>* physical_register_intervals = processing_core_registers_
457 ? &physical_core_register_intervals_
458 : &physical_fp_register_intervals_;
459 for (LiveInterval* fixed : *physical_register_intervals) {
460 if (fixed != nullptr) {
461 intervals.push_back(fixed);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100462 }
463 }
464
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100465 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100466 if (ShouldProcess(processing_core_registers_, temp)) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100467 intervals.push_back(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100468 }
469 }
470
Nicolas Geoffray776b3182015-02-23 14:14:57 +0000471 return ValidateIntervals(intervals, GetNumberOfSpillSlots(), reserved_out_slots_, *codegen_,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100472 allocator_, processing_core_registers_, log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100473}
474
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100475bool RegisterAllocator::ValidateIntervals(const ArenaVector<LiveInterval*>& intervals,
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100476 size_t number_of_spill_slots,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100477 size_t number_of_out_slots,
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100478 const CodeGenerator& codegen,
479 ArenaAllocator* allocator,
480 bool processing_core_registers,
481 bool log_fatal_on_failure) {
482 size_t number_of_registers = processing_core_registers
483 ? codegen.GetNumberOfCoreRegisters()
484 : codegen.GetNumberOfFloatingPointRegisters();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100485 ArenaVector<ArenaBitVector*> liveness_of_values(
Vladimir Markof6a35de2016-03-21 12:01:50 +0000486 allocator->Adapter(kArenaAllocRegisterAllocatorValidate));
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100487 liveness_of_values.reserve(number_of_registers + number_of_spill_slots);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100488
Vladimir Markof6a35de2016-03-21 12:01:50 +0000489 size_t max_end = 0u;
490 for (LiveInterval* start_interval : intervals) {
491 for (AllRangesIterator it(start_interval); !it.Done(); it.Advance()) {
492 max_end = std::max(max_end, it.CurrentRange()->GetEnd());
493 }
494 }
495
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100496 // Allocate a bit vector per register. A live interval that has a register
497 // allocated will populate the associated bit vector based on its live ranges.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100498 for (size_t i = 0; i < number_of_registers + number_of_spill_slots; ++i) {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000499 liveness_of_values.push_back(
500 ArenaBitVector::Create(allocator, max_end, false, kArenaAllocRegisterAllocatorValidate));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100501 }
502
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100503 for (LiveInterval* start_interval : intervals) {
504 for (AllRangesIterator it(start_interval); !it.Done(); it.Advance()) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100505 LiveInterval* current = it.CurrentInterval();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100506 HInstruction* defined_by = current->GetParent()->GetDefinedBy();
507 if (current->GetParent()->HasSpillSlot()
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100508 // Parameters and current method have their own stack slot.
509 && !(defined_by != nullptr && (defined_by->IsParameterValue()
510 || defined_by->IsCurrentMethod()))) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100511 BitVector* liveness_of_spill_slot = liveness_of_values[number_of_registers
Nicolas Geoffray39468442014-09-02 15:17:15 +0100512 + current->GetParent()->GetSpillSlot() / kVRegSize
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100513 - number_of_out_slots];
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100514 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
515 if (liveness_of_spill_slot->IsBitSet(j)) {
516 if (log_fatal_on_failure) {
517 std::ostringstream message;
518 message << "Spill slot conflict at " << j;
519 LOG(FATAL) << message.str();
520 } else {
521 return false;
522 }
523 } else {
524 liveness_of_spill_slot->SetBit(j);
525 }
526 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100527 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100528
529 if (current->HasRegister()) {
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000530 if (kIsDebugBuild && log_fatal_on_failure && !current->IsFixed()) {
531 // Only check when an error is fatal. Only tests code ask for non-fatal failures
532 // and test code may not properly fill the right information to the code generator.
533 CHECK(codegen.HasAllocatedRegister(processing_core_registers, current->GetRegister()));
534 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100535 BitVector* liveness_of_register = liveness_of_values[current->GetRegister()];
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100536 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
537 if (liveness_of_register->IsBitSet(j)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000538 if (current->IsUsingInputRegister() && current->CanUseInputRegister()) {
539 continue;
540 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100541 if (log_fatal_on_failure) {
542 std::ostringstream message;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100543 message << "Register conflict at " << j << " ";
544 if (defined_by != nullptr) {
545 message << "(" << defined_by->DebugName() << ")";
546 }
547 message << "for ";
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100548 if (processing_core_registers) {
549 codegen.DumpCoreRegister(message, current->GetRegister());
550 } else {
551 codegen.DumpFloatingPointRegister(message, current->GetRegister());
552 }
553 LOG(FATAL) << message.str();
554 } else {
555 return false;
556 }
557 } else {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100558 liveness_of_register->SetBit(j);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100559 }
560 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100561 }
562 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100563 }
564 return true;
565}
566
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100567void RegisterAllocator::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100568 interval->Dump(stream);
569 stream << ": ";
570 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100571 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100572 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100573 } else {
574 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100575 }
576 } else {
577 stream << "spilled";
578 }
579 stream << std::endl;
580}
581
Mingyao Yang296bd602014-10-06 16:47:28 -0700582void RegisterAllocator::DumpAllIntervals(std::ostream& stream) const {
583 stream << "inactive: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100584 for (LiveInterval* inactive_interval : inactive_) {
585 DumpInterval(stream, inactive_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700586 }
587 stream << "active: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100588 for (LiveInterval* active_interval : active_) {
589 DumpInterval(stream, active_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700590 }
591 stream << "unhandled: " << std::endl;
592 auto unhandled = (unhandled_ != nullptr) ?
593 unhandled_ : &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100594 for (LiveInterval* unhandled_interval : *unhandled) {
595 DumpInterval(stream, unhandled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700596 }
597 stream << "handled: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100598 for (LiveInterval* handled_interval : handled_) {
599 DumpInterval(stream, handled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700600 }
601}
602
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100603// By the book implementation of a linear scan register allocator.
604void RegisterAllocator::LinearScan() {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100605 while (!unhandled_->empty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100606 // (1) Remove interval with the lowest start position from unhandled.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100607 LiveInterval* current = unhandled_->back();
608 unhandled_->pop_back();
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100609
610 // Make sure the interval is an expected state.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100611 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100612 // Make sure we are going in the right order.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100613 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() >= current->GetStart());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100614 // Make sure a low interval is always with a high.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100615 DCHECK(!current->IsLowInterval() || unhandled_->back()->IsHighInterval());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100616 // Make sure a high interval is always with a low.
617 DCHECK(current->IsLowInterval() ||
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100618 unhandled_->empty() ||
619 !unhandled_->back()->IsHighInterval());
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000620
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100621 size_t position = current->GetStart();
622
Mingyao Yang296bd602014-10-06 16:47:28 -0700623 // Remember the inactive_ size here since the ones moved to inactive_ from
624 // active_ below shouldn't need to be re-checked.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100625 size_t inactive_intervals_to_handle = inactive_.size();
Mingyao Yang296bd602014-10-06 16:47:28 -0700626
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100627 // (2) Remove currently active intervals that are dead at this position.
628 // Move active intervals that have a lifetime hole at this position
629 // to inactive.
Vladimir Markob95fb772015-09-30 13:32:31 +0100630 auto active_kept_end = std::remove_if(
631 active_.begin(),
632 active_.end(),
633 [this, position](LiveInterval* interval) {
634 if (interval->IsDeadAt(position)) {
635 handled_.push_back(interval);
636 return true;
637 } else if (!interval->Covers(position)) {
638 inactive_.push_back(interval);
639 return true;
640 } else {
641 return false; // Keep this interval.
642 }
643 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100644 active_.erase(active_kept_end, active_.end());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100645
646 // (3) Remove currently inactive intervals that are dead at this position.
647 // Move inactive intervals that cover this position to active.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100648 auto inactive_to_handle_end = inactive_.begin() + inactive_intervals_to_handle;
Vladimir Markob95fb772015-09-30 13:32:31 +0100649 auto inactive_kept_end = std::remove_if(
650 inactive_.begin(),
651 inactive_to_handle_end,
652 [this, position](LiveInterval* interval) {
653 DCHECK(interval->GetStart() < position || interval->IsFixed());
654 if (interval->IsDeadAt(position)) {
655 handled_.push_back(interval);
656 return true;
657 } else if (interval->Covers(position)) {
658 active_.push_back(interval);
659 return true;
660 } else {
661 return false; // Keep this interval.
662 }
663 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100664 inactive_.erase(inactive_kept_end, inactive_to_handle_end);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100665
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000666 if (current->IsSlowPathSafepoint()) {
667 // Synthesized interval to record the maximum number of live registers
668 // at safepoints. No need to allocate a register for it.
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500669 if (processing_core_registers_) {
670 maximum_number_of_live_core_registers_ =
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100671 std::max(maximum_number_of_live_core_registers_, active_.size());
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500672 } else {
673 maximum_number_of_live_fp_registers_ =
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100674 std::max(maximum_number_of_live_fp_registers_, active_.size());
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500675 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100676 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() > current->GetStart());
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000677 continue;
678 }
679
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000680 if (current->IsHighInterval() && !current->GetLowInterval()->HasRegister()) {
681 DCHECK(!current->HasRegister());
682 // Allocating the low part was unsucessful. The splitted interval for the high part
683 // will be handled next (it is in the `unhandled_` list).
684 continue;
685 }
686
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100687 // (4) Try to find an available register.
688 bool success = TryAllocateFreeReg(current);
689
690 // (5) If no register could be found, we need to spill.
691 if (!success) {
692 success = AllocateBlockedReg(current);
693 }
694
695 // (6) If the interval had a register allocated, add it to the list of active
696 // intervals.
697 if (success) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000698 codegen_->AddAllocatedRegister(processing_core_registers_
699 ? Location::RegisterLocation(current->GetRegister())
700 : Location::FpuRegisterLocation(current->GetRegister()));
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100701 active_.push_back(current);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000702 if (current->HasHighInterval() && !current->GetHighInterval()->HasRegister()) {
703 current->GetHighInterval()->SetRegister(GetHighForLowRegister(current->GetRegister()));
704 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100705 }
706 }
707}
708
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000709static void FreeIfNotCoverAt(LiveInterval* interval, size_t position, size_t* free_until) {
710 DCHECK(!interval->IsHighInterval());
711 // Note that the same instruction may occur multiple times in the input list,
712 // so `free_until` may have changed already.
David Brazdil3fc992f2015-04-16 18:31:55 +0100713 // Since `position` is not the current scan position, we need to use CoversSlow.
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000714 if (interval->IsDeadAt(position)) {
715 // Set the register to be free. Note that inactive intervals might later
716 // update this.
717 free_until[interval->GetRegister()] = kMaxLifetimePosition;
718 if (interval->HasHighInterval()) {
719 DCHECK(interval->GetHighInterval()->IsDeadAt(position));
720 free_until[interval->GetHighInterval()->GetRegister()] = kMaxLifetimePosition;
721 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100722 } else if (!interval->CoversSlow(position)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000723 // The interval becomes inactive at `defined_by`. We make its register
724 // available only until the next use strictly after `defined_by`.
725 free_until[interval->GetRegister()] = interval->FirstUseAfter(position);
726 if (interval->HasHighInterval()) {
David Brazdil3fc992f2015-04-16 18:31:55 +0100727 DCHECK(!interval->GetHighInterval()->CoversSlow(position));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000728 free_until[interval->GetHighInterval()->GetRegister()] = free_until[interval->GetRegister()];
729 }
730 }
731}
732
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100733// Find a free register. If multiple are found, pick the register that
734// is free the longest.
735bool RegisterAllocator::TryAllocateFreeReg(LiveInterval* current) {
736 size_t* free_until = registers_array_;
737
738 // First set all registers to be free.
739 for (size_t i = 0; i < number_of_registers_; ++i) {
740 free_until[i] = kMaxLifetimePosition;
741 }
742
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100743 // For each active interval, set its register to not free.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100744 for (LiveInterval* interval : active_) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100745 DCHECK(interval->HasRegister());
746 free_until[interval->GetRegister()] = 0;
747 }
748
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000749 // An interval that starts an instruction (that is, it is not split), may
750 // re-use the registers used by the inputs of that instruciton, based on the
751 // location summary.
752 HInstruction* defined_by = current->GetDefinedBy();
753 if (defined_by != nullptr && !current->IsSplit()) {
754 LocationSummary* locations = defined_by->GetLocations();
755 if (!locations->OutputCanOverlapWithInputs() && locations->Out().IsUnallocated()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100756 auto&& inputs = defined_by->GetInputs();
757 for (size_t i = 0; i < inputs.size(); ++i) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000758 // Take the last interval of the input. It is the location of that interval
759 // that will be used at `defined_by`.
Vladimir Marko372f10e2016-05-17 16:30:10 +0100760 LiveInterval* interval = inputs[i]->GetLiveInterval()->GetLastSibling();
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000761 // Note that interval may have not been processed yet.
762 // TODO: Handle non-split intervals last in the work list.
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100763 if (locations->InAt(i).IsValid()
764 && interval->HasRegister()
765 && interval->SameRegisterKind(*current)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000766 // The input must be live until the end of `defined_by`, to comply to
767 // the linear scan algorithm. So we use `defined_by`'s end lifetime
768 // position to check whether the input is dead or is inactive after
769 // `defined_by`.
David Brazdil3fc992f2015-04-16 18:31:55 +0100770 DCHECK(interval->CoversSlow(defined_by->GetLifetimePosition()));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000771 size_t position = defined_by->GetLifetimePosition() + 1;
772 FreeIfNotCoverAt(interval, position, free_until);
773 }
774 }
775 }
776 }
777
Mingyao Yang296bd602014-10-06 16:47:28 -0700778 // For each inactive interval, set its register to be free until
779 // the next intersection with `current`.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100780 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700781 // Temp/Slow-path-safepoint interval has no holes.
782 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
783 if (!current->IsSplit() && !inactive->IsFixed()) {
784 // Neither current nor inactive are fixed.
785 // Thanks to SSA, a non-split interval starting in a hole of an
786 // inactive interval should never intersect with that inactive interval.
787 // Only if it's not fixed though, because fixed intervals don't come from SSA.
788 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
789 continue;
790 }
791
792 DCHECK(inactive->HasRegister());
793 if (free_until[inactive->GetRegister()] == 0) {
794 // Already used by some active interval. No need to intersect.
795 continue;
796 }
797 size_t next_intersection = inactive->FirstIntersectionWith(current);
798 if (next_intersection != kNoLifetime) {
799 free_until[inactive->GetRegister()] =
800 std::min(free_until[inactive->GetRegister()], next_intersection);
801 }
802 }
803
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000804 int reg = kNoRegister;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100805 if (current->HasRegister()) {
806 // Some instructions have a fixed register output.
807 reg = current->GetRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000808 if (free_until[reg] == 0) {
809 DCHECK(current->IsHighInterval());
810 // AllocateBlockedReg will spill the holder of the register.
811 return false;
812 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100813 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000814 DCHECK(!current->IsHighInterval());
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100815 int hint = current->FindFirstRegisterHint(free_until, liveness_);
Nicolas Geoffrayf2975812015-08-07 18:13:03 -0700816 if ((hint != kNoRegister)
817 // For simplicity, if the hint we are getting for a pair cannot be used,
818 // we are just going to allocate a new pair.
819 && !(current->IsLowInterval() && IsBlocked(GetHighForLowRegister(hint)))) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100820 DCHECK(!IsBlocked(hint));
821 reg = hint;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000822 } else if (current->IsLowInterval()) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000823 reg = FindAvailableRegisterPair(free_until, current->GetStart());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100824 } else {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100825 reg = FindAvailableRegister(free_until, current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100826 }
827 }
828
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000829 DCHECK_NE(reg, kNoRegister);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100830 // If we could not find a register, we need to spill.
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000831 if (free_until[reg] == 0) {
832 return false;
833 }
834
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000835 if (current->IsLowInterval()) {
836 // If the high register of this interval is not available, we need to spill.
837 int high_reg = current->GetHighInterval()->GetRegister();
838 if (high_reg == kNoRegister) {
839 high_reg = GetHighForLowRegister(reg);
840 }
841 if (free_until[high_reg] == 0) {
842 return false;
843 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100844 }
845
846 current->SetRegister(reg);
847 if (!current->IsDeadAt(free_until[reg])) {
848 // If the register is only available for a subset of live ranges
Nicolas Geoffray82726882015-06-01 13:51:57 +0100849 // covered by `current`, split `current` before the position where
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100850 // the register is not available anymore.
Nicolas Geoffray82726882015-06-01 13:51:57 +0100851 LiveInterval* split = SplitBetween(current, current->GetStart(), free_until[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100852 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100853 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100854 }
855 return true;
856}
857
858bool RegisterAllocator::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100859 return processing_core_registers_
860 ? blocked_core_registers_[reg]
861 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100862}
863
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000864int RegisterAllocator::FindAvailableRegisterPair(size_t* next_use, size_t starting_at) const {
865 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000866 // Pick the register pair that is used the last.
867 for (size_t i = 0; i < number_of_registers_; ++i) {
868 if (IsBlocked(i)) continue;
869 if (!IsLowRegister(i)) continue;
870 int high_register = GetHighForLowRegister(i);
871 if (IsBlocked(high_register)) continue;
872 int existing_high_register = GetHighForLowRegister(reg);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000873 if ((reg == kNoRegister) || (next_use[i] >= next_use[reg]
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000874 && next_use[high_register] >= next_use[existing_high_register])) {
875 reg = i;
876 if (next_use[i] == kMaxLifetimePosition
877 && next_use[high_register] == kMaxLifetimePosition) {
878 break;
879 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000880 } else if (next_use[reg] <= starting_at || next_use[existing_high_register] <= starting_at) {
881 // If one of the current register is known to be unavailable, just unconditionally
882 // try a new one.
883 reg = i;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000884 }
885 }
886 return reg;
887}
888
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100889bool RegisterAllocator::IsCallerSaveRegister(int reg) const {
890 return processing_core_registers_
891 ? !codegen_->IsCoreCalleeSaveRegister(reg)
892 : !codegen_->IsFloatingPointCalleeSaveRegister(reg);
893}
894
895int RegisterAllocator::FindAvailableRegister(size_t* next_use, LiveInterval* current) const {
896 // We special case intervals that do not span a safepoint to try to find a caller-save
897 // register if one is available. We iterate from 0 to the number of registers,
898 // so if there are caller-save registers available at the end, we continue the iteration.
899 bool prefers_caller_save = !current->HasWillCallSafepoint();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000900 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000901 for (size_t i = 0; i < number_of_registers_; ++i) {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100902 if (IsBlocked(i)) {
903 // Register cannot be used. Continue.
904 continue;
905 }
906
907 // Best case: we found a register fully available.
908 if (next_use[i] == kMaxLifetimePosition) {
909 if (prefers_caller_save && !IsCallerSaveRegister(i)) {
910 // We can get shorter encodings on some platforms by using
911 // small register numbers. So only update the candidate if the previous
912 // one was not available for the whole method.
913 if (reg == kNoRegister || next_use[reg] != kMaxLifetimePosition) {
914 reg = i;
915 }
916 // Continue the iteration in the hope of finding a caller save register.
917 continue;
918 } else {
919 reg = i;
920 // We know the register is good enough. Return it.
921 break;
922 }
923 }
924
925 // If we had no register before, take this one as a reference.
926 if (reg == kNoRegister) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000927 reg = i;
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100928 continue;
929 }
930
931 // Pick the register that is used the last.
932 if (next_use[i] > next_use[reg]) {
933 reg = i;
934 continue;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000935 }
936 }
937 return reg;
938}
939
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100940// Remove interval and its other half if any. Return iterator to the following element.
941static ArenaVector<LiveInterval*>::iterator RemoveIntervalAndPotentialOtherHalf(
942 ArenaVector<LiveInterval*>* intervals, ArenaVector<LiveInterval*>::iterator pos) {
943 DCHECK(intervals->begin() <= pos && pos < intervals->end());
944 LiveInterval* interval = *pos;
945 if (interval->IsLowInterval()) {
946 DCHECK(pos + 1 < intervals->end());
947 DCHECK_EQ(*(pos + 1), interval->GetHighInterval());
948 return intervals->erase(pos, pos + 2);
949 } else if (interval->IsHighInterval()) {
950 DCHECK(intervals->begin() < pos);
951 DCHECK_EQ(*(pos - 1), interval->GetLowInterval());
952 return intervals->erase(pos - 1, pos + 1);
953 } else {
954 return intervals->erase(pos);
955 }
956}
957
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000958bool RegisterAllocator::TrySplitNonPairOrUnalignedPairIntervalAt(size_t position,
959 size_t first_register_use,
960 size_t* next_use) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100961 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
962 LiveInterval* active = *it;
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000963 DCHECK(active->HasRegister());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000964 if (active->IsFixed()) continue;
965 if (active->IsHighInterval()) continue;
966 if (first_register_use > next_use[active->GetRegister()]) continue;
967
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100968 // Split the first interval found that is either:
969 // 1) A non-pair interval.
970 // 2) A pair interval whose high is not low + 1.
971 // 3) A pair interval whose low is not even.
972 if (!active->IsLowInterval() ||
973 IsLowOfUnalignedPairInterval(active) ||
974 !IsLowRegister(active->GetRegister())) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000975 LiveInterval* split = Split(active, position);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000976 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100977 handled_.push_back(active);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000978 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100979 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000980 AddSorted(unhandled_, split);
981 return true;
982 }
983 }
984 return false;
985}
986
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100987// Find the register that is used the last, and spill the interval
988// that holds it. If the first use of `current` is after that register
989// we spill `current` instead.
990bool RegisterAllocator::AllocateBlockedReg(LiveInterval* current) {
991 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -0700992 if (current->HasRegister()) {
993 DCHECK(current->IsHighInterval());
994 // The low interval has allocated the register for the high interval. In
995 // case the low interval had to split both intervals, we may end up in a
996 // situation where the high interval does not have a register use anymore.
997 // We must still proceed in order to split currently active and inactive
998 // uses of the high interval's register, and put the high interval in the
999 // active set.
1000 DCHECK(first_register_use != kNoLifetime || (current->GetNextSibling() != nullptr));
1001 } else if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001002 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001003 return false;
1004 }
1005
1006 // First set all registers as not being used.
1007 size_t* next_use = registers_array_;
1008 for (size_t i = 0; i < number_of_registers_; ++i) {
1009 next_use[i] = kMaxLifetimePosition;
1010 }
1011
1012 // For each active interval, find the next use of its register after the
1013 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001014 for (LiveInterval* active : active_) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001015 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001016 if (active->IsFixed()) {
1017 next_use[active->GetRegister()] = current->GetStart();
1018 } else {
Nicolas Geoffray119a8852016-02-06 17:01:15 +00001019 size_t use = active->FirstRegisterUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001020 if (use != kNoLifetime) {
1021 next_use[active->GetRegister()] = use;
1022 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001023 }
1024 }
1025
1026 // For each inactive interval, find the next use of its register after the
1027 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001028 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001029 // Temp/Slow-path-safepoint interval has no holes.
1030 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
1031 if (!current->IsSplit() && !inactive->IsFixed()) {
1032 // Neither current nor inactive are fixed.
1033 // Thanks to SSA, a non-split interval starting in a hole of an
1034 // inactive interval should never intersect with that inactive interval.
1035 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1036 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
1037 continue;
1038 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001039 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001040 size_t next_intersection = inactive->FirstIntersectionWith(current);
1041 if (next_intersection != kNoLifetime) {
1042 if (inactive->IsFixed()) {
1043 next_use[inactive->GetRegister()] =
1044 std::min(next_intersection, next_use[inactive->GetRegister()]);
1045 } else {
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001046 size_t use = inactive->FirstUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001047 if (use != kNoLifetime) {
1048 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
1049 }
1050 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001051 }
1052 }
1053
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001054 int reg = kNoRegister;
1055 bool should_spill = false;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001056 if (current->HasRegister()) {
1057 DCHECK(current->IsHighInterval());
1058 reg = current->GetRegister();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001059 // When allocating the low part, we made sure the high register was available.
Nicolas Geoffray119a8852016-02-06 17:01:15 +00001060 DCHECK_LT(first_register_use, next_use[reg]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001061 } else if (current->IsLowInterval()) {
Nicolas Geoffray119a8852016-02-06 17:01:15 +00001062 reg = FindAvailableRegisterPair(next_use, first_register_use);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001063 // We should spill if both registers are not available.
Nicolas Geoffray119a8852016-02-06 17:01:15 +00001064 should_spill = (first_register_use >= next_use[reg])
1065 || (first_register_use >= next_use[GetHighForLowRegister(reg)]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001066 } else {
1067 DCHECK(!current->IsHighInterval());
Nicolas Geoffray8826f672015-04-17 09:15:11 +01001068 reg = FindAvailableRegister(next_use, current);
Nicolas Geoffray119a8852016-02-06 17:01:15 +00001069 should_spill = (first_register_use >= next_use[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001070 }
1071
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001072 DCHECK_NE(reg, kNoRegister);
1073 if (should_spill) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001074 DCHECK(!current->IsHighInterval());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001075 bool is_allocation_at_use_site = (current->GetStart() >= (first_register_use - 1));
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001076 if (is_allocation_at_use_site) {
1077 if (!current->IsLowInterval()) {
1078 DumpInterval(std::cerr, current);
1079 DumpAllIntervals(std::cerr);
1080 // This situation has the potential to infinite loop, so we make it a non-debug CHECK.
1081 HInstruction* at = liveness_.GetInstructionFromPosition(first_register_use / 2);
1082 CHECK(false) << "There is not enough registers available for "
1083 << current->GetParent()->GetDefinedBy()->DebugName() << " "
1084 << current->GetParent()->GetDefinedBy()->GetId()
1085 << " at " << first_register_use - 1 << " "
1086 << (at == nullptr ? "" : at->DebugName());
1087 }
1088
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001089 // If we're allocating a register for `current` because the instruction at
1090 // that position requires it, but we think we should spill, then there are
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001091 // non-pair intervals or unaligned pair intervals blocking the allocation.
1092 // We split the first interval found, and put ourselves first in the
1093 // `unhandled_` list.
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001094 bool success = TrySplitNonPairOrUnalignedPairIntervalAt(current->GetStart(),
1095 first_register_use,
1096 next_use);
1097 DCHECK(success);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001098 LiveInterval* existing = unhandled_->back();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001099 DCHECK(existing->IsHighInterval());
1100 DCHECK_EQ(existing->GetLowInterval(), current);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001101 unhandled_->push_back(current);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001102 } else {
1103 // If the first use of that instruction is after the last use of the found
1104 // register, we split this interval just before its first register use.
1105 AllocateSpillSlotFor(current);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001106 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001107 DCHECK(current != split);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001108 AddSorted(unhandled_, split);
1109 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001110 return false;
1111 } else {
1112 // Use this register and spill the active and inactives interval that
1113 // have that register.
1114 current->SetRegister(reg);
1115
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001116 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
1117 LiveInterval* active = *it;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001118 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001119 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001120 LiveInterval* split = Split(active, current->GetStart());
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001121 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001122 handled_.push_back(active);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001123 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001124 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001125 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001126 break;
1127 }
1128 }
1129
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001130 // NOTE: Retrieve end() on each iteration because we're removing elements in the loop body.
1131 for (auto it = inactive_.begin(); it != inactive_.end(); ) {
1132 LiveInterval* inactive = *it;
1133 bool erased = false;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001134 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001135 if (!current->IsSplit() && !inactive->IsFixed()) {
1136 // Neither current nor inactive are fixed.
1137 // Thanks to SSA, a non-split interval starting in a hole of an
1138 // inactive interval should never intersect with that inactive interval.
1139 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1140 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001141 } else {
1142 size_t next_intersection = inactive->FirstIntersectionWith(current);
1143 if (next_intersection != kNoLifetime) {
1144 if (inactive->IsFixed()) {
1145 LiveInterval* split = Split(current, next_intersection);
1146 DCHECK_NE(split, current);
1147 AddSorted(unhandled_, split);
1148 } else {
1149 // Split at the start of `current`, which will lead to splitting
1150 // at the end of the lifetime hole of `inactive`.
1151 LiveInterval* split = Split(inactive, current->GetStart());
1152 // If it's inactive, it must start before the current interval.
1153 DCHECK_NE(split, inactive);
1154 it = RemoveIntervalAndPotentialOtherHalf(&inactive_, it);
1155 erased = true;
1156 handled_.push_back(inactive);
1157 AddSorted(unhandled_, split);
Nicolas Geoffray5b168de2015-03-27 10:27:22 +00001158 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001159 }
1160 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001161 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001162 // If we have erased the element, `it` already points to the next element.
1163 // Otherwise we need to move to the next element.
1164 if (!erased) {
1165 ++it;
1166 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001167 }
1168
1169 return true;
1170 }
1171}
1172
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001173void RegisterAllocator::AddSorted(ArenaVector<LiveInterval*>* array, LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +01001174 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001175 size_t insert_at = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001176 for (size_t i = array->size(); i > 0; --i) {
1177 LiveInterval* current = (*array)[i - 1u];
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001178 // High intervals must be processed right after their low equivalent.
1179 if (current->StartsAfter(interval) && !current->IsHighInterval()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001180 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001181 break;
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001182 } else if ((current->GetStart() == interval->GetStart()) && current->IsSlowPathSafepoint()) {
1183 // Ensure the slow path interval is the last to be processed at its location: we want the
1184 // interval to know all live registers at this location.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001185 DCHECK(i == 1 || (*array)[i - 2u]->StartsAfter(current));
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001186 insert_at = i;
1187 break;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001188 }
1189 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001190
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001191 // Insert the high interval before the low, to ensure the low is processed before.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001192 auto insert_pos = array->begin() + insert_at;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001193 if (interval->HasHighInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001194 array->insert(insert_pos, { interval->GetHighInterval(), interval });
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001195 } else if (interval->HasLowInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001196 array->insert(insert_pos, { interval, interval->GetLowInterval() });
1197 } else {
1198 array->insert(insert_pos, interval);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001199 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001200}
1201
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001202LiveInterval* RegisterAllocator::SplitBetween(LiveInterval* interval, size_t from, size_t to) {
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001203 HBasicBlock* block_from = liveness_.GetBlockFromPosition(from / 2);
1204 HBasicBlock* block_to = liveness_.GetBlockFromPosition(to / 2);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001205 DCHECK(block_from != nullptr);
1206 DCHECK(block_to != nullptr);
1207
1208 // Both locations are in the same block. We split at the given location.
1209 if (block_from == block_to) {
1210 return Split(interval, to);
1211 }
1212
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001213 /*
1214 * Non-linear control flow will force moves at every branch instruction to the new location.
1215 * To avoid having all branches doing the moves, we find the next non-linear position and
1216 * split the interval at this position. Take the following example (block number is the linear
1217 * order position):
1218 *
1219 * B1
1220 * / \
1221 * B2 B3
1222 * \ /
1223 * B4
1224 *
1225 * B2 needs to split an interval, whose next use is in B4. If we were to split at the
1226 * beginning of B4, B3 would need to do a move between B3 and B4 to ensure the interval
1227 * is now in the correct location. It makes performance worst if the interval is spilled
1228 * and both B2 and B3 need to reload it before entering B4.
1229 *
1230 * By splitting at B3, we give a chance to the register allocator to allocate the
1231 * interval to the same register as in B1, and therefore avoid doing any
1232 * moves in B3.
1233 */
1234 if (block_from->GetDominator() != nullptr) {
Vladimir Marko60584552015-09-03 13:35:12 +00001235 for (HBasicBlock* dominated : block_from->GetDominator()->GetDominatedBlocks()) {
1236 size_t position = dominated->GetLifetimeStart();
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001237 if ((position > from) && (block_to->GetLifetimeStart() > position)) {
1238 // Even if we found a better block, we continue iterating in case
1239 // a dominated block is closer.
1240 // Note that dominated blocks are not sorted in liveness order.
Vladimir Marko60584552015-09-03 13:35:12 +00001241 block_to = dominated;
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001242 DCHECK_NE(block_to, block_from);
1243 }
1244 }
1245 }
1246
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001247 // If `to` is in a loop, find the outermost loop header which does not contain `from`.
1248 for (HLoopInformationOutwardIterator it(*block_to); !it.Done(); it.Advance()) {
1249 HBasicBlock* header = it.Current()->GetHeader();
1250 if (block_from->GetLifetimeStart() >= header->GetLifetimeStart()) {
1251 break;
1252 }
1253 block_to = header;
1254 }
1255
1256 // Split at the start of the found block, to piggy back on existing moves
1257 // due to resolution if non-linear control flow (see `ConnectSplitSiblings`).
1258 return Split(interval, block_to->GetLifetimeStart());
1259}
1260
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001261LiveInterval* RegisterAllocator::Split(LiveInterval* interval, size_t position) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001262 DCHECK_GE(position, interval->GetStart());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001263 DCHECK(!interval->IsDeadAt(position));
1264 if (position == interval->GetStart()) {
1265 // Spill slot will be allocated when handling `interval` again.
1266 interval->ClearRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001267 if (interval->HasHighInterval()) {
1268 interval->GetHighInterval()->ClearRegister();
1269 } else if (interval->HasLowInterval()) {
1270 interval->GetLowInterval()->ClearRegister();
1271 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001272 return interval;
1273 } else {
1274 LiveInterval* new_interval = interval->SplitAt(position);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001275 if (interval->HasHighInterval()) {
1276 LiveInterval* high = interval->GetHighInterval()->SplitAt(position);
1277 new_interval->SetHighInterval(high);
1278 high->SetLowInterval(new_interval);
1279 } else if (interval->HasLowInterval()) {
1280 LiveInterval* low = interval->GetLowInterval()->SplitAt(position);
1281 new_interval->SetLowInterval(low);
1282 low->SetHighInterval(new_interval);
1283 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001284 return new_interval;
1285 }
1286}
1287
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001288void RegisterAllocator::AllocateSpillSlotFor(LiveInterval* interval) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001289 if (interval->IsHighInterval()) {
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001290 // The low interval already took care of allocating the spill slot.
1291 DCHECK(!interval->GetLowInterval()->HasRegister());
1292 DCHECK(interval->GetLowInterval()->GetParent()->HasSpillSlot());
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001293 return;
1294 }
1295
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001296 LiveInterval* parent = interval->GetParent();
1297
1298 // An instruction gets a spill slot for its entire lifetime. If the parent
1299 // of this interval already has a spill slot, there is nothing to do.
1300 if (parent->HasSpillSlot()) {
1301 return;
1302 }
1303
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001304 HInstruction* defined_by = parent->GetDefinedBy();
David Brazdil77a48ae2015-09-15 12:34:04 +00001305 DCHECK(!defined_by->IsPhi() || !defined_by->AsPhi()->IsCatchPhi());
1306
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001307 if (defined_by->IsParameterValue()) {
1308 // Parameters have their own stack slot.
1309 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
1310 return;
1311 }
1312
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001313 if (defined_by->IsCurrentMethod()) {
1314 parent->SetSpillSlot(0);
1315 return;
1316 }
1317
Nicolas Geoffray96f89a22014-07-11 10:57:49 +01001318 if (defined_by->IsConstant()) {
1319 // Constants don't need a spill slot.
1320 return;
1321 }
1322
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001323 ArenaVector<size_t>* spill_slots = nullptr;
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001324 switch (interval->GetType()) {
1325 case Primitive::kPrimDouble:
1326 spill_slots = &double_spill_slots_;
1327 break;
1328 case Primitive::kPrimLong:
1329 spill_slots = &long_spill_slots_;
1330 break;
1331 case Primitive::kPrimFloat:
1332 spill_slots = &float_spill_slots_;
1333 break;
1334 case Primitive::kPrimNot:
1335 case Primitive::kPrimInt:
1336 case Primitive::kPrimChar:
1337 case Primitive::kPrimByte:
1338 case Primitive::kPrimBoolean:
1339 case Primitive::kPrimShort:
1340 spill_slots = &int_spill_slots_;
1341 break;
1342 case Primitive::kPrimVoid:
1343 LOG(FATAL) << "Unexpected type for interval " << interval->GetType();
1344 }
1345
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001346 // Find an available spill slot.
1347 size_t slot = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001348 for (size_t e = spill_slots->size(); slot < e; ++slot) {
1349 if ((*spill_slots)[slot] <= parent->GetStart()
1350 && (slot == (e - 1) || (*spill_slots)[slot + 1] <= parent->GetStart())) {
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001351 break;
1352 }
1353 }
1354
David Brazdil77a48ae2015-09-15 12:34:04 +00001355 size_t end = interval->GetLastSibling()->GetEnd();
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001356 if (parent->NeedsTwoSpillSlots()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001357 if (slot + 2u > spill_slots->size()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001358 // We need a new spill slot.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001359 spill_slots->resize(slot + 2u, end);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001360 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001361 (*spill_slots)[slot] = end;
1362 (*spill_slots)[slot + 1] = end;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001363 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001364 if (slot == spill_slots->size()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001365 // We need a new spill slot.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001366 spill_slots->push_back(end);
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001367 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001368 (*spill_slots)[slot] = end;
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001369 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001370 }
1371
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001372 // Note that the exact spill slot location will be computed when we resolve,
1373 // that is when we know the number of spill slots for each type.
1374 parent->SetSpillSlot(slot);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001375}
1376
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001377static bool IsValidDestination(Location destination) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001378 return destination.IsRegister()
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001379 || destination.IsRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001380 || destination.IsFpuRegister()
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001381 || destination.IsFpuRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001382 || destination.IsStackSlot()
1383 || destination.IsDoubleStackSlot();
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001384}
1385
David Brazdil77a48ae2015-09-15 12:34:04 +00001386void RegisterAllocator::AllocateSpillSlotForCatchPhi(HPhi* phi) {
1387 LiveInterval* interval = phi->GetLiveInterval();
1388
1389 HInstruction* previous_phi = phi->GetPrevious();
1390 DCHECK(previous_phi == nullptr ||
1391 previous_phi->AsPhi()->GetRegNumber() <= phi->GetRegNumber())
1392 << "Phis expected to be sorted by vreg number, so that equivalent phis are adjacent.";
1393
1394 if (phi->IsVRegEquivalentOf(previous_phi)) {
1395 // This is an equivalent of the previous phi. We need to assign the same
1396 // catch phi slot.
1397 DCHECK(previous_phi->GetLiveInterval()->HasSpillSlot());
1398 interval->SetSpillSlot(previous_phi->GetLiveInterval()->GetSpillSlot());
1399 } else {
1400 // Allocate a new spill slot for this catch phi.
1401 // TODO: Reuse spill slots when intervals of phis from different catch
1402 // blocks do not overlap.
1403 interval->SetSpillSlot(catch_phi_spill_slots_);
1404 catch_phi_spill_slots_ += interval->NeedsTwoSpillSlots() ? 2 : 1;
1405 }
1406}
1407
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001408void RegisterAllocator::AddMove(HParallelMove* move,
1409 Location source,
1410 Location destination,
1411 HInstruction* instruction,
1412 Primitive::Type type) const {
1413 if (type == Primitive::kPrimLong
1414 && codegen_->ShouldSplitLongMoves()
1415 // The parallel move resolver knows how to deal with long constants.
1416 && !source.IsConstant()) {
Nicolas Geoffray90218252015-04-15 11:56:51 +01001417 move->AddMove(source.ToLow(), destination.ToLow(), Primitive::kPrimInt, instruction);
1418 move->AddMove(source.ToHigh(), destination.ToHigh(), Primitive::kPrimInt, nullptr);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001419 } else {
Nicolas Geoffray90218252015-04-15 11:56:51 +01001420 move->AddMove(source, destination, type, instruction);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001421 }
1422}
1423
1424void RegisterAllocator::AddInputMoveFor(HInstruction* input,
1425 HInstruction* user,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001426 Location source,
1427 Location destination) const {
1428 if (source.Equals(destination)) return;
1429
Roland Levillain476df552014-10-09 17:51:36 +01001430 DCHECK(!user->IsPhi());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001431
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001432 HInstruction* previous = user->GetPrevious();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001433 HParallelMove* move = nullptr;
1434 if (previous == nullptr
Roland Levillain476df552014-10-09 17:51:36 +01001435 || !previous->IsParallelMove()
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001436 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001437 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001438 move->SetLifetimePosition(user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001439 user->GetBlock()->InsertInstructionBefore(move, user);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001440 } else {
1441 move = previous->AsParallelMove();
1442 }
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001443 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001444 AddMove(move, source, destination, nullptr, input->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001445}
1446
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001447static bool IsInstructionStart(size_t position) {
1448 return (position & 1) == 0;
1449}
1450
1451static bool IsInstructionEnd(size_t position) {
1452 return (position & 1) == 1;
1453}
1454
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001455void RegisterAllocator::InsertParallelMoveAt(size_t position,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001456 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001457 Location source,
1458 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001459 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001460 if (source.Equals(destination)) return;
1461
1462 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001463 HParallelMove* move;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001464 if (at == nullptr) {
1465 if (IsInstructionStart(position)) {
1466 // Block boundary, don't do anything the connection of split siblings will handle it.
1467 return;
1468 } else {
1469 // Move must happen before the first instruction of the block.
1470 at = liveness_.GetInstructionFromPosition((position + 1) / 2);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001471 // Note that parallel moves may have already been inserted, so we explicitly
1472 // ask for the first instruction of the block: `GetInstructionFromPosition` does
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001473 // not contain the `HParallelMove` instructions.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001474 at = at->GetBlock()->GetFirstInstruction();
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001475
1476 if (at->GetLifetimePosition() < position) {
1477 // We may insert moves for split siblings and phi spills at the beginning of the block.
1478 // Since this is a different lifetime position, we need to go to the next instruction.
1479 DCHECK(at->IsParallelMove());
1480 at = at->GetNext();
1481 }
1482
Nicolas Geoffray59768572014-12-01 09:50:04 +00001483 if (at->GetLifetimePosition() != position) {
1484 DCHECK_GT(at->GetLifetimePosition(), position);
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001485 move = new (allocator_) HParallelMove(allocator_);
1486 move->SetLifetimePosition(position);
1487 at->GetBlock()->InsertInstructionBefore(move, at);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001488 } else {
1489 DCHECK(at->IsParallelMove());
1490 move = at->AsParallelMove();
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001491 }
1492 }
1493 } else if (IsInstructionEnd(position)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001494 // Move must happen after the instruction.
1495 DCHECK(!at->IsControlFlow());
1496 move = at->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001497 // This is a parallel move for connecting siblings in a same block. We need to
1498 // differentiate it with moves for connecting blocks, and input moves.
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001499 if (move == nullptr || move->GetLifetimePosition() > position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001500 move = new (allocator_) HParallelMove(allocator_);
1501 move->SetLifetimePosition(position);
1502 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
1503 }
1504 } else {
1505 // Move must happen before the instruction.
1506 HInstruction* previous = at->GetPrevious();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001507 if (previous == nullptr
1508 || !previous->IsParallelMove()
1509 || previous->GetLifetimePosition() != position) {
1510 // If the previous is a parallel move, then its position must be lower
1511 // than the given `position`: it was added just after the non-parallel
1512 // move instruction that precedes `instruction`.
1513 DCHECK(previous == nullptr
1514 || !previous->IsParallelMove()
1515 || previous->GetLifetimePosition() < position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001516 move = new (allocator_) HParallelMove(allocator_);
1517 move->SetLifetimePosition(position);
1518 at->GetBlock()->InsertInstructionBefore(move, at);
1519 } else {
1520 move = previous->AsParallelMove();
1521 }
1522 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001523 DCHECK_EQ(move->GetLifetimePosition(), position);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001524 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001525}
1526
1527void RegisterAllocator::InsertParallelMoveAtExitOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001528 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001529 Location source,
1530 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001531 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001532 if (source.Equals(destination)) return;
1533
David Brazdild26a4112015-11-10 11:07:31 +00001534 DCHECK_EQ(block->GetNormalSuccessors().size(), 1u);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001535 HInstruction* last = block->GetLastInstruction();
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001536 // We insert moves at exit for phi predecessors and connecting blocks.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001537 // A block ending with an if or a packed switch cannot branch to a block
1538 // with phis because we do not allow critical edges. It can also not connect
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001539 // a split interval between two blocks: the move has to happen in the successor.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001540 DCHECK(!last->IsIf() && !last->IsPackedSwitch());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001541 HInstruction* previous = last->GetPrevious();
1542 HParallelMove* move;
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001543 // This is a parallel move for connecting blocks. We need to differentiate
1544 // it with moves for connecting siblings in a same block, and output moves.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001545 size_t position = last->GetLifetimePosition();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001546 if (previous == nullptr || !previous->IsParallelMove()
Nicolas Geoffray59768572014-12-01 09:50:04 +00001547 || previous->AsParallelMove()->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001548 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001549 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001550 block->InsertInstructionBefore(move, last);
1551 } else {
1552 move = previous->AsParallelMove();
1553 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001554 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001555}
1556
1557void RegisterAllocator::InsertParallelMoveAtEntryOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001558 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001559 Location source,
1560 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001561 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001562 if (source.Equals(destination)) return;
1563
1564 HInstruction* first = block->GetFirstInstruction();
1565 HParallelMove* move = first->AsParallelMove();
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001566 size_t position = block->GetLifetimeStart();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001567 // This is a parallel move for connecting blocks. We need to differentiate
1568 // it with moves for connecting siblings in a same block, and input moves.
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001569 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001570 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001571 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001572 block->InsertInstructionBefore(move, first);
1573 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001574 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001575}
1576
1577void RegisterAllocator::InsertMoveAfter(HInstruction* instruction,
1578 Location source,
1579 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001580 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001581 if (source.Equals(destination)) return;
1582
Roland Levillain476df552014-10-09 17:51:36 +01001583 if (instruction->IsPhi()) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001584 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001585 return;
1586 }
1587
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001588 size_t position = instruction->GetLifetimePosition() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001589 HParallelMove* move = instruction->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001590 // This is a parallel move for moving the output of an instruction. We need
1591 // to differentiate with input moves, moves for connecting siblings in a
1592 // and moves for connecting blocks.
1593 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001594 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001595 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001596 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
1597 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001598 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001599}
1600
1601void RegisterAllocator::ConnectSiblings(LiveInterval* interval) {
1602 LiveInterval* current = interval;
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001603 if (current->HasSpillSlot()
1604 && current->HasRegister()
1605 // Currently, we spill unconditionnally the current method in the code generators.
1606 && !interval->GetDefinedBy()->IsCurrentMethod()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001607 // We spill eagerly, so move must be at definition.
1608 InsertMoveAfter(interval->GetDefinedBy(),
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001609 interval->ToLocation(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001610 interval->NeedsTwoSpillSlots()
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001611 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
1612 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001613 }
1614 UsePosition* use = current->GetFirstUse();
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001615 UsePosition* env_use = current->GetFirstEnvironmentUse();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001616
1617 // Walk over all siblings, updating locations of use positions, and
1618 // connecting them when they are adjacent.
1619 do {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001620 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001621
1622 // Walk over all uses covered by this interval, and update the location
1623 // information.
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001624
1625 LiveRange* range = current->GetFirstRange();
1626 while (range != nullptr) {
Nicolas Geoffray57902602015-04-21 14:28:41 +01001627 while (use != nullptr && use->GetPosition() < range->GetStart()) {
1628 DCHECK(use->IsSynthesized());
1629 use = use->GetNext();
1630 }
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001631 while (use != nullptr && use->GetPosition() <= range->GetEnd()) {
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001632 DCHECK(!use->GetIsEnvironment());
David Brazdil3fc992f2015-04-16 18:31:55 +01001633 DCHECK(current->CoversSlow(use->GetPosition()) || (use->GetPosition() == range->GetEnd()));
Nicolas Geoffray57902602015-04-21 14:28:41 +01001634 if (!use->IsSynthesized()) {
1635 LocationSummary* locations = use->GetUser()->GetLocations();
1636 Location expected_location = locations->InAt(use->GetInputIndex());
1637 // The expected (actual) location may be invalid in case the input is unused. Currently
1638 // this only happens for intrinsics.
1639 if (expected_location.IsValid()) {
1640 if (expected_location.IsUnallocated()) {
1641 locations->SetInAt(use->GetInputIndex(), source);
1642 } else if (!expected_location.IsConstant()) {
1643 AddInputMoveFor(interval->GetDefinedBy(), use->GetUser(), source, expected_location);
1644 }
1645 } else {
1646 DCHECK(use->GetUser()->IsInvoke());
1647 DCHECK(use->GetUser()->AsInvoke()->GetIntrinsic() != Intrinsics::kNone);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001648 }
1649 }
1650 use = use->GetNext();
1651 }
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001652
1653 // Walk over the environment uses, and update their locations.
1654 while (env_use != nullptr && env_use->GetPosition() < range->GetStart()) {
1655 env_use = env_use->GetNext();
1656 }
1657
1658 while (env_use != nullptr && env_use->GetPosition() <= range->GetEnd()) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001659 DCHECK(current->CoversSlow(env_use->GetPosition())
1660 || (env_use->GetPosition() == range->GetEnd()));
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001661 HEnvironment* environment = env_use->GetEnvironment();
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001662 environment->SetLocationAt(env_use->GetInputIndex(), source);
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001663 env_use = env_use->GetNext();
1664 }
1665
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001666 range = range->GetNext();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001667 }
1668
1669 // If the next interval starts just after this one, and has a register,
1670 // insert a move.
1671 LiveInterval* next_sibling = current->GetNextSibling();
1672 if (next_sibling != nullptr
1673 && next_sibling->HasRegister()
1674 && current->GetEnd() == next_sibling->GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001675 Location destination = next_sibling->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001676 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001677 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001678
Nicolas Geoffray43af7282015-04-16 13:01:01 +01001679 for (SafepointPosition* safepoint_position = current->GetFirstSafepoint();
1680 safepoint_position != nullptr;
1681 safepoint_position = safepoint_position->GetNext()) {
David Brazdil3fc992f2015-04-16 18:31:55 +01001682 DCHECK(current->CoversSlow(safepoint_position->GetPosition()));
Nicolas Geoffray39468442014-09-02 15:17:15 +01001683
Nicolas Geoffray5588e582015-04-14 14:10:59 +01001684 LocationSummary* locations = safepoint_position->GetLocations();
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001685 if ((current->GetType() == Primitive::kPrimNot) && current->GetParent()->HasSpillSlot()) {
Nicolas Geoffray1af564e2016-01-13 12:09:39 +00001686 DCHECK(interval->GetDefinedBy()->IsActualObject())
1687 << interval->GetDefinedBy()->DebugName()
1688 << "@" << safepoint_position->GetInstruction()->DebugName();
Nicolas Geoffray39468442014-09-02 15:17:15 +01001689 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
1690 }
1691
1692 switch (source.GetKind()) {
1693 case Location::kRegister: {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001694 locations->AddLiveRegister(source);
Nicolas Geoffray98893962015-01-21 12:32:32 +00001695 if (kIsDebugBuild && locations->OnlyCallsOnSlowPath()) {
1696 DCHECK_LE(locations->GetNumberOfLiveRegisters(),
1697 maximum_number_of_live_core_registers_ +
1698 maximum_number_of_live_fp_registers_);
1699 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001700 if (current->GetType() == Primitive::kPrimNot) {
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00001701 DCHECK(interval->GetDefinedBy()->IsActualObject())
Nicolas Geoffray1af564e2016-01-13 12:09:39 +00001702 << interval->GetDefinedBy()->DebugName()
1703 << "@" << safepoint_position->GetInstruction()->DebugName();
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001704 locations->SetRegisterBit(source.reg());
Nicolas Geoffray39468442014-09-02 15:17:15 +01001705 }
1706 break;
1707 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001708 case Location::kFpuRegister: {
1709 locations->AddLiveRegister(source);
1710 break;
1711 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001712
1713 case Location::kRegisterPair:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001714 case Location::kFpuRegisterPair: {
1715 locations->AddLiveRegister(source.ToLow());
1716 locations->AddLiveRegister(source.ToHigh());
1717 break;
1718 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001719 case Location::kStackSlot: // Fall-through
1720 case Location::kDoubleStackSlot: // Fall-through
1721 case Location::kConstant: {
1722 // Nothing to do.
1723 break;
1724 }
1725 default: {
1726 LOG(FATAL) << "Unexpected location for object";
1727 }
1728 }
1729 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001730 current = next_sibling;
1731 } while (current != nullptr);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001732
Nicolas Geoffray57902602015-04-21 14:28:41 +01001733 if (kIsDebugBuild) {
1734 // Following uses can only be synthesized uses.
1735 while (use != nullptr) {
1736 DCHECK(use->IsSynthesized());
1737 use = use->GetNext();
1738 }
1739 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001740}
1741
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001742static bool IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(
1743 HInstruction* instruction) {
1744 return instruction->GetBlock()->GetGraph()->HasIrreducibleLoops() &&
1745 (instruction->IsConstant() || instruction->IsCurrentMethod());
1746}
1747
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001748void RegisterAllocator::ConnectSplitSiblings(LiveInterval* interval,
1749 HBasicBlock* from,
1750 HBasicBlock* to) const {
1751 if (interval->GetNextSibling() == nullptr) {
1752 // Nothing to connect. The whole range was allocated to the same location.
1753 return;
1754 }
1755
David Brazdil241a4862015-04-16 17:59:03 +01001756 // Find the intervals that cover `from` and `to`.
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001757 size_t destination_position = to->GetLifetimeStart();
1758 size_t source_position = from->GetLifetimeEnd() - 1;
1759 LiveInterval* destination = interval->GetSiblingAt(destination_position);
1760 LiveInterval* source = interval->GetSiblingAt(source_position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001761
1762 if (destination == source) {
1763 // Interval was not split.
1764 return;
1765 }
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001766
1767 LiveInterval* parent = interval->GetParent();
1768 HInstruction* defined_by = parent->GetDefinedBy();
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001769 if (codegen_->GetGraph()->HasIrreducibleLoops() &&
1770 (destination == nullptr || !destination->CoversSlow(destination_position))) {
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001771 // Our live_in fixed point calculation has found that the instruction is live
1772 // in the `to` block because it will eventually enter an irreducible loop. Our
1773 // live interval computation however does not compute a fixed point, and
1774 // therefore will not have a location for that instruction for `to`.
1775 // Because the instruction is a constant or the ArtMethod, we don't need to
1776 // do anything: it will be materialized in the irreducible loop.
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +01001777 DCHECK(IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(defined_by))
1778 << defined_by->DebugName() << ":" << defined_by->GetId()
1779 << " " << from->GetBlockId() << " -> " << to->GetBlockId();
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001780 return;
1781 }
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +01001782
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001783 if (!destination->HasRegister()) {
1784 // Values are eagerly spilled. Spill slot already contains appropriate value.
1785 return;
1786 }
1787
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001788 Location location_source;
1789 // `GetSiblingAt` returns the interval whose start and end cover `position`,
1790 // but does not check whether the interval is inactive at that position.
1791 // The only situation where the interval is inactive at that position is in the
1792 // presence of irreducible loops for constants and ArtMethod.
1793 if (codegen_->GetGraph()->HasIrreducibleLoops() &&
1794 (source == nullptr || !source->CoversSlow(source_position))) {
1795 DCHECK(IsMaterializableEntryBlockInstructionOfGraphWithIrreducibleLoop(defined_by));
1796 if (defined_by->IsConstant()) {
1797 location_source = defined_by->GetLocations()->Out();
1798 } else {
1799 DCHECK(defined_by->IsCurrentMethod());
1800 location_source = parent->NeedsTwoSpillSlots()
1801 ? Location::DoubleStackSlot(parent->GetSpillSlot())
1802 : Location::StackSlot(parent->GetSpillSlot());
1803 }
1804 } else {
1805 DCHECK(source != nullptr);
1806 DCHECK(source->CoversSlow(source_position));
1807 DCHECK(destination->CoversSlow(destination_position));
1808 location_source = source->ToLocation();
1809 }
1810
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001811 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
1812 // we need to put the moves at the entry of `to`.
David Brazdild26a4112015-11-10 11:07:31 +00001813 if (from->GetNormalSuccessors().size() == 1) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001814 InsertParallelMoveAtExitOf(from,
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001815 defined_by,
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001816 location_source,
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001817 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001818 } else {
Vladimir Marko60584552015-09-03 13:35:12 +00001819 DCHECK_EQ(to->GetPredecessors().size(), 1u);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001820 InsertParallelMoveAtEntryOf(to,
Nicolas Geoffray04eb70f2016-01-21 18:22:23 +00001821 defined_by,
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001822 location_source,
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001823 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001824 }
1825}
1826
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001827void RegisterAllocator::Resolve() {
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001828 codegen_->InitializeCodeGeneration(GetNumberOfSpillSlots(),
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +00001829 maximum_number_of_live_core_registers_,
1830 maximum_number_of_live_fp_registers_,
1831 reserved_out_slots_,
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001832 codegen_->GetGraph()->GetLinearOrder());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001833
1834 // Adjust the Out Location of instructions.
1835 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
1836 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1837 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1838 LiveInterval* current = instruction->GetLiveInterval();
1839 LocationSummary* locations = instruction->GetLocations();
1840 Location location = locations->Out();
Roland Levillain476df552014-10-09 17:51:36 +01001841 if (instruction->IsParameterValue()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001842 // Now that we know the frame size, adjust the parameter's location.
1843 if (location.IsStackSlot()) {
1844 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1845 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001846 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001847 } else if (location.IsDoubleStackSlot()) {
1848 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1849 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001850 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001851 } else if (current->HasSpillSlot()) {
1852 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
1853 }
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001854 } else if (instruction->IsCurrentMethod()) {
1855 // The current method is always at offset 0.
1856 DCHECK(!current->HasSpillSlot() || (current->GetSpillSlot() == 0));
David Brazdil77a48ae2015-09-15 12:34:04 +00001857 } else if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
1858 DCHECK(current->HasSpillSlot());
1859 size_t slot = current->GetSpillSlot()
1860 + GetNumberOfSpillSlots()
1861 + reserved_out_slots_
1862 - catch_phi_spill_slots_;
1863 current->SetSpillSlot(slot * kVRegSize);
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001864 } else if (current->HasSpillSlot()) {
1865 // Adjust the stack slot, now that we know the number of them for each type.
1866 // The way this implementation lays out the stack is the following:
David Brazdil77a48ae2015-09-15 12:34:04 +00001867 // [parameter slots ]
1868 // [catch phi spill slots ]
1869 // [double spill slots ]
1870 // [long spill slots ]
1871 // [float spill slots ]
1872 // [int/ref values ]
1873 // [maximum out values ] (number of arguments for calls)
1874 // [art method ].
1875 size_t slot = current->GetSpillSlot();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001876 switch (current->GetType()) {
1877 case Primitive::kPrimDouble:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001878 slot += long_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001879 FALLTHROUGH_INTENDED;
1880 case Primitive::kPrimLong:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001881 slot += float_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001882 FALLTHROUGH_INTENDED;
1883 case Primitive::kPrimFloat:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001884 slot += int_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001885 FALLTHROUGH_INTENDED;
1886 case Primitive::kPrimNot:
1887 case Primitive::kPrimInt:
1888 case Primitive::kPrimChar:
1889 case Primitive::kPrimByte:
1890 case Primitive::kPrimBoolean:
1891 case Primitive::kPrimShort:
1892 slot += reserved_out_slots_;
1893 break;
1894 case Primitive::kPrimVoid:
1895 LOG(FATAL) << "Unexpected type for interval " << current->GetType();
1896 }
1897 current->SetSpillSlot(slot * kVRegSize);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001898 }
1899
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001900 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001901
1902 if (location.IsUnallocated()) {
1903 if (location.GetPolicy() == Location::kSameAsFirstInput) {
Calin Juravled0d48522014-11-04 16:40:20 +00001904 if (locations->InAt(0).IsUnallocated()) {
1905 locations->SetInAt(0, source);
1906 } else {
1907 DCHECK(locations->InAt(0).Equals(source));
1908 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001909 }
Nicolas Geoffray829280c2015-01-28 10:20:37 +00001910 locations->UpdateOut(source);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001911 } else {
1912 DCHECK(source.Equals(location));
1913 }
1914 }
1915
1916 // Connect siblings.
1917 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1918 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1919 ConnectSiblings(instruction->GetLiveInterval());
1920 }
1921
1922 // Resolve non-linear control flow across branches. Order does not matter.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001923 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001924 HBasicBlock* block = it.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001925 if (block->IsCatchBlock() ||
Nicolas Geoffrayad4ed082016-01-27 14:15:23 +00001926 (block->IsLoopHeader() && block->GetLoopInformation()->IsIrreducible())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001927 // Instructions live at the top of catch blocks or irreducible loop header
1928 // were forced to spill.
David Brazdil77a48ae2015-09-15 12:34:04 +00001929 if (kIsDebugBuild) {
1930 BitVector* live = liveness_.GetLiveInSet(*block);
1931 for (uint32_t idx : live->Indexes()) {
1932 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
Nicolas Geoffray974bbdd2016-03-22 15:12:07 +00001933 LiveInterval* sibling = interval->GetSiblingAt(block->GetLifetimeStart());
1934 // `GetSiblingAt` returns the sibling that contains a position, but there could be
1935 // a lifetime hole in it. `CoversSlow` returns whether the interval is live at that
1936 // position.
Nicolas Geoffray32cc7782016-03-23 11:32:27 +00001937 if ((sibling != nullptr) && sibling->CoversSlow(block->GetLifetimeStart())) {
Nicolas Geoffray974bbdd2016-03-22 15:12:07 +00001938 DCHECK(!sibling->HasRegister());
1939 }
David Brazdil77a48ae2015-09-15 12:34:04 +00001940 }
1941 }
1942 } else {
1943 BitVector* live = liveness_.GetLiveInSet(*block);
1944 for (uint32_t idx : live->Indexes()) {
1945 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
1946 for (HBasicBlock* predecessor : block->GetPredecessors()) {
1947 ConnectSplitSiblings(interval, predecessor, block);
1948 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001949 }
1950 }
1951 }
1952
1953 // Resolve phi inputs. Order does not matter.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001954 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001955 HBasicBlock* current = it.Current();
David Brazdil77a48ae2015-09-15 12:34:04 +00001956 if (current->IsCatchBlock()) {
1957 // Catch phi values are set at runtime by the exception delivery mechanism.
1958 } else {
1959 for (HInstructionIterator inst_it(current->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
1960 HInstruction* phi = inst_it.Current();
1961 for (size_t i = 0, e = current->GetPredecessors().size(); i < e; ++i) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001962 HBasicBlock* predecessor = current->GetPredecessors()[i];
David Brazdild26a4112015-11-10 11:07:31 +00001963 DCHECK_EQ(predecessor->GetNormalSuccessors().size(), 1u);
David Brazdil77a48ae2015-09-15 12:34:04 +00001964 HInstruction* input = phi->InputAt(i);
1965 Location source = input->GetLiveInterval()->GetLocationAt(
1966 predecessor->GetLifetimeEnd() - 1);
1967 Location destination = phi->GetLiveInterval()->ToLocation();
1968 InsertParallelMoveAtExitOf(predecessor, phi, source, destination);
1969 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001970 }
1971 }
1972 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001973
1974 // Assign temp locations.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001975 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001976 if (temp->IsHighInterval()) {
1977 // High intervals can be skipped, they are already handled by the low interval.
1978 continue;
1979 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001980 HInstruction* at = liveness_.GetTempUser(temp);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001981 size_t temp_index = liveness_.GetTempIndex(temp);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001982 LocationSummary* locations = at->GetLocations();
Roland Levillain5368c212014-11-27 15:03:41 +00001983 switch (temp->GetType()) {
1984 case Primitive::kPrimInt:
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001985 locations->SetTempAt(temp_index, Location::RegisterLocation(temp->GetRegister()));
Roland Levillain5368c212014-11-27 15:03:41 +00001986 break;
1987
1988 case Primitive::kPrimDouble:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001989 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
1990 Location location = Location::FpuRegisterPairLocation(
1991 temp->GetRegister(), temp->GetHighInterval()->GetRegister());
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001992 locations->SetTempAt(temp_index, location);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001993 } else {
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001994 locations->SetTempAt(temp_index, Location::FpuRegisterLocation(temp->GetRegister()));
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001995 }
Roland Levillain5368c212014-11-27 15:03:41 +00001996 break;
1997
1998 default:
1999 LOG(FATAL) << "Unexpected type for temporary location "
2000 << temp->GetType();
2001 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01002002 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01002003}
2004
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01002005} // namespace art