blob: ef22c816a031dcd1da3414c526431a8bb090c924 [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
Nicolas Geoffray98893962015-01-21 12:32:32 +000075 static constexpr bool kIsBaseline = false;
76 codegen->SetupBlockedRegisters(kIsBaseline);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +010077 physical_core_register_intervals_.resize(codegen->GetNumberOfCoreRegisters(), nullptr);
78 physical_fp_register_intervals_.resize(codegen->GetNumberOfFloatingPointRegisters(), nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +010079 // Always reserve for the current method and the graph's max out registers.
80 // TODO: compute it instead.
Mathieu Chartiere401d142015-04-22 13:56:20 -070081 // ArtMethod* takes 2 vregs for 64 bits.
82 reserved_out_slots_ = InstructionSetPointerSize(codegen->GetInstructionSet()) / kVRegSize +
83 codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010084}
85
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000086bool RegisterAllocator::CanAllocateRegistersFor(const HGraph& graph ATTRIBUTE_UNUSED,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010087 InstructionSet instruction_set) {
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020088 return instruction_set == kArm
89 || instruction_set == kArm64
90 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -070091 || instruction_set == kMips64
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020092 || instruction_set == kThumb2
Nicolas Geoffray234d69d2015-03-09 10:28:50 +000093 || instruction_set == kX86
Goran Jakovljevicf652cec2015-08-25 16:11:42 +020094 || instruction_set == kX86_64;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010095}
96
97static bool ShouldProcess(bool processing_core_registers, LiveInterval* interval) {
Nicolas Geoffray39468442014-09-02 15:17:15 +010098 if (interval == nullptr) return false;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010099 bool is_core_register = (interval->GetType() != Primitive::kPrimDouble)
100 && (interval->GetType() != Primitive::kPrimFloat);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100101 return processing_core_registers == is_core_register;
102}
103
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100104void RegisterAllocator::AllocateRegisters() {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100105 AllocateRegistersInternal();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100106 Resolve();
107
108 if (kIsDebugBuild) {
109 processing_core_registers_ = true;
110 ValidateInternal(true);
111 processing_core_registers_ = false;
112 ValidateInternal(true);
Nicolas Geoffray59768572014-12-01 09:50:04 +0000113 // Check that the linear order is still correct with regards to lifetime positions.
114 // Since only parallel moves have been inserted during the register allocation,
115 // these checks are mostly for making sure these moves have been added correctly.
116 size_t current_liveness = 0;
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100117 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray59768572014-12-01 09:50:04 +0000118 HBasicBlock* block = it.Current();
119 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
120 HInstruction* instruction = inst_it.Current();
121 DCHECK_LE(current_liveness, instruction->GetLifetimePosition());
122 current_liveness = instruction->GetLifetimePosition();
123 }
124 for (HInstructionIterator inst_it(block->GetInstructions());
125 !inst_it.Done();
126 inst_it.Advance()) {
127 HInstruction* instruction = inst_it.Current();
128 DCHECK_LE(current_liveness, instruction->GetLifetimePosition()) << instruction->DebugName();
129 current_liveness = instruction->GetLifetimePosition();
130 }
131 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100132 }
133}
134
David Brazdil77a48ae2015-09-15 12:34:04 +0000135void RegisterAllocator::BlockRegister(Location location, size_t start, size_t end) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100136 int reg = location.reg();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100137 DCHECK(location.IsRegister() || location.IsFpuRegister());
138 LiveInterval* interval = location.IsRegister()
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100139 ? physical_core_register_intervals_[reg]
140 : physical_fp_register_intervals_[reg];
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100141 Primitive::Type type = location.IsRegister()
142 ? Primitive::kPrimInt
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000143 : Primitive::kPrimFloat;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100144 if (interval == nullptr) {
145 interval = LiveInterval::MakeFixedInterval(allocator_, reg, type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100146 if (location.IsRegister()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100147 physical_core_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100148 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100149 physical_fp_register_intervals_[reg] = interval;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100150 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100151 }
152 DCHECK(interval->GetRegister() == reg);
153 interval->AddRange(start, end);
154}
155
David Brazdil77a48ae2015-09-15 12:34:04 +0000156void RegisterAllocator::BlockRegisters(size_t start, size_t end, bool caller_save_only) {
157 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
158 if (!caller_save_only || !codegen_->IsCoreCalleeSaveRegister(i)) {
159 BlockRegister(Location::RegisterLocation(i), start, end);
160 }
161 }
162 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
163 if (!caller_save_only || !codegen_->IsFloatingPointCalleeSaveRegister(i)) {
164 BlockRegister(Location::FpuRegisterLocation(i), start, end);
165 }
166 }
167}
168
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100169void RegisterAllocator::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100170 // Iterate post-order, to ensure the list is sorted, and the last added interval
171 // is the one with the lowest start position.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +0100172 for (HLinearPostOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100173 HBasicBlock* block = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800174 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
175 back_it.Advance()) {
176 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100177 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800178 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
179 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100180 }
David Brazdil77a48ae2015-09-15 12:34:04 +0000181
182 if (block->IsCatchBlock()) {
183 // By blocking all registers at the top of each catch block, we force
184 // intervals used after catch to spill.
185 size_t position = block->GetLifetimeStart();
186 BlockRegisters(position, position + 1);
187 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100188 }
189
Nicolas Geoffray39468442014-09-02 15:17:15 +0100190 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100191 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
192 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100193 processing_core_registers_ = true;
194 unhandled_ = &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100195 for (LiveInterval* fixed : physical_core_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100196 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700197 // Fixed interval is added to inactive_ instead of unhandled_.
198 // It's also the only type of inactive interval whose start position
199 // can be after the current interval during linear scan.
200 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100201 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100202 }
203 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100204 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100205
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100206 inactive_.clear();
207 active_.clear();
208 handled_.clear();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100209
210 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
Vladimir Marko5233f932015-09-29 19:01:15 +0100211 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_,
212 kArenaAllocRegisterAllocator);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100213 processing_core_registers_ = false;
214 unhandled_ = &unhandled_fp_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100215 for (LiveInterval* fixed : physical_fp_register_intervals_) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100216 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700217 // Fixed interval is added to inactive_ instead of unhandled_.
218 // It's also the only type of inactive interval whose start position
219 // can be after the current interval during linear scan.
220 // Fixed interval is never split and never moves to unhandled_.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100221 inactive_.push_back(fixed);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100222 }
223 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100224 LinearScan();
225}
226
227void RegisterAllocator::ProcessInstruction(HInstruction* instruction) {
228 LocationSummary* locations = instruction->GetLocations();
229 size_t position = instruction->GetLifetimePosition();
230
231 if (locations == nullptr) return;
232
233 // Create synthesized intervals for temporaries.
234 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
235 Location temp = locations->GetTemp(i);
Nicolas Geoffray52839d12014-11-07 17:47:25 +0000236 if (temp.IsRegister() || temp.IsFpuRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100237 BlockRegister(temp, position, position + 1);
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000238 // Ensure that an explicit temporary register is marked as being allocated.
239 codegen_->AddAllocatedRegister(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100240 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100241 DCHECK(temp.IsUnallocated());
Roland Levillain5368c212014-11-27 15:03:41 +0000242 switch (temp.GetPolicy()) {
243 case Location::kRequiresRegister: {
244 LiveInterval* interval =
245 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimInt);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100246 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000247 interval->AddTempUse(instruction, i);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100248 unhandled_core_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000249 break;
250 }
251
252 case Location::kRequiresFpuRegister: {
253 LiveInterval* interval =
254 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimDouble);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100255 temp_intervals_.push_back(interval);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +0000256 interval->AddTempUse(instruction, i);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000257 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100258 interval->AddHighInterval(/* is_temp */ true);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000259 LiveInterval* high = interval->GetHighInterval();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100260 temp_intervals_.push_back(high);
261 unhandled_fp_intervals_.push_back(high);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000262 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100263 unhandled_fp_intervals_.push_back(interval);
Roland Levillain5368c212014-11-27 15:03:41 +0000264 break;
265 }
266
267 default:
268 LOG(FATAL) << "Unexpected policy for temporary location "
269 << temp.GetPolicy();
270 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100271 }
272 }
273
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100274 bool core_register = (instruction->GetType() != Primitive::kPrimDouble)
275 && (instruction->GetType() != Primitive::kPrimFloat);
276
Alexandre Rames8158f282015-08-07 10:26:17 +0100277 if (locations->NeedsSafepoint()) {
Nicolas Geoffrayc0572a42015-02-06 14:35:25 +0000278 if (codegen_->IsLeafMethod()) {
279 // TODO: We do this here because we do not want the suspend check to artificially
280 // create live registers. We should find another place, but this is currently the
281 // simplest.
282 DCHECK(instruction->IsSuspendCheckEntry());
283 instruction->GetBlock()->RemoveInstruction(instruction);
284 return;
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100285 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100286 safepoints_.push_back(instruction);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100287 if (locations->OnlyCallsOnSlowPath()) {
288 // We add a synthesized range at this position to record the live registers
289 // at this position. Ideally, we could just update the safepoints when locations
290 // are updated, but we currently need to know the full stack size before updating
291 // locations (because of parameters and the fact that we don't have a frame pointer).
292 // And knowing the full stack size requires to know the maximum number of live
293 // registers at calls in slow paths.
294 // By adding the following interval in the algorithm, we can compute this
295 // maximum before updating locations.
296 LiveInterval* interval = LiveInterval::MakeSlowPathInterval(allocator_, instruction);
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000297 interval->AddRange(position, position + 1);
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000298 AddSorted(&unhandled_core_intervals_, interval);
299 AddSorted(&unhandled_fp_intervals_, interval);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100300 }
301 }
302
303 if (locations->WillCall()) {
David Brazdil77a48ae2015-09-15 12:34:04 +0000304 BlockRegisters(position, position + 1, /* caller_save_only */ true);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100305 }
306
307 for (size_t i = 0; i < instruction->InputCount(); ++i) {
308 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100309 if (input.IsRegister() || input.IsFpuRegister()) {
310 BlockRegister(input, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000311 } else if (input.IsPair()) {
312 BlockRegister(input.ToLow(), position, position + 1);
313 BlockRegister(input.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100314 }
315 }
316
Nicolas Geoffray39468442014-09-02 15:17:15 +0100317 LiveInterval* current = instruction->GetLiveInterval();
318 if (current == nullptr) return;
319
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100320 ArenaVector<LiveInterval*>& unhandled = core_register
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100321 ? unhandled_core_intervals_
322 : unhandled_fp_intervals_;
323
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100324 DCHECK(unhandled.empty() || current->StartsBeforeOrAt(unhandled.back()));
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000325
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000326 if (codegen_->NeedsTwoRegisters(current->GetType())) {
327 current->AddHighInterval();
328 }
329
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100330 for (size_t safepoint_index = safepoints_.size(); safepoint_index > 0; --safepoint_index) {
331 HInstruction* safepoint = safepoints_[safepoint_index - 1u];
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100332 size_t safepoint_position = safepoint->GetLifetimePosition();
333
334 // Test that safepoints are ordered in the optimal way.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100335 DCHECK(safepoint_index == safepoints_.size() ||
336 safepoints_[safepoint_index]->GetLifetimePosition() < safepoint_position);
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100337
338 if (safepoint_position == current->GetStart()) {
339 // The safepoint is for this instruction, so the location of the instruction
340 // does not need to be saved.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100341 DCHECK_EQ(safepoint_index, safepoints_.size());
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100342 DCHECK_EQ(safepoint, instruction);
343 continue;
344 } else if (current->IsDeadAt(safepoint_position)) {
345 break;
346 } else if (!current->Covers(safepoint_position)) {
347 // Hole in the interval.
348 continue;
349 }
350 current->AddSafepoint(safepoint);
351 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100352 current->ResetSearchCache();
Nicolas Geoffray5588e582015-04-14 14:10:59 +0100353
Nicolas Geoffray39468442014-09-02 15:17:15 +0100354 // Some instructions define their output in fixed register/stack slot. We need
355 // to ensure we know these locations before doing register allocation. For a
356 // given register, we create an interval that covers these locations. The register
357 // will be unavailable at these locations when trying to allocate one for an
358 // interval.
359 //
360 // The backwards walking ensures the ranges are ordered on increasing start positions.
361 Location output = locations->Out();
Calin Juravled0d48522014-11-04 16:40:20 +0000362 if (output.IsUnallocated() && output.GetPolicy() == Location::kSameAsFirstInput) {
363 Location first = locations->InAt(0);
364 if (first.IsRegister() || first.IsFpuRegister()) {
365 current->SetFrom(position + 1);
366 current->SetRegister(first.reg());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000367 } else if (first.IsPair()) {
368 current->SetFrom(position + 1);
369 current->SetRegister(first.low());
370 LiveInterval* high = current->GetHighInterval();
371 high->SetRegister(first.high());
372 high->SetFrom(position + 1);
Calin Juravled0d48522014-11-04 16:40:20 +0000373 }
374 } else if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100375 // Shift the interval's start by one to account for the blocked register.
376 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100377 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100378 BlockRegister(output, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000379 } else if (output.IsPair()) {
380 current->SetFrom(position + 1);
381 current->SetRegister(output.low());
382 LiveInterval* high = current->GetHighInterval();
383 high->SetRegister(output.high());
384 high->SetFrom(position + 1);
385 BlockRegister(output.ToLow(), position, position + 1);
386 BlockRegister(output.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100387 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
388 current->SetSpillSlot(output.GetStackIndex());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000389 } else {
390 DCHECK(output.IsUnallocated() || output.IsConstant());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100391 }
392
David Brazdil77a48ae2015-09-15 12:34:04 +0000393 if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
394 AllocateSpillSlotForCatchPhi(instruction->AsPhi());
395 }
396
Nicolas Geoffray39468442014-09-02 15:17:15 +0100397 // If needed, add interval to the list of unhandled intervals.
398 if (current->HasSpillSlot() || instruction->IsConstant()) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100399 // Split just before first register use.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100400 size_t first_register_use = current->FirstRegisterUse();
401 if (first_register_use != kNoLifetime) {
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +0100402 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000403 // Don't add directly to `unhandled`, it needs to be sorted and the start
Nicolas Geoffray39468442014-09-02 15:17:15 +0100404 // of this new interval might be after intervals already in the list.
405 AddSorted(&unhandled, split);
406 } else {
407 // Nothing to do, we won't allocate a register for this value.
408 }
409 } else {
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000410 // Don't add directly to `unhandled`, temp or safepoint intervals
411 // for this instruction may have been added, and those can be
412 // processed first.
413 AddSorted(&unhandled, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100414 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100415}
416
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100417class AllRangesIterator : public ValueObject {
418 public:
419 explicit AllRangesIterator(LiveInterval* interval)
420 : current_interval_(interval),
421 current_range_(interval->GetFirstRange()) {}
422
423 bool Done() const { return current_interval_ == nullptr; }
424 LiveRange* CurrentRange() const { return current_range_; }
425 LiveInterval* CurrentInterval() const { return current_interval_; }
426
427 void Advance() {
428 current_range_ = current_range_->GetNext();
429 if (current_range_ == nullptr) {
430 current_interval_ = current_interval_->GetNextSibling();
431 if (current_interval_ != nullptr) {
432 current_range_ = current_interval_->GetFirstRange();
433 }
434 }
435 }
436
437 private:
438 LiveInterval* current_interval_;
439 LiveRange* current_range_;
440
441 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
442};
443
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100444bool RegisterAllocator::ValidateInternal(bool log_fatal_on_failure) const {
445 // To simplify unit testing, we eagerly create the array of intervals, and
446 // call the helper method.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100447 ArenaVector<LiveInterval*> intervals(allocator_->Adapter(kArenaAllocRegisterAllocator));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100448 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
449 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
450 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100451 intervals.push_back(instruction->GetLiveInterval());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100452 }
453 }
454
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100455 const ArenaVector<LiveInterval*>* physical_register_intervals = processing_core_registers_
456 ? &physical_core_register_intervals_
457 : &physical_fp_register_intervals_;
458 for (LiveInterval* fixed : *physical_register_intervals) {
459 if (fixed != nullptr) {
460 intervals.push_back(fixed);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100461 }
462 }
463
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100464 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100465 if (ShouldProcess(processing_core_registers_, temp)) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100466 intervals.push_back(temp);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100467 }
468 }
469
Nicolas Geoffray776b3182015-02-23 14:14:57 +0000470 return ValidateIntervals(intervals, GetNumberOfSpillSlots(), reserved_out_slots_, *codegen_,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100471 allocator_, processing_core_registers_, log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100472}
473
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100474bool RegisterAllocator::ValidateIntervals(const ArenaVector<LiveInterval*>& intervals,
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100475 size_t number_of_spill_slots,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100476 size_t number_of_out_slots,
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100477 const CodeGenerator& codegen,
478 ArenaAllocator* allocator,
479 bool processing_core_registers,
480 bool log_fatal_on_failure) {
481 size_t number_of_registers = processing_core_registers
482 ? codegen.GetNumberOfCoreRegisters()
483 : codegen.GetNumberOfFloatingPointRegisters();
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100484 ArenaVector<ArenaBitVector*> liveness_of_values(
485 allocator->Adapter(kArenaAllocRegisterAllocator));
486 liveness_of_values.reserve(number_of_registers + number_of_spill_slots);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100487
488 // Allocate a bit vector per register. A live interval that has a register
489 // allocated will populate the associated bit vector based on its live ranges.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100490 for (size_t i = 0; i < number_of_registers + number_of_spill_slots; ++i) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100491 liveness_of_values.push_back(new (allocator) ArenaBitVector(allocator, 0, true));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100492 }
493
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100494 for (LiveInterval* start_interval : intervals) {
495 for (AllRangesIterator it(start_interval); !it.Done(); it.Advance()) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100496 LiveInterval* current = it.CurrentInterval();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100497 HInstruction* defined_by = current->GetParent()->GetDefinedBy();
498 if (current->GetParent()->HasSpillSlot()
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100499 // Parameters and current method have their own stack slot.
500 && !(defined_by != nullptr && (defined_by->IsParameterValue()
501 || defined_by->IsCurrentMethod()))) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100502 BitVector* liveness_of_spill_slot = liveness_of_values[number_of_registers
Nicolas Geoffray39468442014-09-02 15:17:15 +0100503 + current->GetParent()->GetSpillSlot() / kVRegSize
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100504 - number_of_out_slots];
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100505 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
506 if (liveness_of_spill_slot->IsBitSet(j)) {
507 if (log_fatal_on_failure) {
508 std::ostringstream message;
509 message << "Spill slot conflict at " << j;
510 LOG(FATAL) << message.str();
511 } else {
512 return false;
513 }
514 } else {
515 liveness_of_spill_slot->SetBit(j);
516 }
517 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100518 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100519
520 if (current->HasRegister()) {
Nicolas Geoffray45b83af2015-07-06 15:12:53 +0000521 if (kIsDebugBuild && log_fatal_on_failure && !current->IsFixed()) {
522 // Only check when an error is fatal. Only tests code ask for non-fatal failures
523 // and test code may not properly fill the right information to the code generator.
524 CHECK(codegen.HasAllocatedRegister(processing_core_registers, current->GetRegister()));
525 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100526 BitVector* liveness_of_register = liveness_of_values[current->GetRegister()];
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100527 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
528 if (liveness_of_register->IsBitSet(j)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000529 if (current->IsUsingInputRegister() && current->CanUseInputRegister()) {
530 continue;
531 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100532 if (log_fatal_on_failure) {
533 std::ostringstream message;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100534 message << "Register conflict at " << j << " ";
535 if (defined_by != nullptr) {
536 message << "(" << defined_by->DebugName() << ")";
537 }
538 message << "for ";
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100539 if (processing_core_registers) {
540 codegen.DumpCoreRegister(message, current->GetRegister());
541 } else {
542 codegen.DumpFloatingPointRegister(message, current->GetRegister());
543 }
544 LOG(FATAL) << message.str();
545 } else {
546 return false;
547 }
548 } else {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100549 liveness_of_register->SetBit(j);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100550 }
551 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100552 }
553 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100554 }
555 return true;
556}
557
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100558void RegisterAllocator::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100559 interval->Dump(stream);
560 stream << ": ";
561 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100562 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100563 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100564 } else {
565 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100566 }
567 } else {
568 stream << "spilled";
569 }
570 stream << std::endl;
571}
572
Mingyao Yang296bd602014-10-06 16:47:28 -0700573void RegisterAllocator::DumpAllIntervals(std::ostream& stream) const {
574 stream << "inactive: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100575 for (LiveInterval* inactive_interval : inactive_) {
576 DumpInterval(stream, inactive_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700577 }
578 stream << "active: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100579 for (LiveInterval* active_interval : active_) {
580 DumpInterval(stream, active_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700581 }
582 stream << "unhandled: " << std::endl;
583 auto unhandled = (unhandled_ != nullptr) ?
584 unhandled_ : &unhandled_core_intervals_;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100585 for (LiveInterval* unhandled_interval : *unhandled) {
586 DumpInterval(stream, unhandled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700587 }
588 stream << "handled: " << std::endl;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100589 for (LiveInterval* handled_interval : handled_) {
590 DumpInterval(stream, handled_interval);
Mingyao Yang296bd602014-10-06 16:47:28 -0700591 }
592}
593
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100594// By the book implementation of a linear scan register allocator.
595void RegisterAllocator::LinearScan() {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100596 while (!unhandled_->empty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100597 // (1) Remove interval with the lowest start position from unhandled.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100598 LiveInterval* current = unhandled_->back();
599 unhandled_->pop_back();
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100600
601 // Make sure the interval is an expected state.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100602 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100603 // Make sure we are going in the right order.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100604 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() >= current->GetStart());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100605 // Make sure a low interval is always with a high.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100606 DCHECK(!current->IsLowInterval() || unhandled_->back()->IsHighInterval());
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100607 // Make sure a high interval is always with a low.
608 DCHECK(current->IsLowInterval() ||
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100609 unhandled_->empty() ||
610 !unhandled_->back()->IsHighInterval());
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000611
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100612 size_t position = current->GetStart();
613
Mingyao Yang296bd602014-10-06 16:47:28 -0700614 // Remember the inactive_ size here since the ones moved to inactive_ from
615 // active_ below shouldn't need to be re-checked.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100616 size_t inactive_intervals_to_handle = inactive_.size();
Mingyao Yang296bd602014-10-06 16:47:28 -0700617
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100618 // (2) Remove currently active intervals that are dead at this position.
619 // Move active intervals that have a lifetime hole at this position
620 // to inactive.
Vladimir Markob95fb772015-09-30 13:32:31 +0100621 auto active_kept_end = std::remove_if(
622 active_.begin(),
623 active_.end(),
624 [this, position](LiveInterval* interval) {
625 if (interval->IsDeadAt(position)) {
626 handled_.push_back(interval);
627 return true;
628 } else if (!interval->Covers(position)) {
629 inactive_.push_back(interval);
630 return true;
631 } else {
632 return false; // Keep this interval.
633 }
634 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100635 active_.erase(active_kept_end, active_.end());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100636
637 // (3) Remove currently inactive intervals that are dead at this position.
638 // Move inactive intervals that cover this position to active.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100639 auto inactive_to_handle_end = inactive_.begin() + inactive_intervals_to_handle;
Vladimir Markob95fb772015-09-30 13:32:31 +0100640 auto inactive_kept_end = std::remove_if(
641 inactive_.begin(),
642 inactive_to_handle_end,
643 [this, position](LiveInterval* interval) {
644 DCHECK(interval->GetStart() < position || interval->IsFixed());
645 if (interval->IsDeadAt(position)) {
646 handled_.push_back(interval);
647 return true;
648 } else if (interval->Covers(position)) {
649 active_.push_back(interval);
650 return true;
651 } else {
652 return false; // Keep this interval.
653 }
654 });
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100655 inactive_.erase(inactive_kept_end, inactive_to_handle_end);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100656
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000657 if (current->IsSlowPathSafepoint()) {
658 // Synthesized interval to record the maximum number of live registers
659 // at safepoints. No need to allocate a register for it.
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500660 if (processing_core_registers_) {
661 maximum_number_of_live_core_registers_ =
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100662 std::max(maximum_number_of_live_core_registers_, active_.size());
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500663 } else {
664 maximum_number_of_live_fp_registers_ =
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100665 std::max(maximum_number_of_live_fp_registers_, active_.size());
Mark Mendellf85a9ca2015-01-13 09:20:58 -0500666 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100667 DCHECK(unhandled_->empty() || unhandled_->back()->GetStart() > current->GetStart());
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000668 continue;
669 }
670
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000671 if (current->IsHighInterval() && !current->GetLowInterval()->HasRegister()) {
672 DCHECK(!current->HasRegister());
673 // Allocating the low part was unsucessful. The splitted interval for the high part
674 // will be handled next (it is in the `unhandled_` list).
675 continue;
676 }
677
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100678 // (4) Try to find an available register.
679 bool success = TryAllocateFreeReg(current);
680
681 // (5) If no register could be found, we need to spill.
682 if (!success) {
683 success = AllocateBlockedReg(current);
684 }
685
686 // (6) If the interval had a register allocated, add it to the list of active
687 // intervals.
688 if (success) {
Nicolas Geoffray98893962015-01-21 12:32:32 +0000689 codegen_->AddAllocatedRegister(processing_core_registers_
690 ? Location::RegisterLocation(current->GetRegister())
691 : Location::FpuRegisterLocation(current->GetRegister()));
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100692 active_.push_back(current);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000693 if (current->HasHighInterval() && !current->GetHighInterval()->HasRegister()) {
694 current->GetHighInterval()->SetRegister(GetHighForLowRegister(current->GetRegister()));
695 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100696 }
697 }
698}
699
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000700static void FreeIfNotCoverAt(LiveInterval* interval, size_t position, size_t* free_until) {
701 DCHECK(!interval->IsHighInterval());
702 // Note that the same instruction may occur multiple times in the input list,
703 // so `free_until` may have changed already.
David Brazdil3fc992f2015-04-16 18:31:55 +0100704 // Since `position` is not the current scan position, we need to use CoversSlow.
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000705 if (interval->IsDeadAt(position)) {
706 // Set the register to be free. Note that inactive intervals might later
707 // update this.
708 free_until[interval->GetRegister()] = kMaxLifetimePosition;
709 if (interval->HasHighInterval()) {
710 DCHECK(interval->GetHighInterval()->IsDeadAt(position));
711 free_until[interval->GetHighInterval()->GetRegister()] = kMaxLifetimePosition;
712 }
David Brazdil3fc992f2015-04-16 18:31:55 +0100713 } else if (!interval->CoversSlow(position)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000714 // The interval becomes inactive at `defined_by`. We make its register
715 // available only until the next use strictly after `defined_by`.
716 free_until[interval->GetRegister()] = interval->FirstUseAfter(position);
717 if (interval->HasHighInterval()) {
David Brazdil3fc992f2015-04-16 18:31:55 +0100718 DCHECK(!interval->GetHighInterval()->CoversSlow(position));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000719 free_until[interval->GetHighInterval()->GetRegister()] = free_until[interval->GetRegister()];
720 }
721 }
722}
723
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100724// Find a free register. If multiple are found, pick the register that
725// is free the longest.
726bool RegisterAllocator::TryAllocateFreeReg(LiveInterval* current) {
727 size_t* free_until = registers_array_;
728
729 // First set all registers to be free.
730 for (size_t i = 0; i < number_of_registers_; ++i) {
731 free_until[i] = kMaxLifetimePosition;
732 }
733
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100734 // For each active interval, set its register to not free.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100735 for (LiveInterval* interval : active_) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100736 DCHECK(interval->HasRegister());
737 free_until[interval->GetRegister()] = 0;
738 }
739
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000740 // An interval that starts an instruction (that is, it is not split), may
741 // re-use the registers used by the inputs of that instruciton, based on the
742 // location summary.
743 HInstruction* defined_by = current->GetDefinedBy();
744 if (defined_by != nullptr && !current->IsSplit()) {
745 LocationSummary* locations = defined_by->GetLocations();
746 if (!locations->OutputCanOverlapWithInputs() && locations->Out().IsUnallocated()) {
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100747 for (size_t i = 0, e = defined_by->InputCount(); i < e; ++i) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000748 // Take the last interval of the input. It is the location of that interval
749 // that will be used at `defined_by`.
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100750 LiveInterval* interval = defined_by->InputAt(i)->GetLiveInterval()->GetLastSibling();
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000751 // Note that interval may have not been processed yet.
752 // TODO: Handle non-split intervals last in the work list.
Nicolas Geoffray94015b92015-06-04 18:21:04 +0100753 if (locations->InAt(i).IsValid()
754 && interval->HasRegister()
755 && interval->SameRegisterKind(*current)) {
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000756 // The input must be live until the end of `defined_by`, to comply to
757 // the linear scan algorithm. So we use `defined_by`'s end lifetime
758 // position to check whether the input is dead or is inactive after
759 // `defined_by`.
David Brazdil3fc992f2015-04-16 18:31:55 +0100760 DCHECK(interval->CoversSlow(defined_by->GetLifetimePosition()));
Nicolas Geoffray829280c2015-01-28 10:20:37 +0000761 size_t position = defined_by->GetLifetimePosition() + 1;
762 FreeIfNotCoverAt(interval, position, free_until);
763 }
764 }
765 }
766 }
767
Mingyao Yang296bd602014-10-06 16:47:28 -0700768 // For each inactive interval, set its register to be free until
769 // the next intersection with `current`.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100770 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700771 // Temp/Slow-path-safepoint interval has no holes.
772 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
773 if (!current->IsSplit() && !inactive->IsFixed()) {
774 // Neither current nor inactive are fixed.
775 // Thanks to SSA, a non-split interval starting in a hole of an
776 // inactive interval should never intersect with that inactive interval.
777 // Only if it's not fixed though, because fixed intervals don't come from SSA.
778 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
779 continue;
780 }
781
782 DCHECK(inactive->HasRegister());
783 if (free_until[inactive->GetRegister()] == 0) {
784 // Already used by some active interval. No need to intersect.
785 continue;
786 }
787 size_t next_intersection = inactive->FirstIntersectionWith(current);
788 if (next_intersection != kNoLifetime) {
789 free_until[inactive->GetRegister()] =
790 std::min(free_until[inactive->GetRegister()], next_intersection);
791 }
792 }
793
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000794 int reg = kNoRegister;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100795 if (current->HasRegister()) {
796 // Some instructions have a fixed register output.
797 reg = current->GetRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000798 if (free_until[reg] == 0) {
799 DCHECK(current->IsHighInterval());
800 // AllocateBlockedReg will spill the holder of the register.
801 return false;
802 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100803 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000804 DCHECK(!current->IsHighInterval());
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +0100805 int hint = current->FindFirstRegisterHint(free_until, liveness_);
Nicolas Geoffrayf2975812015-08-07 18:13:03 -0700806 if ((hint != kNoRegister)
807 // For simplicity, if the hint we are getting for a pair cannot be used,
808 // we are just going to allocate a new pair.
809 && !(current->IsLowInterval() && IsBlocked(GetHighForLowRegister(hint)))) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100810 DCHECK(!IsBlocked(hint));
811 reg = hint;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000812 } else if (current->IsLowInterval()) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000813 reg = FindAvailableRegisterPair(free_until, current->GetStart());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100814 } else {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100815 reg = FindAvailableRegister(free_until, current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100816 }
817 }
818
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000819 DCHECK_NE(reg, kNoRegister);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100820 // If we could not find a register, we need to spill.
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000821 if (free_until[reg] == 0) {
822 return false;
823 }
824
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000825 if (current->IsLowInterval()) {
826 // If the high register of this interval is not available, we need to spill.
827 int high_reg = current->GetHighInterval()->GetRegister();
828 if (high_reg == kNoRegister) {
829 high_reg = GetHighForLowRegister(reg);
830 }
831 if (free_until[high_reg] == 0) {
832 return false;
833 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100834 }
835
836 current->SetRegister(reg);
837 if (!current->IsDeadAt(free_until[reg])) {
838 // If the register is only available for a subset of live ranges
Nicolas Geoffray82726882015-06-01 13:51:57 +0100839 // covered by `current`, split `current` before the position where
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100840 // the register is not available anymore.
Nicolas Geoffray82726882015-06-01 13:51:57 +0100841 LiveInterval* split = SplitBetween(current, current->GetStart(), free_until[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100842 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100843 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100844 }
845 return true;
846}
847
848bool RegisterAllocator::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100849 return processing_core_registers_
850 ? blocked_core_registers_[reg]
851 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100852}
853
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000854int RegisterAllocator::FindAvailableRegisterPair(size_t* next_use, size_t starting_at) const {
855 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000856 // Pick the register pair that is used the last.
857 for (size_t i = 0; i < number_of_registers_; ++i) {
858 if (IsBlocked(i)) continue;
859 if (!IsLowRegister(i)) continue;
860 int high_register = GetHighForLowRegister(i);
861 if (IsBlocked(high_register)) continue;
862 int existing_high_register = GetHighForLowRegister(reg);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000863 if ((reg == kNoRegister) || (next_use[i] >= next_use[reg]
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000864 && next_use[high_register] >= next_use[existing_high_register])) {
865 reg = i;
866 if (next_use[i] == kMaxLifetimePosition
867 && next_use[high_register] == kMaxLifetimePosition) {
868 break;
869 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000870 } else if (next_use[reg] <= starting_at || next_use[existing_high_register] <= starting_at) {
871 // If one of the current register is known to be unavailable, just unconditionally
872 // try a new one.
873 reg = i;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000874 }
875 }
876 return reg;
877}
878
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100879bool RegisterAllocator::IsCallerSaveRegister(int reg) const {
880 return processing_core_registers_
881 ? !codegen_->IsCoreCalleeSaveRegister(reg)
882 : !codegen_->IsFloatingPointCalleeSaveRegister(reg);
883}
884
885int RegisterAllocator::FindAvailableRegister(size_t* next_use, LiveInterval* current) const {
886 // We special case intervals that do not span a safepoint to try to find a caller-save
887 // register if one is available. We iterate from 0 to the number of registers,
888 // so if there are caller-save registers available at the end, we continue the iteration.
889 bool prefers_caller_save = !current->HasWillCallSafepoint();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000890 int reg = kNoRegister;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000891 for (size_t i = 0; i < number_of_registers_; ++i) {
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100892 if (IsBlocked(i)) {
893 // Register cannot be used. Continue.
894 continue;
895 }
896
897 // Best case: we found a register fully available.
898 if (next_use[i] == kMaxLifetimePosition) {
899 if (prefers_caller_save && !IsCallerSaveRegister(i)) {
900 // We can get shorter encodings on some platforms by using
901 // small register numbers. So only update the candidate if the previous
902 // one was not available for the whole method.
903 if (reg == kNoRegister || next_use[reg] != kMaxLifetimePosition) {
904 reg = i;
905 }
906 // Continue the iteration in the hope of finding a caller save register.
907 continue;
908 } else {
909 reg = i;
910 // We know the register is good enough. Return it.
911 break;
912 }
913 }
914
915 // If we had no register before, take this one as a reference.
916 if (reg == kNoRegister) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000917 reg = i;
Nicolas Geoffray8826f672015-04-17 09:15:11 +0100918 continue;
919 }
920
921 // Pick the register that is used the last.
922 if (next_use[i] > next_use[reg]) {
923 reg = i;
924 continue;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000925 }
926 }
927 return reg;
928}
929
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100930// Remove interval and its other half if any. Return iterator to the following element.
931static ArenaVector<LiveInterval*>::iterator RemoveIntervalAndPotentialOtherHalf(
932 ArenaVector<LiveInterval*>* intervals, ArenaVector<LiveInterval*>::iterator pos) {
933 DCHECK(intervals->begin() <= pos && pos < intervals->end());
934 LiveInterval* interval = *pos;
935 if (interval->IsLowInterval()) {
936 DCHECK(pos + 1 < intervals->end());
937 DCHECK_EQ(*(pos + 1), interval->GetHighInterval());
938 return intervals->erase(pos, pos + 2);
939 } else if (interval->IsHighInterval()) {
940 DCHECK(intervals->begin() < pos);
941 DCHECK_EQ(*(pos - 1), interval->GetLowInterval());
942 return intervals->erase(pos - 1, pos + 1);
943 } else {
944 return intervals->erase(pos);
945 }
946}
947
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000948bool RegisterAllocator::TrySplitNonPairOrUnalignedPairIntervalAt(size_t position,
949 size_t first_register_use,
950 size_t* next_use) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100951 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
952 LiveInterval* active = *it;
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000953 DCHECK(active->HasRegister());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +0000954 if (active->IsFixed()) continue;
955 if (active->IsHighInterval()) continue;
956 if (first_register_use > next_use[active->GetRegister()]) continue;
957
Nicolas Geoffray2e92bc22015-08-20 19:52:26 +0100958 // Split the first interval found that is either:
959 // 1) A non-pair interval.
960 // 2) A pair interval whose high is not low + 1.
961 // 3) A pair interval whose low is not even.
962 if (!active->IsLowInterval() ||
963 IsLowOfUnalignedPairInterval(active) ||
964 !IsLowRegister(active->GetRegister())) {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000965 LiveInterval* split = Split(active, position);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000966 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100967 handled_.push_back(active);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000968 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +0100969 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000970 AddSorted(unhandled_, split);
971 return true;
972 }
973 }
974 return false;
975}
976
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100977// Find the register that is used the last, and spill the interval
978// that holds it. If the first use of `current` is after that register
979// we spill `current` instead.
980bool RegisterAllocator::AllocateBlockedReg(LiveInterval* current) {
981 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -0700982 if (current->HasRegister()) {
983 DCHECK(current->IsHighInterval());
984 // The low interval has allocated the register for the high interval. In
985 // case the low interval had to split both intervals, we may end up in a
986 // situation where the high interval does not have a register use anymore.
987 // We must still proceed in order to split currently active and inactive
988 // uses of the high interval's register, and put the high interval in the
989 // active set.
990 DCHECK(first_register_use != kNoLifetime || (current->GetNextSibling() != nullptr));
991 } else if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100992 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100993 return false;
994 }
995
Nicolas Geoffray1ba19812015-04-21 09:12:40 +0100996 // We use the first use to compare with other intervals. If this interval
997 // is used after any active intervals, we will spill this interval.
998 size_t first_use = current->FirstUseAfter(current->GetStart());
999
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001000 // First set all registers as not being used.
1001 size_t* next_use = registers_array_;
1002 for (size_t i = 0; i < number_of_registers_; ++i) {
1003 next_use[i] = kMaxLifetimePosition;
1004 }
1005
1006 // For each active interval, find the next use of its register after the
1007 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001008 for (LiveInterval* active : active_) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001009 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001010 if (active->IsFixed()) {
1011 next_use[active->GetRegister()] = current->GetStart();
1012 } else {
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001013 size_t use = active->FirstUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001014 if (use != kNoLifetime) {
1015 next_use[active->GetRegister()] = use;
1016 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001017 }
1018 }
1019
1020 // For each inactive interval, find the next use of its register after the
1021 // start of current.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001022 for (LiveInterval* inactive : inactive_) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001023 // Temp/Slow-path-safepoint interval has no holes.
1024 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
1025 if (!current->IsSplit() && !inactive->IsFixed()) {
1026 // Neither current nor inactive are fixed.
1027 // Thanks to SSA, a non-split interval starting in a hole of an
1028 // inactive interval should never intersect with that inactive interval.
1029 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1030 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
1031 continue;
1032 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001033 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001034 size_t next_intersection = inactive->FirstIntersectionWith(current);
1035 if (next_intersection != kNoLifetime) {
1036 if (inactive->IsFixed()) {
1037 next_use[inactive->GetRegister()] =
1038 std::min(next_intersection, next_use[inactive->GetRegister()]);
1039 } else {
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001040 size_t use = inactive->FirstUseAfter(current->GetStart());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001041 if (use != kNoLifetime) {
1042 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
1043 }
1044 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001045 }
1046 }
1047
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001048 int reg = kNoRegister;
1049 bool should_spill = false;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001050 if (current->HasRegister()) {
1051 DCHECK(current->IsHighInterval());
1052 reg = current->GetRegister();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001053 // When allocating the low part, we made sure the high register was available.
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001054 DCHECK_LT(first_use, next_use[reg]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001055 } else if (current->IsLowInterval()) {
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001056 reg = FindAvailableRegisterPair(next_use, first_use);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001057 // We should spill if both registers are not available.
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001058 should_spill = (first_use >= next_use[reg])
1059 || (first_use >= next_use[GetHighForLowRegister(reg)]);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001060 } else {
1061 DCHECK(!current->IsHighInterval());
Nicolas Geoffray8826f672015-04-17 09:15:11 +01001062 reg = FindAvailableRegister(next_use, current);
Nicolas Geoffray1ba19812015-04-21 09:12:40 +01001063 should_spill = (first_use >= next_use[reg]);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001064 }
1065
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001066 DCHECK_NE(reg, kNoRegister);
1067 if (should_spill) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001068 DCHECK(!current->IsHighInterval());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001069 bool is_allocation_at_use_site = (current->GetStart() >= (first_register_use - 1));
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001070 if (is_allocation_at_use_site) {
1071 if (!current->IsLowInterval()) {
1072 DumpInterval(std::cerr, current);
1073 DumpAllIntervals(std::cerr);
1074 // This situation has the potential to infinite loop, so we make it a non-debug CHECK.
1075 HInstruction* at = liveness_.GetInstructionFromPosition(first_register_use / 2);
1076 CHECK(false) << "There is not enough registers available for "
1077 << current->GetParent()->GetDefinedBy()->DebugName() << " "
1078 << current->GetParent()->GetDefinedBy()->GetId()
1079 << " at " << first_register_use - 1 << " "
1080 << (at == nullptr ? "" : at->DebugName());
1081 }
1082
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001083 // If we're allocating a register for `current` because the instruction at
1084 // that position requires it, but we think we should spill, then there are
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001085 // non-pair intervals or unaligned pair intervals blocking the allocation.
1086 // We split the first interval found, and put ourselves first in the
1087 // `unhandled_` list.
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001088 bool success = TrySplitNonPairOrUnalignedPairIntervalAt(current->GetStart(),
1089 first_register_use,
1090 next_use);
1091 DCHECK(success);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001092 LiveInterval* existing = unhandled_->back();
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001093 DCHECK(existing->IsHighInterval());
1094 DCHECK_EQ(existing->GetLowInterval(), current);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001095 unhandled_->push_back(current);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001096 } else {
1097 // If the first use of that instruction is after the last use of the found
1098 // register, we split this interval just before its first register use.
1099 AllocateSpillSlotFor(current);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001100 LiveInterval* split = SplitBetween(current, current->GetStart(), first_register_use - 1);
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001101 DCHECK(current != split);
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001102 AddSorted(unhandled_, split);
1103 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001104 return false;
1105 } else {
1106 // Use this register and spill the active and inactives interval that
1107 // have that register.
1108 current->SetRegister(reg);
1109
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001110 for (auto it = active_.begin(), end = active_.end(); it != end; ++it) {
1111 LiveInterval* active = *it;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001112 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001113 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001114 LiveInterval* split = Split(active, current->GetStart());
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001115 if (split != active) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001116 handled_.push_back(active);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +00001117 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001118 RemoveIntervalAndPotentialOtherHalf(&active_, it);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001119 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001120 break;
1121 }
1122 }
1123
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001124 // NOTE: Retrieve end() on each iteration because we're removing elements in the loop body.
1125 for (auto it = inactive_.begin(); it != inactive_.end(); ) {
1126 LiveInterval* inactive = *it;
1127 bool erased = false;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001128 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -07001129 if (!current->IsSplit() && !inactive->IsFixed()) {
1130 // Neither current nor inactive are fixed.
1131 // Thanks to SSA, a non-split interval starting in a hole of an
1132 // inactive interval should never intersect with that inactive interval.
1133 // Only if it's not fixed though, because fixed intervals don't come from SSA.
1134 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001135 } else {
1136 size_t next_intersection = inactive->FirstIntersectionWith(current);
1137 if (next_intersection != kNoLifetime) {
1138 if (inactive->IsFixed()) {
1139 LiveInterval* split = Split(current, next_intersection);
1140 DCHECK_NE(split, current);
1141 AddSorted(unhandled_, split);
1142 } else {
1143 // Split at the start of `current`, which will lead to splitting
1144 // at the end of the lifetime hole of `inactive`.
1145 LiveInterval* split = Split(inactive, current->GetStart());
1146 // If it's inactive, it must start before the current interval.
1147 DCHECK_NE(split, inactive);
1148 it = RemoveIntervalAndPotentialOtherHalf(&inactive_, it);
1149 erased = true;
1150 handled_.push_back(inactive);
1151 AddSorted(unhandled_, split);
Nicolas Geoffray5b168de2015-03-27 10:27:22 +00001152 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001153 }
1154 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001155 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001156 // If we have erased the element, `it` already points to the next element.
1157 // Otherwise we need to move to the next element.
1158 if (!erased) {
1159 ++it;
1160 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001161 }
1162
1163 return true;
1164 }
1165}
1166
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001167void RegisterAllocator::AddSorted(ArenaVector<LiveInterval*>* array, LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +01001168 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001169 size_t insert_at = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001170 for (size_t i = array->size(); i > 0; --i) {
1171 LiveInterval* current = (*array)[i - 1u];
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001172 // High intervals must be processed right after their low equivalent.
1173 if (current->StartsAfter(interval) && !current->IsHighInterval()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001174 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001175 break;
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001176 } else if ((current->GetStart() == interval->GetStart()) && current->IsSlowPathSafepoint()) {
1177 // Ensure the slow path interval is the last to be processed at its location: we want the
1178 // interval to know all live registers at this location.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001179 DCHECK(i == 1 || (*array)[i - 2u]->StartsAfter(current));
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001180 insert_at = i;
1181 break;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001182 }
1183 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001184
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001185 // Insert the high interval before the low, to ensure the low is processed before.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001186 auto insert_pos = array->begin() + insert_at;
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001187 if (interval->HasHighInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001188 array->insert(insert_pos, { interval->GetHighInterval(), interval });
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001189 } else if (interval->HasLowInterval()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001190 array->insert(insert_pos, { interval, interval->GetLowInterval() });
1191 } else {
1192 array->insert(insert_pos, interval);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001193 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001194}
1195
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001196LiveInterval* RegisterAllocator::SplitBetween(LiveInterval* interval, size_t from, size_t to) {
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001197 HBasicBlock* block_from = liveness_.GetBlockFromPosition(from / 2);
1198 HBasicBlock* block_to = liveness_.GetBlockFromPosition(to / 2);
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001199 DCHECK(block_from != nullptr);
1200 DCHECK(block_to != nullptr);
1201
1202 // Both locations are in the same block. We split at the given location.
1203 if (block_from == block_to) {
1204 return Split(interval, to);
1205 }
1206
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001207 /*
1208 * Non-linear control flow will force moves at every branch instruction to the new location.
1209 * To avoid having all branches doing the moves, we find the next non-linear position and
1210 * split the interval at this position. Take the following example (block number is the linear
1211 * order position):
1212 *
1213 * B1
1214 * / \
1215 * B2 B3
1216 * \ /
1217 * B4
1218 *
1219 * B2 needs to split an interval, whose next use is in B4. If we were to split at the
1220 * beginning of B4, B3 would need to do a move between B3 and B4 to ensure the interval
1221 * is now in the correct location. It makes performance worst if the interval is spilled
1222 * and both B2 and B3 need to reload it before entering B4.
1223 *
1224 * By splitting at B3, we give a chance to the register allocator to allocate the
1225 * interval to the same register as in B1, and therefore avoid doing any
1226 * moves in B3.
1227 */
1228 if (block_from->GetDominator() != nullptr) {
Vladimir Marko60584552015-09-03 13:35:12 +00001229 for (HBasicBlock* dominated : block_from->GetDominator()->GetDominatedBlocks()) {
1230 size_t position = dominated->GetLifetimeStart();
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001231 if ((position > from) && (block_to->GetLifetimeStart() > position)) {
1232 // Even if we found a better block, we continue iterating in case
1233 // a dominated block is closer.
1234 // Note that dominated blocks are not sorted in liveness order.
Vladimir Marko60584552015-09-03 13:35:12 +00001235 block_to = dominated;
Nicolas Geoffrayfbda5f32015-04-29 14:16:00 +01001236 DCHECK_NE(block_to, block_from);
1237 }
1238 }
1239 }
1240
Nicolas Geoffray8cbab3c2015-04-23 15:14:36 +01001241 // If `to` is in a loop, find the outermost loop header which does not contain `from`.
1242 for (HLoopInformationOutwardIterator it(*block_to); !it.Done(); it.Advance()) {
1243 HBasicBlock* header = it.Current()->GetHeader();
1244 if (block_from->GetLifetimeStart() >= header->GetLifetimeStart()) {
1245 break;
1246 }
1247 block_to = header;
1248 }
1249
1250 // Split at the start of the found block, to piggy back on existing moves
1251 // due to resolution if non-linear control flow (see `ConnectSplitSiblings`).
1252 return Split(interval, block_to->GetLifetimeStart());
1253}
1254
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001255LiveInterval* RegisterAllocator::Split(LiveInterval* interval, size_t position) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001256 DCHECK_GE(position, interval->GetStart());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001257 DCHECK(!interval->IsDeadAt(position));
1258 if (position == interval->GetStart()) {
1259 // Spill slot will be allocated when handling `interval` again.
1260 interval->ClearRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001261 if (interval->HasHighInterval()) {
1262 interval->GetHighInterval()->ClearRegister();
1263 } else if (interval->HasLowInterval()) {
1264 interval->GetLowInterval()->ClearRegister();
1265 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001266 return interval;
1267 } else {
1268 LiveInterval* new_interval = interval->SplitAt(position);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001269 if (interval->HasHighInterval()) {
1270 LiveInterval* high = interval->GetHighInterval()->SplitAt(position);
1271 new_interval->SetHighInterval(high);
1272 high->SetLowInterval(new_interval);
1273 } else if (interval->HasLowInterval()) {
1274 LiveInterval* low = interval->GetLowInterval()->SplitAt(position);
1275 new_interval->SetLowInterval(low);
1276 low->SetHighInterval(new_interval);
1277 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001278 return new_interval;
1279 }
1280}
1281
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001282void RegisterAllocator::AllocateSpillSlotFor(LiveInterval* interval) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001283 if (interval->IsHighInterval()) {
Nicolas Geoffrayda2b2542015-08-06 19:56:45 -07001284 // The low interval already took care of allocating the spill slot.
1285 DCHECK(!interval->GetLowInterval()->HasRegister());
1286 DCHECK(interval->GetLowInterval()->GetParent()->HasSpillSlot());
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001287 return;
1288 }
1289
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001290 LiveInterval* parent = interval->GetParent();
1291
1292 // An instruction gets a spill slot for its entire lifetime. If the parent
1293 // of this interval already has a spill slot, there is nothing to do.
1294 if (parent->HasSpillSlot()) {
1295 return;
1296 }
1297
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001298 HInstruction* defined_by = parent->GetDefinedBy();
David Brazdil77a48ae2015-09-15 12:34:04 +00001299 DCHECK(!defined_by->IsPhi() || !defined_by->AsPhi()->IsCatchPhi());
1300
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001301 if (defined_by->IsParameterValue()) {
1302 // Parameters have their own stack slot.
1303 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
1304 return;
1305 }
1306
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001307 if (defined_by->IsCurrentMethod()) {
1308 parent->SetSpillSlot(0);
1309 return;
1310 }
1311
Nicolas Geoffray96f89a22014-07-11 10:57:49 +01001312 if (defined_by->IsConstant()) {
1313 // Constants don't need a spill slot.
1314 return;
1315 }
1316
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001317 ArenaVector<size_t>* spill_slots = nullptr;
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001318 switch (interval->GetType()) {
1319 case Primitive::kPrimDouble:
1320 spill_slots = &double_spill_slots_;
1321 break;
1322 case Primitive::kPrimLong:
1323 spill_slots = &long_spill_slots_;
1324 break;
1325 case Primitive::kPrimFloat:
1326 spill_slots = &float_spill_slots_;
1327 break;
1328 case Primitive::kPrimNot:
1329 case Primitive::kPrimInt:
1330 case Primitive::kPrimChar:
1331 case Primitive::kPrimByte:
1332 case Primitive::kPrimBoolean:
1333 case Primitive::kPrimShort:
1334 spill_slots = &int_spill_slots_;
1335 break;
1336 case Primitive::kPrimVoid:
1337 LOG(FATAL) << "Unexpected type for interval " << interval->GetType();
1338 }
1339
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001340 // Find an available spill slot.
1341 size_t slot = 0;
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001342 for (size_t e = spill_slots->size(); slot < e; ++slot) {
1343 if ((*spill_slots)[slot] <= parent->GetStart()
1344 && (slot == (e - 1) || (*spill_slots)[slot + 1] <= parent->GetStart())) {
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001345 break;
1346 }
1347 }
1348
David Brazdil77a48ae2015-09-15 12:34:04 +00001349 size_t end = interval->GetLastSibling()->GetEnd();
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001350 if (parent->NeedsTwoSpillSlots()) {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001351 if (slot + 2u > spill_slots->size()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001352 // We need a new spill slot.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001353 spill_slots->resize(slot + 2u, end);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001354 }
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001355 (*spill_slots)[slot] = end;
1356 (*spill_slots)[slot + 1] = end;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001357 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001358 if (slot == spill_slots->size()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001359 // We need a new spill slot.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001360 spill_slots->push_back(end);
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001361 } else {
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001362 (*spill_slots)[slot] = end;
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001363 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001364 }
1365
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001366 // Note that the exact spill slot location will be computed when we resolve,
1367 // that is when we know the number of spill slots for each type.
1368 parent->SetSpillSlot(slot);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001369}
1370
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001371static bool IsValidDestination(Location destination) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001372 return destination.IsRegister()
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001373 || destination.IsRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001374 || destination.IsFpuRegister()
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001375 || destination.IsFpuRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001376 || destination.IsStackSlot()
1377 || destination.IsDoubleStackSlot();
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001378}
1379
David Brazdil77a48ae2015-09-15 12:34:04 +00001380void RegisterAllocator::AllocateSpillSlotForCatchPhi(HPhi* phi) {
1381 LiveInterval* interval = phi->GetLiveInterval();
1382
1383 HInstruction* previous_phi = phi->GetPrevious();
1384 DCHECK(previous_phi == nullptr ||
1385 previous_phi->AsPhi()->GetRegNumber() <= phi->GetRegNumber())
1386 << "Phis expected to be sorted by vreg number, so that equivalent phis are adjacent.";
1387
1388 if (phi->IsVRegEquivalentOf(previous_phi)) {
1389 // This is an equivalent of the previous phi. We need to assign the same
1390 // catch phi slot.
1391 DCHECK(previous_phi->GetLiveInterval()->HasSpillSlot());
1392 interval->SetSpillSlot(previous_phi->GetLiveInterval()->GetSpillSlot());
1393 } else {
1394 // Allocate a new spill slot for this catch phi.
1395 // TODO: Reuse spill slots when intervals of phis from different catch
1396 // blocks do not overlap.
1397 interval->SetSpillSlot(catch_phi_spill_slots_);
1398 catch_phi_spill_slots_ += interval->NeedsTwoSpillSlots() ? 2 : 1;
1399 }
1400}
1401
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001402void RegisterAllocator::AddMove(HParallelMove* move,
1403 Location source,
1404 Location destination,
1405 HInstruction* instruction,
1406 Primitive::Type type) const {
1407 if (type == Primitive::kPrimLong
1408 && codegen_->ShouldSplitLongMoves()
1409 // The parallel move resolver knows how to deal with long constants.
1410 && !source.IsConstant()) {
Nicolas Geoffray90218252015-04-15 11:56:51 +01001411 move->AddMove(source.ToLow(), destination.ToLow(), Primitive::kPrimInt, instruction);
1412 move->AddMove(source.ToHigh(), destination.ToHigh(), Primitive::kPrimInt, nullptr);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001413 } else {
Nicolas Geoffray90218252015-04-15 11:56:51 +01001414 move->AddMove(source, destination, type, instruction);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001415 }
1416}
1417
1418void RegisterAllocator::AddInputMoveFor(HInstruction* input,
1419 HInstruction* user,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001420 Location source,
1421 Location destination) const {
1422 if (source.Equals(destination)) return;
1423
Roland Levillain476df552014-10-09 17:51:36 +01001424 DCHECK(!user->IsPhi());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001425
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001426 HInstruction* previous = user->GetPrevious();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001427 HParallelMove* move = nullptr;
1428 if (previous == nullptr
Roland Levillain476df552014-10-09 17:51:36 +01001429 || !previous->IsParallelMove()
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001430 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001431 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001432 move->SetLifetimePosition(user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001433 user->GetBlock()->InsertInstructionBefore(move, user);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001434 } else {
1435 move = previous->AsParallelMove();
1436 }
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001437 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001438 AddMove(move, source, destination, nullptr, input->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001439}
1440
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001441static bool IsInstructionStart(size_t position) {
1442 return (position & 1) == 0;
1443}
1444
1445static bool IsInstructionEnd(size_t position) {
1446 return (position & 1) == 1;
1447}
1448
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001449void RegisterAllocator::InsertParallelMoveAt(size_t position,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001450 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001451 Location source,
1452 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001453 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001454 if (source.Equals(destination)) return;
1455
1456 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001457 HParallelMove* move;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001458 if (at == nullptr) {
1459 if (IsInstructionStart(position)) {
1460 // Block boundary, don't do anything the connection of split siblings will handle it.
1461 return;
1462 } else {
1463 // Move must happen before the first instruction of the block.
1464 at = liveness_.GetInstructionFromPosition((position + 1) / 2);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001465 // Note that parallel moves may have already been inserted, so we explicitly
1466 // ask for the first instruction of the block: `GetInstructionFromPosition` does
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001467 // not contain the `HParallelMove` instructions.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001468 at = at->GetBlock()->GetFirstInstruction();
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001469
1470 if (at->GetLifetimePosition() < position) {
1471 // We may insert moves for split siblings and phi spills at the beginning of the block.
1472 // Since this is a different lifetime position, we need to go to the next instruction.
1473 DCHECK(at->IsParallelMove());
1474 at = at->GetNext();
1475 }
1476
Nicolas Geoffray59768572014-12-01 09:50:04 +00001477 if (at->GetLifetimePosition() != position) {
1478 DCHECK_GT(at->GetLifetimePosition(), position);
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001479 move = new (allocator_) HParallelMove(allocator_);
1480 move->SetLifetimePosition(position);
1481 at->GetBlock()->InsertInstructionBefore(move, at);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001482 } else {
1483 DCHECK(at->IsParallelMove());
1484 move = at->AsParallelMove();
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001485 }
1486 }
1487 } else if (IsInstructionEnd(position)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001488 // Move must happen after the instruction.
1489 DCHECK(!at->IsControlFlow());
1490 move = at->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001491 // This is a parallel move for connecting siblings in a same block. We need to
1492 // differentiate it with moves for connecting blocks, and input moves.
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001493 if (move == nullptr || move->GetLifetimePosition() > position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001494 move = new (allocator_) HParallelMove(allocator_);
1495 move->SetLifetimePosition(position);
1496 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
1497 }
1498 } else {
1499 // Move must happen before the instruction.
1500 HInstruction* previous = at->GetPrevious();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001501 if (previous == nullptr
1502 || !previous->IsParallelMove()
1503 || previous->GetLifetimePosition() != position) {
1504 // If the previous is a parallel move, then its position must be lower
1505 // than the given `position`: it was added just after the non-parallel
1506 // move instruction that precedes `instruction`.
1507 DCHECK(previous == nullptr
1508 || !previous->IsParallelMove()
1509 || previous->GetLifetimePosition() < position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001510 move = new (allocator_) HParallelMove(allocator_);
1511 move->SetLifetimePosition(position);
1512 at->GetBlock()->InsertInstructionBefore(move, at);
1513 } else {
1514 move = previous->AsParallelMove();
1515 }
1516 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001517 DCHECK_EQ(move->GetLifetimePosition(), position);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001518 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001519}
1520
1521void RegisterAllocator::InsertParallelMoveAtExitOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001522 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001523 Location source,
1524 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001525 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001526 if (source.Equals(destination)) return;
1527
David Brazdil77a48ae2015-09-15 12:34:04 +00001528 DCHECK_EQ(block->NumberOfNormalSuccessors(), 1u);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001529 HInstruction* last = block->GetLastInstruction();
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001530 // We insert moves at exit for phi predecessors and connecting blocks.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001531 // A block ending with an if or a packed switch cannot branch to a block
1532 // with phis because we do not allow critical edges. It can also not connect
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001533 // a split interval between two blocks: the move has to happen in the successor.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001534 DCHECK(!last->IsIf() && !last->IsPackedSwitch());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001535 HInstruction* previous = last->GetPrevious();
1536 HParallelMove* move;
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001537 // This is a parallel move for connecting blocks. We need to differentiate
1538 // it with moves for connecting siblings in a same block, and output moves.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001539 size_t position = last->GetLifetimePosition();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001540 if (previous == nullptr || !previous->IsParallelMove()
Nicolas Geoffray59768572014-12-01 09:50:04 +00001541 || previous->AsParallelMove()->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001542 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001543 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001544 block->InsertInstructionBefore(move, last);
1545 } else {
1546 move = previous->AsParallelMove();
1547 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001548 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001549}
1550
1551void RegisterAllocator::InsertParallelMoveAtEntryOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001552 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001553 Location source,
1554 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001555 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001556 if (source.Equals(destination)) return;
1557
1558 HInstruction* first = block->GetFirstInstruction();
1559 HParallelMove* move = first->AsParallelMove();
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001560 size_t position = block->GetLifetimeStart();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001561 // This is a parallel move for connecting blocks. We need to differentiate
1562 // it with moves for connecting siblings in a same block, and input moves.
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001563 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001564 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001565 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001566 block->InsertInstructionBefore(move, first);
1567 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001568 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001569}
1570
1571void RegisterAllocator::InsertMoveAfter(HInstruction* instruction,
1572 Location source,
1573 Location destination) const {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001574 DCHECK(IsValidDestination(destination)) << destination;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001575 if (source.Equals(destination)) return;
1576
Roland Levillain476df552014-10-09 17:51:36 +01001577 if (instruction->IsPhi()) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001578 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001579 return;
1580 }
1581
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001582 size_t position = instruction->GetLifetimePosition() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001583 HParallelMove* move = instruction->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001584 // This is a parallel move for moving the output of an instruction. We need
1585 // to differentiate with input moves, moves for connecting siblings in a
1586 // and moves for connecting blocks.
1587 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001588 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001589 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001590 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
1591 }
Nicolas Geoffray234d69d2015-03-09 10:28:50 +00001592 AddMove(move, source, destination, instruction, instruction->GetType());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001593}
1594
1595void RegisterAllocator::ConnectSiblings(LiveInterval* interval) {
1596 LiveInterval* current = interval;
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001597 if (current->HasSpillSlot()
1598 && current->HasRegister()
1599 // Currently, we spill unconditionnally the current method in the code generators.
1600 && !interval->GetDefinedBy()->IsCurrentMethod()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001601 // We spill eagerly, so move must be at definition.
1602 InsertMoveAfter(interval->GetDefinedBy(),
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001603 interval->ToLocation(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001604 interval->NeedsTwoSpillSlots()
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001605 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
1606 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001607 }
1608 UsePosition* use = current->GetFirstUse();
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001609 UsePosition* env_use = current->GetFirstEnvironmentUse();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001610
1611 // Walk over all siblings, updating locations of use positions, and
1612 // connecting them when they are adjacent.
1613 do {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001614 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001615
1616 // Walk over all uses covered by this interval, and update the location
1617 // information.
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001618
1619 LiveRange* range = current->GetFirstRange();
1620 while (range != nullptr) {
Nicolas Geoffray57902602015-04-21 14:28:41 +01001621 while (use != nullptr && use->GetPosition() < range->GetStart()) {
1622 DCHECK(use->IsSynthesized());
1623 use = use->GetNext();
1624 }
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001625 while (use != nullptr && use->GetPosition() <= range->GetEnd()) {
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001626 DCHECK(!use->GetIsEnvironment());
David Brazdil3fc992f2015-04-16 18:31:55 +01001627 DCHECK(current->CoversSlow(use->GetPosition()) || (use->GetPosition() == range->GetEnd()));
Nicolas Geoffray57902602015-04-21 14:28:41 +01001628 if (!use->IsSynthesized()) {
1629 LocationSummary* locations = use->GetUser()->GetLocations();
1630 Location expected_location = locations->InAt(use->GetInputIndex());
1631 // The expected (actual) location may be invalid in case the input is unused. Currently
1632 // this only happens for intrinsics.
1633 if (expected_location.IsValid()) {
1634 if (expected_location.IsUnallocated()) {
1635 locations->SetInAt(use->GetInputIndex(), source);
1636 } else if (!expected_location.IsConstant()) {
1637 AddInputMoveFor(interval->GetDefinedBy(), use->GetUser(), source, expected_location);
1638 }
1639 } else {
1640 DCHECK(use->GetUser()->IsInvoke());
1641 DCHECK(use->GetUser()->AsInvoke()->GetIntrinsic() != Intrinsics::kNone);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001642 }
1643 }
1644 use = use->GetNext();
1645 }
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001646
1647 // Walk over the environment uses, and update their locations.
1648 while (env_use != nullptr && env_use->GetPosition() < range->GetStart()) {
1649 env_use = env_use->GetNext();
1650 }
1651
1652 while (env_use != nullptr && env_use->GetPosition() <= range->GetEnd()) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001653 DCHECK(current->CoversSlow(env_use->GetPosition())
1654 || (env_use->GetPosition() == range->GetEnd()));
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001655 HEnvironment* environment = env_use->GetEnvironment();
Nicolas Geoffray0a23d742015-05-07 11:57:35 +01001656 environment->SetLocationAt(env_use->GetInputIndex(), source);
Nicolas Geoffray4ed947a2015-04-27 16:58:06 +01001657 env_use = env_use->GetNext();
1658 }
1659
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001660 range = range->GetNext();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001661 }
1662
1663 // If the next interval starts just after this one, and has a register,
1664 // insert a move.
1665 LiveInterval* next_sibling = current->GetNextSibling();
1666 if (next_sibling != nullptr
1667 && next_sibling->HasRegister()
1668 && current->GetEnd() == next_sibling->GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001669 Location destination = next_sibling->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001670 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001671 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001672
Nicolas Geoffray43af7282015-04-16 13:01:01 +01001673 for (SafepointPosition* safepoint_position = current->GetFirstSafepoint();
1674 safepoint_position != nullptr;
1675 safepoint_position = safepoint_position->GetNext()) {
David Brazdil3fc992f2015-04-16 18:31:55 +01001676 DCHECK(current->CoversSlow(safepoint_position->GetPosition()));
Nicolas Geoffray39468442014-09-02 15:17:15 +01001677
Nicolas Geoffray5588e582015-04-14 14:10:59 +01001678 LocationSummary* locations = safepoint_position->GetLocations();
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001679 if ((current->GetType() == Primitive::kPrimNot) && current->GetParent()->HasSpillSlot()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001680 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
1681 }
1682
1683 switch (source.GetKind()) {
1684 case Location::kRegister: {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001685 locations->AddLiveRegister(source);
Nicolas Geoffray98893962015-01-21 12:32:32 +00001686 if (kIsDebugBuild && locations->OnlyCallsOnSlowPath()) {
1687 DCHECK_LE(locations->GetNumberOfLiveRegisters(),
1688 maximum_number_of_live_core_registers_ +
1689 maximum_number_of_live_fp_registers_);
1690 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001691 if (current->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001692 locations->SetRegisterBit(source.reg());
Nicolas Geoffray39468442014-09-02 15:17:15 +01001693 }
1694 break;
1695 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001696 case Location::kFpuRegister: {
1697 locations->AddLiveRegister(source);
1698 break;
1699 }
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +00001700
1701 case Location::kRegisterPair:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001702 case Location::kFpuRegisterPair: {
1703 locations->AddLiveRegister(source.ToLow());
1704 locations->AddLiveRegister(source.ToHigh());
1705 break;
1706 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001707 case Location::kStackSlot: // Fall-through
1708 case Location::kDoubleStackSlot: // Fall-through
1709 case Location::kConstant: {
1710 // Nothing to do.
1711 break;
1712 }
1713 default: {
1714 LOG(FATAL) << "Unexpected location for object";
1715 }
1716 }
1717 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001718 current = next_sibling;
1719 } while (current != nullptr);
Nicolas Geoffrayd8126be2015-03-27 10:22:41 +00001720
Nicolas Geoffray57902602015-04-21 14:28:41 +01001721 if (kIsDebugBuild) {
1722 // Following uses can only be synthesized uses.
1723 while (use != nullptr) {
1724 DCHECK(use->IsSynthesized());
1725 use = use->GetNext();
1726 }
1727 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001728}
1729
1730void RegisterAllocator::ConnectSplitSiblings(LiveInterval* interval,
1731 HBasicBlock* from,
1732 HBasicBlock* to) const {
1733 if (interval->GetNextSibling() == nullptr) {
1734 // Nothing to connect. The whole range was allocated to the same location.
1735 return;
1736 }
1737
David Brazdil241a4862015-04-16 17:59:03 +01001738 // Find the intervals that cover `from` and `to`.
1739 LiveInterval* destination = interval->GetSiblingAt(to->GetLifetimeStart());
1740 LiveInterval* source = interval->GetSiblingAt(from->GetLifetimeEnd() - 1);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001741
1742 if (destination == source) {
1743 // Interval was not split.
1744 return;
1745 }
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +01001746 DCHECK(destination != nullptr && source != nullptr);
1747
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001748 if (!destination->HasRegister()) {
1749 // Values are eagerly spilled. Spill slot already contains appropriate value.
1750 return;
1751 }
1752
1753 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
1754 // we need to put the moves at the entry of `to`.
David Brazdil77a48ae2015-09-15 12:34:04 +00001755 if (from->NumberOfNormalSuccessors() == 1) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001756 InsertParallelMoveAtExitOf(from,
1757 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001758 source->ToLocation(),
1759 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001760 } else {
Vladimir Marko60584552015-09-03 13:35:12 +00001761 DCHECK_EQ(to->GetPredecessors().size(), 1u);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001762 InsertParallelMoveAtEntryOf(to,
1763 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001764 source->ToLocation(),
1765 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001766 }
1767}
1768
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001769void RegisterAllocator::Resolve() {
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001770 codegen_->InitializeCodeGeneration(GetNumberOfSpillSlots(),
Nicolas Geoffray4c204ba2015-02-03 15:12:35 +00001771 maximum_number_of_live_core_registers_,
1772 maximum_number_of_live_fp_registers_,
1773 reserved_out_slots_,
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001774 codegen_->GetGraph()->GetLinearOrder());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001775
1776 // Adjust the Out Location of instructions.
1777 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
1778 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1779 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1780 LiveInterval* current = instruction->GetLiveInterval();
1781 LocationSummary* locations = instruction->GetLocations();
1782 Location location = locations->Out();
Roland Levillain476df552014-10-09 17:51:36 +01001783 if (instruction->IsParameterValue()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001784 // Now that we know the frame size, adjust the parameter's location.
1785 if (location.IsStackSlot()) {
1786 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1787 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001788 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001789 } else if (location.IsDoubleStackSlot()) {
1790 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1791 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001792 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001793 } else if (current->HasSpillSlot()) {
1794 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
1795 }
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001796 } else if (instruction->IsCurrentMethod()) {
1797 // The current method is always at offset 0.
1798 DCHECK(!current->HasSpillSlot() || (current->GetSpillSlot() == 0));
David Brazdil77a48ae2015-09-15 12:34:04 +00001799 } else if (instruction->IsPhi() && instruction->AsPhi()->IsCatchPhi()) {
1800 DCHECK(current->HasSpillSlot());
1801 size_t slot = current->GetSpillSlot()
1802 + GetNumberOfSpillSlots()
1803 + reserved_out_slots_
1804 - catch_phi_spill_slots_;
1805 current->SetSpillSlot(slot * kVRegSize);
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001806 } else if (current->HasSpillSlot()) {
1807 // Adjust the stack slot, now that we know the number of them for each type.
1808 // The way this implementation lays out the stack is the following:
David Brazdil77a48ae2015-09-15 12:34:04 +00001809 // [parameter slots ]
1810 // [catch phi spill slots ]
1811 // [double spill slots ]
1812 // [long spill slots ]
1813 // [float spill slots ]
1814 // [int/ref values ]
1815 // [maximum out values ] (number of arguments for calls)
1816 // [art method ].
1817 size_t slot = current->GetSpillSlot();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001818 switch (current->GetType()) {
1819 case Primitive::kPrimDouble:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001820 slot += long_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001821 FALLTHROUGH_INTENDED;
1822 case Primitive::kPrimLong:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001823 slot += float_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001824 FALLTHROUGH_INTENDED;
1825 case Primitive::kPrimFloat:
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001826 slot += int_spill_slots_.size();
Nicolas Geoffray776b3182015-02-23 14:14:57 +00001827 FALLTHROUGH_INTENDED;
1828 case Primitive::kPrimNot:
1829 case Primitive::kPrimInt:
1830 case Primitive::kPrimChar:
1831 case Primitive::kPrimByte:
1832 case Primitive::kPrimBoolean:
1833 case Primitive::kPrimShort:
1834 slot += reserved_out_slots_;
1835 break;
1836 case Primitive::kPrimVoid:
1837 LOG(FATAL) << "Unexpected type for interval " << current->GetType();
1838 }
1839 current->SetSpillSlot(slot * kVRegSize);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001840 }
1841
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001842 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001843
1844 if (location.IsUnallocated()) {
1845 if (location.GetPolicy() == Location::kSameAsFirstInput) {
Calin Juravled0d48522014-11-04 16:40:20 +00001846 if (locations->InAt(0).IsUnallocated()) {
1847 locations->SetInAt(0, source);
1848 } else {
1849 DCHECK(locations->InAt(0).Equals(source));
1850 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001851 }
Nicolas Geoffray829280c2015-01-28 10:20:37 +00001852 locations->UpdateOut(source);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001853 } else {
1854 DCHECK(source.Equals(location));
1855 }
1856 }
1857
1858 // Connect siblings.
1859 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1860 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1861 ConnectSiblings(instruction->GetLiveInterval());
1862 }
1863
1864 // Resolve non-linear control flow across branches. Order does not matter.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001865 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001866 HBasicBlock* block = it.Current();
David Brazdil77a48ae2015-09-15 12:34:04 +00001867 if (block->IsCatchBlock()) {
1868 // Instructions live at the top of catch blocks were forced to spill.
1869 if (kIsDebugBuild) {
1870 BitVector* live = liveness_.GetLiveInSet(*block);
1871 for (uint32_t idx : live->Indexes()) {
1872 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
1873 DCHECK(!interval->GetSiblingAt(block->GetLifetimeStart())->HasRegister());
1874 }
1875 }
1876 } else {
1877 BitVector* live = liveness_.GetLiveInSet(*block);
1878 for (uint32_t idx : live->Indexes()) {
1879 LiveInterval* interval = liveness_.GetInstructionFromSsaIndex(idx)->GetLiveInterval();
1880 for (HBasicBlock* predecessor : block->GetPredecessors()) {
1881 ConnectSplitSiblings(interval, predecessor, block);
1882 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001883 }
1884 }
1885 }
1886
1887 // Resolve phi inputs. Order does not matter.
Nicolas Geoffray0d9f17d2015-04-15 14:17:44 +01001888 for (HLinearOrderIterator it(*codegen_->GetGraph()); !it.Done(); it.Advance()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001889 HBasicBlock* current = it.Current();
David Brazdil77a48ae2015-09-15 12:34:04 +00001890 if (current->IsCatchBlock()) {
1891 // Catch phi values are set at runtime by the exception delivery mechanism.
1892 } else {
1893 for (HInstructionIterator inst_it(current->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
1894 HInstruction* phi = inst_it.Current();
1895 for (size_t i = 0, e = current->GetPredecessors().size(); i < e; ++i) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001896 HBasicBlock* predecessor = current->GetPredecessors()[i];
David Brazdil77a48ae2015-09-15 12:34:04 +00001897 DCHECK_EQ(predecessor->NumberOfNormalSuccessors(), 1u);
1898 HInstruction* input = phi->InputAt(i);
1899 Location source = input->GetLiveInterval()->GetLocationAt(
1900 predecessor->GetLifetimeEnd() - 1);
1901 Location destination = phi->GetLiveInterval()->ToLocation();
1902 InsertParallelMoveAtExitOf(predecessor, phi, source, destination);
1903 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001904 }
1905 }
1906 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001907
1908 // Assign temp locations.
Vladimir Marko2aaa4b52015-09-17 17:03:26 +01001909 for (LiveInterval* temp : temp_intervals_) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001910 if (temp->IsHighInterval()) {
1911 // High intervals can be skipped, they are already handled by the low interval.
1912 continue;
1913 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001914 HInstruction* at = liveness_.GetTempUser(temp);
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001915 size_t temp_index = liveness_.GetTempIndex(temp);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001916 LocationSummary* locations = at->GetLocations();
Roland Levillain5368c212014-11-27 15:03:41 +00001917 switch (temp->GetType()) {
1918 case Primitive::kPrimInt:
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001919 locations->SetTempAt(temp_index, Location::RegisterLocation(temp->GetRegister()));
Roland Levillain5368c212014-11-27 15:03:41 +00001920 break;
1921
1922 case Primitive::kPrimDouble:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001923 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
1924 Location location = Location::FpuRegisterPairLocation(
1925 temp->GetRegister(), temp->GetHighInterval()->GetRegister());
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001926 locations->SetTempAt(temp_index, location);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001927 } else {
Nicolas Geoffrayf01d3442015-03-27 17:15:49 +00001928 locations->SetTempAt(temp_index, Location::FpuRegisterLocation(temp->GetRegister()));
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001929 }
Roland Levillain5368c212014-11-27 15:03:41 +00001930 break;
1931
1932 default:
1933 LOG(FATAL) << "Unexpected type for temporary location "
1934 << temp->GetType();
1935 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001936 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001937}
1938
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001939} // namespace art