blob: 26c1e3fc27d64bc25187e1a478be883c4d1aa2e7 [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
Ian Rogersc7dd2952014-10-21 23:31:19 -070019#include <sstream>
20
Ian Rogerse77493c2014-08-20 15:08:45 -070021#include "base/bit_vector-inl.h"
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010022#include "code_generator.h"
23#include "ssa_liveness_analysis.h"
24
25namespace art {
26
27static constexpr size_t kMaxLifetimePosition = -1;
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010028static constexpr size_t kDefaultNumberOfSpillSlots = 4;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010029
Nicolas Geoffray840e5462015-01-07 16:01:24 +000030// For simplicity, we implement register pairs as (reg, reg + 1).
31// Note that this is a requirement for double registers on ARM, since we
32// allocate SRegister.
33static int GetHighForLowRegister(int reg) { return reg + 1; }
34static bool IsLowRegister(int reg) { return (reg & 1) == 0; }
35
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010036RegisterAllocator::RegisterAllocator(ArenaAllocator* allocator,
37 CodeGenerator* codegen,
38 const SsaLivenessAnalysis& liveness)
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010039 : allocator_(allocator),
40 codegen_(codegen),
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010041 liveness_(liveness),
Nicolas Geoffray39468442014-09-02 15:17:15 +010042 unhandled_core_intervals_(allocator, 0),
43 unhandled_fp_intervals_(allocator, 0),
44 unhandled_(nullptr),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010045 handled_(allocator, 0),
46 active_(allocator, 0),
47 inactive_(allocator, 0),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010048 physical_core_register_intervals_(allocator, codegen->GetNumberOfCoreRegisters()),
49 physical_fp_register_intervals_(allocator, codegen->GetNumberOfFloatingPointRegisters()),
Nicolas Geoffray39468442014-09-02 15:17:15 +010050 temp_intervals_(allocator, 4),
Nicolas Geoffray31d76b42014-06-09 15:02:22 +010051 spill_slots_(allocator, kDefaultNumberOfSpillSlots),
Nicolas Geoffray39468442014-09-02 15:17:15 +010052 safepoints_(allocator, 0),
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010053 processing_core_registers_(false),
54 number_of_registers_(-1),
55 registers_array_(nullptr),
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010056 blocked_core_registers_(codegen->GetBlockedCoreRegisters()),
57 blocked_fp_registers_(codegen->GetBlockedFloatingPointRegisters()),
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +010058 reserved_out_slots_(0),
59 maximum_number_of_live_registers_(0) {
Nicolas Geoffray71175b72014-10-09 22:13:55 +010060 codegen->SetupBlockedRegisters();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010061 physical_core_register_intervals_.SetSize(codegen->GetNumberOfCoreRegisters());
62 physical_fp_register_intervals_.SetSize(codegen->GetNumberOfFloatingPointRegisters());
Nicolas Geoffray39468442014-09-02 15:17:15 +010063 // Always reserve for the current method and the graph's max out registers.
64 // TODO: compute it instead.
65 reserved_out_slots_ = 1 + codegen->GetGraph()->GetMaximumNumberOfOutVRegs();
Nicolas Geoffraya7062e02014-05-22 12:50:17 +010066}
67
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010068bool RegisterAllocator::CanAllocateRegistersFor(const HGraph& graph,
69 InstructionSet instruction_set) {
70 if (!Supports(instruction_set)) {
71 return false;
72 }
Alexandre Rames3e69f162014-12-10 10:36:50 +000073 if (instruction_set == kArm64 || instruction_set == kX86_64) {
74 return true;
75 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010076 for (size_t i = 0, e = graph.GetBlocks().Size(); i < e; ++i) {
77 for (HInstructionIterator it(graph.GetBlocks().Get(i)->GetInstructions());
78 !it.Done();
79 it.Advance()) {
80 HInstruction* current = it.Current();
Nicolas Geoffray840e5462015-01-07 16:01:24 +000081 if (instruction_set == kX86) {
82 if (current->GetType() == Primitive::kPrimLong ||
83 current->GetType() == Primitive::kPrimFloat ||
84 current->GetType() == Primitive::kPrimDouble) {
85 return false;
86 }
87 } else if (instruction_set == kArm || instruction_set == kThumb2) {
88 if (current->GetType() == Primitive::kPrimLong) {
89 return false;
90 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +010091 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +010092 }
93 }
94 return true;
95}
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;
117 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
118 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
135void RegisterAllocator::BlockRegister(Location location,
136 size_t start,
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100137 size_t end) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100138 int reg = location.reg();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100139 DCHECK(location.IsRegister() || location.IsFpuRegister());
140 LiveInterval* interval = location.IsRegister()
141 ? physical_core_register_intervals_.Get(reg)
142 : physical_fp_register_intervals_.Get(reg);
143 Primitive::Type type = location.IsRegister()
144 ? Primitive::kPrimInt
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000145 : Primitive::kPrimFloat;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100146 if (interval == nullptr) {
147 interval = LiveInterval::MakeFixedInterval(allocator_, reg, type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100148 if (location.IsRegister()) {
149 physical_core_register_intervals_.Put(reg, interval);
150 } else {
151 physical_fp_register_intervals_.Put(reg, interval);
152 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100153 }
154 DCHECK(interval->GetRegister() == reg);
155 interval->AddRange(start, end);
156}
157
158void RegisterAllocator::AllocateRegistersInternal() {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100159 // Iterate post-order, to ensure the list is sorted, and the last added interval
160 // is the one with the lowest start position.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100161 for (HLinearPostOrderIterator it(liveness_); !it.Done(); it.Advance()) {
162 HBasicBlock* block = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800163 for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
164 back_it.Advance()) {
165 ProcessInstruction(back_it.Current());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100166 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800167 for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
168 ProcessInstruction(inst_it.Current());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100169 }
170 }
171
Nicolas Geoffray39468442014-09-02 15:17:15 +0100172 number_of_registers_ = codegen_->GetNumberOfCoreRegisters();
173 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_);
174 processing_core_registers_ = true;
175 unhandled_ = &unhandled_core_intervals_;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100176 for (size_t i = 0, e = physical_core_register_intervals_.Size(); i < e; ++i) {
177 LiveInterval* fixed = physical_core_register_intervals_.Get(i);
178 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700179 // Fixed interval is added to inactive_ instead of unhandled_.
180 // It's also the only type of inactive interval whose start position
181 // can be after the current interval during linear scan.
182 // Fixed interval is never split and never moves to unhandled_.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100183 inactive_.Add(fixed);
184 }
185 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100186 LinearScan();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100187
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100188 size_t saved_maximum_number_of_live_registers = maximum_number_of_live_registers_;
189 maximum_number_of_live_registers_ = 0;
190
Nicolas Geoffray39468442014-09-02 15:17:15 +0100191 inactive_.Reset();
192 active_.Reset();
193 handled_.Reset();
194
195 number_of_registers_ = codegen_->GetNumberOfFloatingPointRegisters();
196 registers_array_ = allocator_->AllocArray<size_t>(number_of_registers_);
197 processing_core_registers_ = false;
198 unhandled_ = &unhandled_fp_intervals_;
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100199 for (size_t i = 0, e = physical_fp_register_intervals_.Size(); i < e; ++i) {
200 LiveInterval* fixed = physical_fp_register_intervals_.Get(i);
201 if (fixed != nullptr) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700202 // Fixed interval is added to inactive_ instead of unhandled_.
203 // It's also the only type of inactive interval whose start position
204 // can be after the current interval during linear scan.
205 // Fixed interval is never split and never moves to unhandled_.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100206 inactive_.Add(fixed);
207 }
208 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100209 LinearScan();
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100210 maximum_number_of_live_registers_ += saved_maximum_number_of_live_registers;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100211}
212
213void RegisterAllocator::ProcessInstruction(HInstruction* instruction) {
214 LocationSummary* locations = instruction->GetLocations();
215 size_t position = instruction->GetLifetimePosition();
216
217 if (locations == nullptr) return;
218
219 // Create synthesized intervals for temporaries.
220 for (size_t i = 0; i < locations->GetTempCount(); ++i) {
221 Location temp = locations->GetTemp(i);
Nicolas Geoffray52839d12014-11-07 17:47:25 +0000222 if (temp.IsRegister() || temp.IsFpuRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100223 BlockRegister(temp, position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100224 } else {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100225 DCHECK(temp.IsUnallocated());
Roland Levillain5368c212014-11-27 15:03:41 +0000226 switch (temp.GetPolicy()) {
227 case Location::kRequiresRegister: {
228 LiveInterval* interval =
229 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimInt);
230 temp_intervals_.Add(interval);
231 interval->AddRange(position, position + 1);
232 unhandled_core_intervals_.Add(interval);
233 break;
234 }
235
236 case Location::kRequiresFpuRegister: {
237 LiveInterval* interval =
238 LiveInterval::MakeTempInterval(allocator_, Primitive::kPrimDouble);
239 temp_intervals_.Add(interval);
240 interval->AddRange(position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000241 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
242 interval->AddHighInterval(true);
243 LiveInterval* high = interval->GetHighInterval();
244 temp_intervals_.Add(high);
245 unhandled_fp_intervals_.Add(high);
246 }
Roland Levillain5368c212014-11-27 15:03:41 +0000247 unhandled_fp_intervals_.Add(interval);
248 break;
249 }
250
251 default:
252 LOG(FATAL) << "Unexpected policy for temporary location "
253 << temp.GetPolicy();
254 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100255 }
256 }
257
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100258 bool core_register = (instruction->GetType() != Primitive::kPrimDouble)
259 && (instruction->GetType() != Primitive::kPrimFloat);
260
Nicolas Geoffray39468442014-09-02 15:17:15 +0100261 if (locations->CanCall()) {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100262 if (!instruction->IsSuspendCheck()) {
263 codegen_->MarkNotLeaf();
264 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100265 safepoints_.Add(instruction);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100266 if (locations->OnlyCallsOnSlowPath()) {
267 // We add a synthesized range at this position to record the live registers
268 // at this position. Ideally, we could just update the safepoints when locations
269 // are updated, but we currently need to know the full stack size before updating
270 // locations (because of parameters and the fact that we don't have a frame pointer).
271 // And knowing the full stack size requires to know the maximum number of live
272 // registers at calls in slow paths.
273 // By adding the following interval in the algorithm, we can compute this
274 // maximum before updating locations.
275 LiveInterval* interval = LiveInterval::MakeSlowPathInterval(allocator_, instruction);
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000276 interval->AddRange(position, position + 1);
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000277 AddSorted(&unhandled_core_intervals_, interval);
278 AddSorted(&unhandled_fp_intervals_, interval);
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +0100279 }
280 }
281
282 if (locations->WillCall()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100283 // Block all registers.
284 for (size_t i = 0; i < codegen_->GetNumberOfCoreRegisters(); ++i) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100285 BlockRegister(Location::RegisterLocation(i),
Nicolas Geoffray39468442014-09-02 15:17:15 +0100286 position,
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100287 position + 1);
288 }
289 for (size_t i = 0; i < codegen_->GetNumberOfFloatingPointRegisters(); ++i) {
290 BlockRegister(Location::FpuRegisterLocation(i),
291 position,
292 position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100293 }
294 }
295
296 for (size_t i = 0; i < instruction->InputCount(); ++i) {
297 Location input = locations->InAt(i);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100298 if (input.IsRegister() || input.IsFpuRegister()) {
299 BlockRegister(input, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000300 } else if (input.IsPair()) {
301 BlockRegister(input.ToLow(), position, position + 1);
302 BlockRegister(input.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100303 }
304 }
305
Nicolas Geoffray39468442014-09-02 15:17:15 +0100306 LiveInterval* current = instruction->GetLiveInterval();
307 if (current == nullptr) return;
308
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100309 GrowableArray<LiveInterval*>& unhandled = core_register
310 ? unhandled_core_intervals_
311 : unhandled_fp_intervals_;
312
Nicolas Geoffray76905622014-09-25 14:39:26 +0100313 DCHECK(unhandled.IsEmpty() || current->StartsBeforeOrAt(unhandled.Peek()));
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000314
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000315 if (codegen_->NeedsTwoRegisters(current->GetType())) {
316 current->AddHighInterval();
317 }
318
Nicolas Geoffray39468442014-09-02 15:17:15 +0100319 // Some instructions define their output in fixed register/stack slot. We need
320 // to ensure we know these locations before doing register allocation. For a
321 // given register, we create an interval that covers these locations. The register
322 // will be unavailable at these locations when trying to allocate one for an
323 // interval.
324 //
325 // The backwards walking ensures the ranges are ordered on increasing start positions.
326 Location output = locations->Out();
Calin Juravled0d48522014-11-04 16:40:20 +0000327 if (output.IsUnallocated() && output.GetPolicy() == Location::kSameAsFirstInput) {
328 Location first = locations->InAt(0);
329 if (first.IsRegister() || first.IsFpuRegister()) {
330 current->SetFrom(position + 1);
331 current->SetRegister(first.reg());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000332 } else if (first.IsPair()) {
333 current->SetFrom(position + 1);
334 current->SetRegister(first.low());
335 LiveInterval* high = current->GetHighInterval();
336 high->SetRegister(first.high());
337 high->SetFrom(position + 1);
Calin Juravled0d48522014-11-04 16:40:20 +0000338 }
339 } else if (output.IsRegister() || output.IsFpuRegister()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100340 // Shift the interval's start by one to account for the blocked register.
341 current->SetFrom(position + 1);
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +0100342 current->SetRegister(output.reg());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100343 BlockRegister(output, position, position + 1);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000344 } else if (output.IsPair()) {
345 current->SetFrom(position + 1);
346 current->SetRegister(output.low());
347 LiveInterval* high = current->GetHighInterval();
348 high->SetRegister(output.high());
349 high->SetFrom(position + 1);
350 BlockRegister(output.ToLow(), position, position + 1);
351 BlockRegister(output.ToHigh(), position, position + 1);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100352 } else if (output.IsStackSlot() || output.IsDoubleStackSlot()) {
353 current->SetSpillSlot(output.GetStackIndex());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000354 } else {
355 DCHECK(output.IsUnallocated() || output.IsConstant());
Nicolas Geoffray39468442014-09-02 15:17:15 +0100356 }
357
358 // If needed, add interval to the list of unhandled intervals.
359 if (current->HasSpillSlot() || instruction->IsConstant()) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100360 // Split just before first register use.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100361 size_t first_register_use = current->FirstRegisterUse();
362 if (first_register_use != kNoLifetime) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100363 LiveInterval* split = Split(current, first_register_use - 1);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000364 // Don't add directly to `unhandled`, it needs to be sorted and the start
Nicolas Geoffray39468442014-09-02 15:17:15 +0100365 // of this new interval might be after intervals already in the list.
366 AddSorted(&unhandled, split);
367 } else {
368 // Nothing to do, we won't allocate a register for this value.
369 }
370 } else {
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000371 // Don't add directly to `unhandled`, temp or safepoint intervals
372 // for this instruction may have been added, and those can be
373 // processed first.
374 AddSorted(&unhandled, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100375 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100376}
377
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100378class AllRangesIterator : public ValueObject {
379 public:
380 explicit AllRangesIterator(LiveInterval* interval)
381 : current_interval_(interval),
382 current_range_(interval->GetFirstRange()) {}
383
384 bool Done() const { return current_interval_ == nullptr; }
385 LiveRange* CurrentRange() const { return current_range_; }
386 LiveInterval* CurrentInterval() const { return current_interval_; }
387
388 void Advance() {
389 current_range_ = current_range_->GetNext();
390 if (current_range_ == nullptr) {
391 current_interval_ = current_interval_->GetNextSibling();
392 if (current_interval_ != nullptr) {
393 current_range_ = current_interval_->GetFirstRange();
394 }
395 }
396 }
397
398 private:
399 LiveInterval* current_interval_;
400 LiveRange* current_range_;
401
402 DISALLOW_COPY_AND_ASSIGN(AllRangesIterator);
403};
404
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100405bool RegisterAllocator::ValidateInternal(bool log_fatal_on_failure) const {
406 // To simplify unit testing, we eagerly create the array of intervals, and
407 // call the helper method.
408 GrowableArray<LiveInterval*> intervals(allocator_, 0);
409 for (size_t i = 0; i < liveness_.GetNumberOfSsaValues(); ++i) {
410 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
411 if (ShouldProcess(processing_core_registers_, instruction->GetLiveInterval())) {
412 intervals.Add(instruction->GetLiveInterval());
413 }
414 }
415
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100416 if (processing_core_registers_) {
417 for (size_t i = 0, e = physical_core_register_intervals_.Size(); i < e; ++i) {
418 LiveInterval* fixed = physical_core_register_intervals_.Get(i);
419 if (fixed != nullptr) {
420 intervals.Add(fixed);
421 }
422 }
423 } else {
424 for (size_t i = 0, e = physical_fp_register_intervals_.Size(); i < e; ++i) {
425 LiveInterval* fixed = physical_fp_register_intervals_.Get(i);
426 if (fixed != nullptr) {
427 intervals.Add(fixed);
428 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100429 }
430 }
431
Nicolas Geoffray39468442014-09-02 15:17:15 +0100432 for (size_t i = 0, e = temp_intervals_.Size(); i < e; ++i) {
433 LiveInterval* temp = temp_intervals_.Get(i);
434 if (ShouldProcess(processing_core_registers_, temp)) {
435 intervals.Add(temp);
436 }
437 }
438
439 return ValidateIntervals(intervals, spill_slots_.Size(), reserved_out_slots_, *codegen_,
440 allocator_, processing_core_registers_, log_fatal_on_failure);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100441}
442
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100443bool RegisterAllocator::ValidateIntervals(const GrowableArray<LiveInterval*>& intervals,
444 size_t number_of_spill_slots,
Nicolas Geoffray39468442014-09-02 15:17:15 +0100445 size_t number_of_out_slots,
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100446 const CodeGenerator& codegen,
447 ArenaAllocator* allocator,
448 bool processing_core_registers,
449 bool log_fatal_on_failure) {
450 size_t number_of_registers = processing_core_registers
451 ? codegen.GetNumberOfCoreRegisters()
452 : codegen.GetNumberOfFloatingPointRegisters();
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100453 GrowableArray<ArenaBitVector*> liveness_of_values(
454 allocator, number_of_registers + number_of_spill_slots);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100455
456 // Allocate a bit vector per register. A live interval that has a register
457 // allocated will populate the associated bit vector based on its live ranges.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100458 for (size_t i = 0; i < number_of_registers + number_of_spill_slots; ++i) {
459 liveness_of_values.Add(new (allocator) ArenaBitVector(allocator, 0, true));
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100460 }
461
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100462 for (size_t i = 0, e = intervals.Size(); i < e; ++i) {
463 for (AllRangesIterator it(intervals.Get(i)); !it.Done(); it.Advance()) {
464 LiveInterval* current = it.CurrentInterval();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100465 HInstruction* defined_by = current->GetParent()->GetDefinedBy();
466 if (current->GetParent()->HasSpillSlot()
467 // Parameters have their own stack slot.
468 && !(defined_by != nullptr && defined_by->IsParameterValue())) {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100469 BitVector* liveness_of_spill_slot = liveness_of_values.Get(number_of_registers
470 + current->GetParent()->GetSpillSlot() / kVRegSize
471 - number_of_out_slots);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100472 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
473 if (liveness_of_spill_slot->IsBitSet(j)) {
474 if (log_fatal_on_failure) {
475 std::ostringstream message;
476 message << "Spill slot conflict at " << j;
477 LOG(FATAL) << message.str();
478 } else {
479 return false;
480 }
481 } else {
482 liveness_of_spill_slot->SetBit(j);
483 }
484 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100485 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100486
487 if (current->HasRegister()) {
488 BitVector* liveness_of_register = liveness_of_values.Get(current->GetRegister());
489 for (size_t j = it.CurrentRange()->GetStart(); j < it.CurrentRange()->GetEnd(); ++j) {
490 if (liveness_of_register->IsBitSet(j)) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100491 if (log_fatal_on_failure) {
492 std::ostringstream message;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100493 message << "Register conflict at " << j << " ";
494 if (defined_by != nullptr) {
495 message << "(" << defined_by->DebugName() << ")";
496 }
497 message << "for ";
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100498 if (processing_core_registers) {
499 codegen.DumpCoreRegister(message, current->GetRegister());
500 } else {
501 codegen.DumpFloatingPointRegister(message, current->GetRegister());
502 }
503 LOG(FATAL) << message.str();
504 } else {
505 return false;
506 }
507 } else {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100508 liveness_of_register->SetBit(j);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100509 }
510 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100511 }
512 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100513 }
514 return true;
515}
516
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100517void RegisterAllocator::DumpInterval(std::ostream& stream, LiveInterval* interval) const {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100518 interval->Dump(stream);
519 stream << ": ";
520 if (interval->HasRegister()) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100521 if (interval->IsFloatingPoint()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100522 codegen_->DumpFloatingPointRegister(stream, interval->GetRegister());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100523 } else {
524 codegen_->DumpCoreRegister(stream, interval->GetRegister());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100525 }
526 } else {
527 stream << "spilled";
528 }
529 stream << std::endl;
530}
531
Mingyao Yang296bd602014-10-06 16:47:28 -0700532void RegisterAllocator::DumpAllIntervals(std::ostream& stream) const {
533 stream << "inactive: " << std::endl;
534 for (size_t i = 0; i < inactive_.Size(); i ++) {
535 DumpInterval(stream, inactive_.Get(i));
536 }
537 stream << "active: " << std::endl;
538 for (size_t i = 0; i < active_.Size(); i ++) {
539 DumpInterval(stream, active_.Get(i));
540 }
541 stream << "unhandled: " << std::endl;
542 auto unhandled = (unhandled_ != nullptr) ?
543 unhandled_ : &unhandled_core_intervals_;
544 for (size_t i = 0; i < unhandled->Size(); i ++) {
545 DumpInterval(stream, unhandled->Get(i));
546 }
547 stream << "handled: " << std::endl;
548 for (size_t i = 0; i < handled_.Size(); i ++) {
549 DumpInterval(stream, handled_.Get(i));
550 }
551}
552
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100553// By the book implementation of a linear scan register allocator.
554void RegisterAllocator::LinearScan() {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100555 while (!unhandled_->IsEmpty()) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100556 // (1) Remove interval with the lowest start position from unhandled.
Nicolas Geoffray39468442014-09-02 15:17:15 +0100557 LiveInterval* current = unhandled_->Pop();
558 DCHECK(!current->IsFixed() && !current->HasSpillSlot());
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100559 DCHECK(unhandled_->IsEmpty() || unhandled_->Peek()->GetStart() >= current->GetStart());
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000560 DCHECK(!current->IsLowInterval() || unhandled_->Peek()->IsHighInterval());
Nicolas Geoffray87d03762014-11-19 15:17:56 +0000561
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100562 size_t position = current->GetStart();
563
Mingyao Yang296bd602014-10-06 16:47:28 -0700564 // Remember the inactive_ size here since the ones moved to inactive_ from
565 // active_ below shouldn't need to be re-checked.
566 size_t inactive_intervals_to_handle = inactive_.Size();
567
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100568 // (2) Remove currently active intervals that are dead at this position.
569 // Move active intervals that have a lifetime hole at this position
570 // to inactive.
571 for (size_t i = 0; i < active_.Size(); ++i) {
572 LiveInterval* interval = active_.Get(i);
573 if (interval->IsDeadAt(position)) {
574 active_.Delete(interval);
575 --i;
576 handled_.Add(interval);
577 } else if (!interval->Covers(position)) {
578 active_.Delete(interval);
579 --i;
580 inactive_.Add(interval);
581 }
582 }
583
584 // (3) Remove currently inactive intervals that are dead at this position.
585 // Move inactive intervals that cover this position to active.
Mingyao Yang296bd602014-10-06 16:47:28 -0700586 for (size_t i = 0; i < inactive_intervals_to_handle; ++i) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100587 LiveInterval* interval = inactive_.Get(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700588 DCHECK(interval->GetStart() < position || interval->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100589 if (interval->IsDeadAt(position)) {
590 inactive_.Delete(interval);
591 --i;
Mingyao Yang296bd602014-10-06 16:47:28 -0700592 --inactive_intervals_to_handle;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100593 handled_.Add(interval);
594 } else if (interval->Covers(position)) {
595 inactive_.Delete(interval);
596 --i;
Mingyao Yang296bd602014-10-06 16:47:28 -0700597 --inactive_intervals_to_handle;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100598 active_.Add(interval);
599 }
600 }
601
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000602 if (current->IsSlowPathSafepoint()) {
603 // Synthesized interval to record the maximum number of live registers
604 // at safepoints. No need to allocate a register for it.
605 maximum_number_of_live_registers_ =
606 std::max(maximum_number_of_live_registers_, active_.Size());
607 DCHECK(unhandled_->IsEmpty() || unhandled_->Peek()->GetStart() > current->GetStart());
608 continue;
609 }
610
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000611 if (current->IsHighInterval() && !current->GetLowInterval()->HasRegister()) {
612 DCHECK(!current->HasRegister());
613 // Allocating the low part was unsucessful. The splitted interval for the high part
614 // will be handled next (it is in the `unhandled_` list).
615 continue;
616 }
617
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100618 // (4) Try to find an available register.
619 bool success = TryAllocateFreeReg(current);
620
621 // (5) If no register could be found, we need to spill.
622 if (!success) {
623 success = AllocateBlockedReg(current);
624 }
625
626 // (6) If the interval had a register allocated, add it to the list of active
627 // intervals.
628 if (success) {
629 active_.Add(current);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000630 if (current->HasHighInterval() && !current->GetHighInterval()->HasRegister()) {
631 current->GetHighInterval()->SetRegister(GetHighForLowRegister(current->GetRegister()));
632 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100633 }
634 }
635}
636
637// Find a free register. If multiple are found, pick the register that
638// is free the longest.
639bool RegisterAllocator::TryAllocateFreeReg(LiveInterval* current) {
640 size_t* free_until = registers_array_;
641
642 // First set all registers to be free.
643 for (size_t i = 0; i < number_of_registers_; ++i) {
644 free_until[i] = kMaxLifetimePosition;
645 }
646
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100647 // For each active interval, set its register to not free.
648 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
649 LiveInterval* interval = active_.Get(i);
650 DCHECK(interval->HasRegister());
651 free_until[interval->GetRegister()] = 0;
652 }
653
Mingyao Yang296bd602014-10-06 16:47:28 -0700654 // For each inactive interval, set its register to be free until
655 // the next intersection with `current`.
656 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
657 LiveInterval* inactive = inactive_.Get(i);
658 // Temp/Slow-path-safepoint interval has no holes.
659 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
660 if (!current->IsSplit() && !inactive->IsFixed()) {
661 // Neither current nor inactive are fixed.
662 // Thanks to SSA, a non-split interval starting in a hole of an
663 // inactive interval should never intersect with that inactive interval.
664 // Only if it's not fixed though, because fixed intervals don't come from SSA.
665 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
666 continue;
667 }
668
669 DCHECK(inactive->HasRegister());
670 if (free_until[inactive->GetRegister()] == 0) {
671 // Already used by some active interval. No need to intersect.
672 continue;
673 }
674 size_t next_intersection = inactive->FirstIntersectionWith(current);
675 if (next_intersection != kNoLifetime) {
676 free_until[inactive->GetRegister()] =
677 std::min(free_until[inactive->GetRegister()], next_intersection);
678 }
679 }
680
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100681 int reg = -1;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100682 if (current->HasRegister()) {
683 // Some instructions have a fixed register output.
684 reg = current->GetRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000685 if (free_until[reg] == 0) {
686 DCHECK(current->IsHighInterval());
687 // AllocateBlockedReg will spill the holder of the register.
688 return false;
689 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100690 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000691 DCHECK(!current->IsHighInterval());
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100692 int hint = current->FindFirstRegisterHint(free_until);
693 if (hint != kNoRegister) {
694 DCHECK(!IsBlocked(hint));
695 reg = hint;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000696 } else if (current->IsLowInterval()) {
697 reg = FindAvailableRegisterPair(free_until);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100698 } else {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000699 reg = FindAvailableRegister(free_until);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100700 }
701 }
702
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000703 DCHECK_NE(reg, -1);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100704 // If we could not find a register, we need to spill.
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000705 if (free_until[reg] == 0) {
706 return false;
707 }
708
709 if (current->IsLowInterval() && free_until[GetHighForLowRegister(reg)] == 0) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100710 return false;
711 }
712
713 current->SetRegister(reg);
714 if (!current->IsDeadAt(free_until[reg])) {
715 // If the register is only available for a subset of live ranges
716 // covered by `current`, split `current` at the position where
717 // the register is not available anymore.
718 LiveInterval* split = Split(current, free_until[reg]);
719 DCHECK(split != nullptr);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100720 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100721 }
722 return true;
723}
724
725bool RegisterAllocator::IsBlocked(int reg) const {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100726 return processing_core_registers_
727 ? blocked_core_registers_[reg]
728 : blocked_fp_registers_[reg];
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100729}
730
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000731int RegisterAllocator::FindAvailableRegisterPair(size_t* next_use) const {
732 int reg = -1;
733 // Pick the register pair that is used the last.
734 for (size_t i = 0; i < number_of_registers_; ++i) {
735 if (IsBlocked(i)) continue;
736 if (!IsLowRegister(i)) continue;
737 int high_register = GetHighForLowRegister(i);
738 if (IsBlocked(high_register)) continue;
739 int existing_high_register = GetHighForLowRegister(reg);
740 if ((reg == -1) || (next_use[i] >= next_use[reg]
741 && next_use[high_register] >= next_use[existing_high_register])) {
742 reg = i;
743 if (next_use[i] == kMaxLifetimePosition
744 && next_use[high_register] == kMaxLifetimePosition) {
745 break;
746 }
747 }
748 }
749 return reg;
750}
751
752int RegisterAllocator::FindAvailableRegister(size_t* next_use) const {
753 int reg = -1;
754 // Pick the register that is used the last.
755 for (size_t i = 0; i < number_of_registers_; ++i) {
756 if (IsBlocked(i)) continue;
757 if (reg == -1 || next_use[i] > next_use[reg]) {
758 reg = i;
759 if (next_use[i] == kMaxLifetimePosition) break;
760 }
761 }
762 return reg;
763}
764
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100765// Find the register that is used the last, and spill the interval
766// that holds it. If the first use of `current` is after that register
767// we spill `current` instead.
768bool RegisterAllocator::AllocateBlockedReg(LiveInterval* current) {
769 size_t first_register_use = current->FirstRegisterUse();
Nicolas Geoffray412f10c2014-06-19 10:00:34 +0100770 if (first_register_use == kNoLifetime) {
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100771 AllocateSpillSlotFor(current);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100772 return false;
773 }
774
775 // First set all registers as not being used.
776 size_t* next_use = registers_array_;
777 for (size_t i = 0; i < number_of_registers_; ++i) {
778 next_use[i] = kMaxLifetimePosition;
779 }
780
781 // For each active interval, find the next use of its register after the
782 // start of current.
783 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
784 LiveInterval* active = active_.Get(i);
785 DCHECK(active->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100786 if (active->IsFixed()) {
787 next_use[active->GetRegister()] = current->GetStart();
788 } else {
789 size_t use = active->FirstRegisterUseAfter(current->GetStart());
790 if (use != kNoLifetime) {
791 next_use[active->GetRegister()] = use;
792 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100793 }
794 }
795
796 // For each inactive interval, find the next use of its register after the
797 // start of current.
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100798 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
799 LiveInterval* inactive = inactive_.Get(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700800 // Temp/Slow-path-safepoint interval has no holes.
801 DCHECK(!inactive->IsTemp() && !inactive->IsSlowPathSafepoint());
802 if (!current->IsSplit() && !inactive->IsFixed()) {
803 // Neither current nor inactive are fixed.
804 // Thanks to SSA, a non-split interval starting in a hole of an
805 // inactive interval should never intersect with that inactive interval.
806 // Only if it's not fixed though, because fixed intervals don't come from SSA.
807 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
808 continue;
809 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100810 DCHECK(inactive->HasRegister());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100811 size_t next_intersection = inactive->FirstIntersectionWith(current);
812 if (next_intersection != kNoLifetime) {
813 if (inactive->IsFixed()) {
814 next_use[inactive->GetRegister()] =
815 std::min(next_intersection, next_use[inactive->GetRegister()]);
816 } else {
817 size_t use = inactive->FirstRegisterUseAfter(current->GetStart());
818 if (use != kNoLifetime) {
819 next_use[inactive->GetRegister()] = std::min(use, next_use[inactive->GetRegister()]);
820 }
821 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100822 }
823 }
824
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100825 int reg = -1;
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000826 if (current->HasRegister()) {
827 DCHECK(current->IsHighInterval());
828 reg = current->GetRegister();
829 } else if (current->IsLowInterval()) {
830 reg = FindAvailableRegisterPair(next_use);
831 } else {
832 DCHECK(!current->IsHighInterval());
833 reg = FindAvailableRegister(next_use);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100834 }
835
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000836 if ((first_register_use >= next_use[reg])
837 || (current->IsLowInterval() && first_register_use >= next_use[GetHighForLowRegister(reg)])) {
838 DCHECK(!current->IsHighInterval());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100839 // If the first use of that instruction is after the last use of the found
840 // register, we split this interval just before its first register use.
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100841 AllocateSpillSlotFor(current);
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100842 LiveInterval* split = Split(current, first_register_use - 1);
843 DCHECK_NE(current, split) << "There is not enough registers available for "
844 << split->GetParent()->GetDefinedBy()->DebugName();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100845 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100846 return false;
847 } else {
848 // Use this register and spill the active and inactives interval that
849 // have that register.
850 current->SetRegister(reg);
851
852 for (size_t i = 0, e = active_.Size(); i < e; ++i) {
853 LiveInterval* active = active_.Get(i);
854 if (active->GetRegister() == reg) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100855 DCHECK(!active->IsFixed());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100856 LiveInterval* split = Split(active, current->GetStart());
857 active_.DeleteAt(i);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +0000858 if (split != active) {
859 handled_.Add(active);
860 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100861 AddSorted(unhandled_, split);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100862 break;
863 }
864 }
865
Mingyao Yang296bd602014-10-06 16:47:28 -0700866 for (size_t i = 0, e = inactive_.Size(); i < e; ++i) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100867 LiveInterval* inactive = inactive_.Get(i);
868 if (inactive->GetRegister() == reg) {
Mingyao Yang296bd602014-10-06 16:47:28 -0700869 if (!current->IsSplit() && !inactive->IsFixed()) {
870 // Neither current nor inactive are fixed.
871 // Thanks to SSA, a non-split interval starting in a hole of an
872 // inactive interval should never intersect with that inactive interval.
873 // Only if it's not fixed though, because fixed intervals don't come from SSA.
874 DCHECK_EQ(inactive->FirstIntersectionWith(current), kNoLifetime);
875 continue;
876 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100877 size_t next_intersection = inactive->FirstIntersectionWith(current);
878 if (next_intersection != kNoLifetime) {
879 if (inactive->IsFixed()) {
880 LiveInterval* split = Split(current, next_intersection);
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +0000881 DCHECK_NE(split, current);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100882 AddSorted(unhandled_, split);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100883 } else {
Nicolas Geoffraydd8f8872015-01-15 15:37:37 +0000884 // Split at the start of `current`, which will lead to splitting
885 // at the end of the lifetime hole of `inactive`.
886 LiveInterval* split = Split(inactive, current->GetStart());
887 // If it's inactive, it must start before the current interval.
888 DCHECK_NE(split, inactive);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100889 inactive_.DeleteAt(i);
Mingyao Yang296bd602014-10-06 16:47:28 -0700890 --i;
891 --e;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100892 handled_.Add(inactive);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100893 AddSorted(unhandled_, split);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100894 }
895 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100896 }
897 }
898
899 return true;
900 }
901}
902
Nicolas Geoffray39468442014-09-02 15:17:15 +0100903void RegisterAllocator::AddSorted(GrowableArray<LiveInterval*>* array, LiveInterval* interval) {
Nicolas Geoffrayc8147a72014-10-21 16:06:20 +0100904 DCHECK(!interval->IsFixed() && !interval->HasSpillSlot());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100905 size_t insert_at = 0;
Nicolas Geoffray39468442014-09-02 15:17:15 +0100906 for (size_t i = array->Size(); i > 0; --i) {
907 LiveInterval* current = array->Get(i - 1);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100908 if (current->StartsAfter(interval)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100909 insert_at = i;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100910 break;
Nicolas Geoffrayacd03392014-11-26 15:46:52 +0000911 } else if ((current->GetStart() == interval->GetStart()) && current->IsSlowPathSafepoint()) {
912 // Ensure the slow path interval is the last to be processed at its location: we want the
913 // interval to know all live registers at this location.
914 DCHECK(i == 1 || array->Get(i - 2)->StartsAfter(current));
915 insert_at = i;
916 break;
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100917 }
918 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000919
Nicolas Geoffray39468442014-09-02 15:17:15 +0100920 array->InsertAt(insert_at, interval);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000921 // Insert the high interval before the low, to ensure the low is processed before.
922 if (interval->HasHighInterval()) {
923 array->InsertAt(insert_at, interval->GetHighInterval());
924 } else if (interval->HasLowInterval()) {
925 array->InsertAt(insert_at + 1, interval->GetLowInterval());
926 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100927}
928
929LiveInterval* RegisterAllocator::Split(LiveInterval* interval, size_t position) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000930 DCHECK_GE(position, interval->GetStart());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100931 DCHECK(!interval->IsDeadAt(position));
932 if (position == interval->GetStart()) {
933 // Spill slot will be allocated when handling `interval` again.
934 interval->ClearRegister();
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000935 if (interval->HasHighInterval()) {
936 interval->GetHighInterval()->ClearRegister();
937 } else if (interval->HasLowInterval()) {
938 interval->GetLowInterval()->ClearRegister();
939 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100940 return interval;
941 } else {
942 LiveInterval* new_interval = interval->SplitAt(position);
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000943 if (interval->HasHighInterval()) {
944 LiveInterval* high = interval->GetHighInterval()->SplitAt(position);
945 new_interval->SetHighInterval(high);
946 high->SetLowInterval(new_interval);
947 } else if (interval->HasLowInterval()) {
948 LiveInterval* low = interval->GetLowInterval()->SplitAt(position);
949 new_interval->SetLowInterval(low);
950 low->SetHighInterval(new_interval);
951 }
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100952 return new_interval;
953 }
954}
955
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100956void RegisterAllocator::AllocateSpillSlotFor(LiveInterval* interval) {
Nicolas Geoffray840e5462015-01-07 16:01:24 +0000957 if (interval->IsHighInterval()) {
958 // The low interval will contain the spill slot.
959 return;
960 }
961
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100962 LiveInterval* parent = interval->GetParent();
963
964 // An instruction gets a spill slot for its entire lifetime. If the parent
965 // of this interval already has a spill slot, there is nothing to do.
966 if (parent->HasSpillSlot()) {
967 return;
968 }
969
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +0100970 HInstruction* defined_by = parent->GetDefinedBy();
971 if (defined_by->IsParameterValue()) {
972 // Parameters have their own stack slot.
973 parent->SetSpillSlot(codegen_->GetStackSlotOfParameter(defined_by->AsParameterValue()));
974 return;
975 }
976
Nicolas Geoffray96f89a22014-07-11 10:57:49 +0100977 if (defined_by->IsConstant()) {
978 // Constants don't need a spill slot.
979 return;
980 }
981
Nicolas Geoffray31d76b42014-06-09 15:02:22 +0100982 LiveInterval* last_sibling = interval;
983 while (last_sibling->GetNextSibling() != nullptr) {
984 last_sibling = last_sibling->GetNextSibling();
985 }
986 size_t end = last_sibling->GetEnd();
987
Nicolas Geoffray412f10c2014-06-19 10:00:34 +0100988 // Find an available spill slot.
989 size_t slot = 0;
990 for (size_t e = spill_slots_.Size(); slot < e; ++slot) {
991 // We check if it is less rather than less or equal because the parallel move
992 // resolver does not work when a single spill slot needs to be exchanged with
993 // a double spill slot. The strict comparison avoids needing to exchange these
994 // locations at the same lifetime position.
995 if (spill_slots_.Get(slot) < parent->GetStart()
996 && (slot == (e - 1) || spill_slots_.Get(slot + 1) < parent->GetStart())) {
997 break;
998 }
999 }
1000
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001001 if (parent->NeedsTwoSpillSlots()) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001002 if (slot == spill_slots_.Size()) {
1003 // We need a new spill slot.
1004 spill_slots_.Add(end);
1005 spill_slots_.Add(end);
1006 } else if (slot == spill_slots_.Size() - 1) {
1007 spill_slots_.Put(slot, end);
1008 spill_slots_.Add(end);
1009 } else {
1010 spill_slots_.Put(slot, end);
1011 spill_slots_.Put(slot + 1, end);
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001012 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001013 } else {
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001014 if (slot == spill_slots_.Size()) {
1015 // We need a new spill slot.
1016 spill_slots_.Add(end);
1017 } else {
1018 spill_slots_.Put(slot, end);
1019 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001020 }
1021
Nicolas Geoffray39468442014-09-02 15:17:15 +01001022 parent->SetSpillSlot((slot + reserved_out_slots_) * kVRegSize);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001023}
1024
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001025static bool IsValidDestination(Location destination) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001026 return destination.IsRegister()
1027 || destination.IsFpuRegister()
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001028 || destination.IsFpuRegisterPair()
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001029 || destination.IsStackSlot()
1030 || destination.IsDoubleStackSlot();
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001031}
1032
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001033void RegisterAllocator::AddInputMoveFor(HInstruction* user,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001034 Location source,
1035 Location destination) const {
1036 if (source.Equals(destination)) return;
1037
Roland Levillain476df552014-10-09 17:51:36 +01001038 DCHECK(!user->IsPhi());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001039
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001040 HInstruction* previous = user->GetPrevious();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001041 HParallelMove* move = nullptr;
1042 if (previous == nullptr
Roland Levillain476df552014-10-09 17:51:36 +01001043 || !previous->IsParallelMove()
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001044 || previous->GetLifetimePosition() < user->GetLifetimePosition()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001045 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001046 move->SetLifetimePosition(user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001047 user->GetBlock()->InsertInstructionBefore(move, user);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001048 } else {
1049 move = previous->AsParallelMove();
1050 }
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001051 DCHECK_EQ(move->GetLifetimePosition(), user->GetLifetimePosition());
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001052 move->AddMove(new (allocator_) MoveOperands(source, destination, nullptr));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001053}
1054
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001055static bool IsInstructionStart(size_t position) {
1056 return (position & 1) == 0;
1057}
1058
1059static bool IsInstructionEnd(size_t position) {
1060 return (position & 1) == 1;
1061}
1062
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001063void RegisterAllocator::InsertParallelMoveAt(size_t position,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001064 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001065 Location source,
1066 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001067 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001068 if (source.Equals(destination)) return;
1069
1070 HInstruction* at = liveness_.GetInstructionFromPosition(position / 2);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001071 HParallelMove* move;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001072 if (at == nullptr) {
1073 if (IsInstructionStart(position)) {
1074 // Block boundary, don't do anything the connection of split siblings will handle it.
1075 return;
1076 } else {
1077 // Move must happen before the first instruction of the block.
1078 at = liveness_.GetInstructionFromPosition((position + 1) / 2);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001079 // Note that parallel moves may have already been inserted, so we explicitly
1080 // ask for the first instruction of the block: `GetInstructionFromPosition` does
1081 // not contain the moves.
1082 at = at->GetBlock()->GetFirstInstruction();
1083 if (at->GetLifetimePosition() != position) {
1084 DCHECK_GT(at->GetLifetimePosition(), position);
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001085 move = new (allocator_) HParallelMove(allocator_);
1086 move->SetLifetimePosition(position);
1087 at->GetBlock()->InsertInstructionBefore(move, at);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001088 } else {
1089 DCHECK(at->IsParallelMove());
1090 move = at->AsParallelMove();
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001091 }
1092 }
1093 } else if (IsInstructionEnd(position)) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001094 // Move must happen after the instruction.
1095 DCHECK(!at->IsControlFlow());
1096 move = at->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001097 // This is a parallel move for connecting siblings in a same block. We need to
1098 // differentiate it with moves for connecting blocks, and input moves.
Nicolas Geoffray8e3964b2014-10-17 11:06:38 +01001099 if (move == nullptr || move->GetLifetimePosition() > position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001100 move = new (allocator_) HParallelMove(allocator_);
1101 move->SetLifetimePosition(position);
1102 at->GetBlock()->InsertInstructionBefore(move, at->GetNext());
1103 }
1104 } else {
1105 // Move must happen before the instruction.
1106 HInstruction* previous = at->GetPrevious();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001107 if (previous == nullptr
1108 || !previous->IsParallelMove()
1109 || previous->GetLifetimePosition() != position) {
1110 // If the previous is a parallel move, then its position must be lower
1111 // than the given `position`: it was added just after the non-parallel
1112 // move instruction that precedes `instruction`.
1113 DCHECK(previous == nullptr
1114 || !previous->IsParallelMove()
1115 || previous->GetLifetimePosition() < position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001116 move = new (allocator_) HParallelMove(allocator_);
1117 move->SetLifetimePosition(position);
1118 at->GetBlock()->InsertInstructionBefore(move, at);
1119 } else {
1120 move = previous->AsParallelMove();
1121 }
1122 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001123 DCHECK_EQ(move->GetLifetimePosition(), position);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001124 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001125}
1126
1127void RegisterAllocator::InsertParallelMoveAtExitOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001128 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001129 Location source,
1130 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001131 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001132 if (source.Equals(destination)) return;
1133
1134 DCHECK_EQ(block->GetSuccessors().Size(), 1u);
1135 HInstruction* last = block->GetLastInstruction();
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001136 // We insert moves at exit for phi predecessors and connecting blocks.
1137 // A block ending with an if cannot branch to a block with phis because
1138 // we do not allow critical edges. It can also not connect
1139 // a split interval between two blocks: the move has to happen in the successor.
1140 DCHECK(!last->IsIf());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001141 HInstruction* previous = last->GetPrevious();
1142 HParallelMove* move;
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001143 // This is a parallel move for connecting blocks. We need to differentiate
1144 // it with moves for connecting siblings in a same block, and output moves.
Nicolas Geoffray59768572014-12-01 09:50:04 +00001145 size_t position = last->GetLifetimePosition();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001146 if (previous == nullptr || !previous->IsParallelMove()
Nicolas Geoffray59768572014-12-01 09:50:04 +00001147 || previous->AsParallelMove()->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001148 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffray59768572014-12-01 09:50:04 +00001149 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001150 block->InsertInstructionBefore(move, last);
1151 } else {
1152 move = previous->AsParallelMove();
1153 }
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001154 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001155}
1156
1157void RegisterAllocator::InsertParallelMoveAtEntryOf(HBasicBlock* block,
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001158 HInstruction* instruction,
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001159 Location source,
1160 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001161 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001162 if (source.Equals(destination)) return;
1163
1164 HInstruction* first = block->GetFirstInstruction();
1165 HParallelMove* move = first->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001166 // This is a parallel move for connecting blocks. We need to differentiate
1167 // it with moves for connecting siblings in a same block, and input moves.
1168 if (move == nullptr || move->GetLifetimePosition() != block->GetLifetimeStart()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001169 move = new (allocator_) HParallelMove(allocator_);
1170 move->SetLifetimePosition(block->GetLifetimeStart());
1171 block->InsertInstructionBefore(move, first);
1172 }
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001173 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001174}
1175
1176void RegisterAllocator::InsertMoveAfter(HInstruction* instruction,
1177 Location source,
1178 Location destination) const {
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001179 DCHECK(IsValidDestination(destination));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001180 if (source.Equals(destination)) return;
1181
Roland Levillain476df552014-10-09 17:51:36 +01001182 if (instruction->IsPhi()) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001183 InsertParallelMoveAtEntryOf(instruction->GetBlock(), instruction, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001184 return;
1185 }
1186
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001187 size_t position = instruction->GetLifetimePosition() + 1;
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001188 HParallelMove* move = instruction->GetNext()->AsParallelMove();
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001189 // This is a parallel move for moving the output of an instruction. We need
1190 // to differentiate with input moves, moves for connecting siblings in a
1191 // and moves for connecting blocks.
1192 if (move == nullptr || move->GetLifetimePosition() != position) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001193 move = new (allocator_) HParallelMove(allocator_);
Nicolas Geoffraye27f31a2014-06-12 17:53:14 +01001194 move->SetLifetimePosition(position);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001195 instruction->GetBlock()->InsertInstructionBefore(move, instruction->GetNext());
1196 }
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001197 move->AddMove(new (allocator_) MoveOperands(source, destination, instruction));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001198}
1199
1200void RegisterAllocator::ConnectSiblings(LiveInterval* interval) {
1201 LiveInterval* current = interval;
1202 if (current->HasSpillSlot() && current->HasRegister()) {
1203 // We spill eagerly, so move must be at definition.
1204 InsertMoveAfter(interval->GetDefinedBy(),
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001205 interval->ToLocation(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001206 interval->NeedsTwoSpillSlots()
Nicolas Geoffray412f10c2014-06-19 10:00:34 +01001207 ? Location::DoubleStackSlot(interval->GetParent()->GetSpillSlot())
1208 : Location::StackSlot(interval->GetParent()->GetSpillSlot()));
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001209 }
1210 UsePosition* use = current->GetFirstUse();
1211
1212 // Walk over all siblings, updating locations of use positions, and
1213 // connecting them when they are adjacent.
1214 do {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001215 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001216
1217 // Walk over all uses covered by this interval, and update the location
1218 // information.
1219 while (use != nullptr && use->GetPosition() <= current->GetEnd()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001220 LocationSummary* locations = use->GetUser()->GetLocations();
1221 if (use->GetIsEnvironment()) {
1222 locations->SetEnvironmentAt(use->GetInputIndex(), source);
1223 } else {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001224 Location expected_location = locations->InAt(use->GetInputIndex());
1225 if (expected_location.IsUnallocated()) {
1226 locations->SetInAt(use->GetInputIndex(), source);
Nicolas Geoffray2a877f32014-09-10 10:49:34 +01001227 } else if (!expected_location.IsConstant()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001228 AddInputMoveFor(use->GetUser(), source, expected_location);
1229 }
1230 }
1231 use = use->GetNext();
1232 }
1233
1234 // If the next interval starts just after this one, and has a register,
1235 // insert a move.
1236 LiveInterval* next_sibling = current->GetNextSibling();
1237 if (next_sibling != nullptr
1238 && next_sibling->HasRegister()
1239 && current->GetEnd() == next_sibling->GetStart()) {
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001240 Location destination = next_sibling->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001241 InsertParallelMoveAt(current->GetEnd(), interval->GetDefinedBy(), source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001242 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001243
1244 // At each safepoint, we record stack and register information.
1245 for (size_t i = 0, e = safepoints_.Size(); i < e; ++i) {
1246 HInstruction* safepoint = safepoints_.Get(i);
1247 size_t position = safepoint->GetLifetimePosition();
1248 LocationSummary* locations = safepoint->GetLocations();
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +00001249 if (!current->Covers(position)) {
1250 continue;
1251 }
1252 if (interval->GetStart() == position) {
1253 // The safepoint is for this instruction, so the location of the instruction
1254 // does not need to be saved.
1255 continue;
1256 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001257
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001258 if ((current->GetType() == Primitive::kPrimNot) && current->GetParent()->HasSpillSlot()) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001259 locations->SetStackBit(current->GetParent()->GetSpillSlot() / kVRegSize);
1260 }
1261
1262 switch (source.GetKind()) {
1263 case Location::kRegister: {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001264 locations->AddLiveRegister(source);
Nicolas Geoffray87d03762014-11-19 15:17:56 +00001265 DCHECK_LE(locations->GetNumberOfLiveRegisters(), maximum_number_of_live_registers_);
Nicolas Geoffrayacd03392014-11-26 15:46:52 +00001266
Nicolas Geoffray39468442014-09-02 15:17:15 +01001267 if (current->GetType() == Primitive::kPrimNot) {
Nicolas Geoffray56b9ee62014-10-09 11:47:51 +01001268 locations->SetRegisterBit(source.reg());
Nicolas Geoffray39468442014-09-02 15:17:15 +01001269 }
1270 break;
1271 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001272 case Location::kFpuRegister: {
1273 locations->AddLiveRegister(source);
1274 break;
1275 }
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001276 case Location::kFpuRegisterPair: {
1277 locations->AddLiveRegister(source.ToLow());
1278 locations->AddLiveRegister(source.ToHigh());
1279 break;
1280 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001281 case Location::kStackSlot: // Fall-through
1282 case Location::kDoubleStackSlot: // Fall-through
1283 case Location::kConstant: {
1284 // Nothing to do.
1285 break;
1286 }
1287 default: {
1288 LOG(FATAL) << "Unexpected location for object";
1289 }
1290 }
1291 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001292 current = next_sibling;
1293 } while (current != nullptr);
1294 DCHECK(use == nullptr);
1295}
1296
1297void RegisterAllocator::ConnectSplitSiblings(LiveInterval* interval,
1298 HBasicBlock* from,
1299 HBasicBlock* to) const {
1300 if (interval->GetNextSibling() == nullptr) {
1301 // Nothing to connect. The whole range was allocated to the same location.
1302 return;
1303 }
1304
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001305 // Intervals end at the lifetime end of a block. The decrement by one
1306 // ensures the `Cover` call will return true.
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001307 size_t from_position = from->GetLifetimeEnd() - 1;
Nicolas Geoffray46fbaab2014-11-26 18:30:23 +00001308 size_t to_position = to->GetLifetimeStart();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001309
1310 LiveInterval* destination = nullptr;
1311 LiveInterval* source = nullptr;
1312
1313 LiveInterval* current = interval;
1314
1315 // Check the intervals that cover `from` and `to`.
1316 while ((current != nullptr) && (source == nullptr || destination == nullptr)) {
1317 if (current->Covers(from_position)) {
1318 DCHECK(source == nullptr);
1319 source = current;
1320 }
1321 if (current->Covers(to_position)) {
1322 DCHECK(destination == nullptr);
1323 destination = current;
1324 }
1325
1326 current = current->GetNextSibling();
1327 }
1328
1329 if (destination == source) {
1330 // Interval was not split.
1331 return;
1332 }
1333
Nicolas Geoffray8ddb00c2014-09-29 12:00:40 +01001334 DCHECK(destination != nullptr && source != nullptr);
1335
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001336 if (!destination->HasRegister()) {
1337 // Values are eagerly spilled. Spill slot already contains appropriate value.
1338 return;
1339 }
1340
1341 // If `from` has only one successor, we can put the moves at the exit of it. Otherwise
1342 // we need to put the moves at the entry of `to`.
1343 if (from->GetSuccessors().Size() == 1) {
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001344 InsertParallelMoveAtExitOf(from,
1345 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001346 source->ToLocation(),
1347 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001348 } else {
1349 DCHECK_EQ(to->GetPredecessors().Size(), 1u);
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001350 InsertParallelMoveAtEntryOf(to,
1351 interval->GetParent()->GetDefinedBy(),
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001352 source->ToLocation(),
1353 destination->ToLocation());
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001354 }
1355}
1356
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001357void RegisterAllocator::Resolve() {
Nicolas Geoffray3bca0df2014-09-19 11:01:00 +01001358 codegen_->ComputeFrameSize(
1359 spill_slots_.Size(), maximum_number_of_live_registers_, reserved_out_slots_);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001360
1361 // Adjust the Out Location of instructions.
1362 // TODO: Use pointers of Location inside LiveInterval to avoid doing another iteration.
1363 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1364 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1365 LiveInterval* current = instruction->GetLiveInterval();
1366 LocationSummary* locations = instruction->GetLocations();
1367 Location location = locations->Out();
Roland Levillain476df552014-10-09 17:51:36 +01001368 if (instruction->IsParameterValue()) {
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001369 // Now that we know the frame size, adjust the parameter's location.
1370 if (location.IsStackSlot()) {
1371 location = Location::StackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1372 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001373 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001374 } else if (location.IsDoubleStackSlot()) {
1375 location = Location::DoubleStackSlot(location.GetStackIndex() + codegen_->GetFrameSize());
1376 current->SetSpillSlot(location.GetStackIndex());
Nicolas Geoffrayf43083d2014-11-07 10:48:10 +00001377 locations->UpdateOut(location);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001378 } else if (current->HasSpillSlot()) {
1379 current->SetSpillSlot(current->GetSpillSlot() + codegen_->GetFrameSize());
1380 }
1381 }
1382
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001383 Location source = current->ToLocation();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001384
1385 if (location.IsUnallocated()) {
1386 if (location.GetPolicy() == Location::kSameAsFirstInput) {
Calin Juravled0d48522014-11-04 16:40:20 +00001387 if (locations->InAt(0).IsUnallocated()) {
1388 locations->SetInAt(0, source);
1389 } else {
1390 DCHECK(locations->InAt(0).Equals(source));
1391 }
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001392 }
1393 locations->SetOut(source);
1394 } else {
1395 DCHECK(source.Equals(location));
1396 }
1397 }
1398
1399 // Connect siblings.
1400 for (size_t i = 0, e = liveness_.GetNumberOfSsaValues(); i < e; ++i) {
1401 HInstruction* instruction = liveness_.GetInstructionFromSsaIndex(i);
1402 ConnectSiblings(instruction->GetLiveInterval());
1403 }
1404
1405 // Resolve non-linear control flow across branches. Order does not matter.
1406 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
1407 HBasicBlock* block = it.Current();
1408 BitVector* live = liveness_.GetLiveInSet(*block);
1409 for (uint32_t idx : live->Indexes()) {
1410 HInstruction* current = liveness_.GetInstructionFromSsaIndex(idx);
1411 LiveInterval* interval = current->GetLiveInterval();
1412 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
1413 ConnectSplitSiblings(interval, block->GetPredecessors().Get(i), block);
1414 }
1415 }
1416 }
1417
1418 // Resolve phi inputs. Order does not matter.
1419 for (HLinearOrderIterator it(liveness_); !it.Done(); it.Advance()) {
1420 HBasicBlock* current = it.Current();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001421 for (HInstructionIterator inst_it(current->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
1422 HInstruction* phi = inst_it.Current();
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001423 for (size_t i = 0, e = current->GetPredecessors().Size(); i < e; ++i) {
1424 HBasicBlock* predecessor = current->GetPredecessors().Get(i);
1425 DCHECK_EQ(predecessor->GetSuccessors().Size(), 1u);
1426 HInstruction* input = phi->InputAt(i);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001427 Location source = input->GetLiveInterval()->GetLocationAt(
1428 predecessor->GetLifetimeEnd() - 1);
1429 Location destination = phi->GetLiveInterval()->ToLocation();
Nicolas Geoffray740475d2014-09-29 10:33:25 +01001430 InsertParallelMoveAtExitOf(predecessor, nullptr, source, destination);
Nicolas Geoffray86dbb9a2014-06-04 11:12:39 +01001431 }
1432 }
1433 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001434
1435 // Assign temp locations.
1436 HInstruction* current = nullptr;
1437 size_t temp_index = 0;
1438 for (size_t i = 0; i < temp_intervals_.Size(); ++i) {
1439 LiveInterval* temp = temp_intervals_.Get(i);
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001440 if (temp->IsHighInterval()) {
1441 // High intervals can be skipped, they are already handled by the low interval.
1442 continue;
1443 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001444 HInstruction* at = liveness_.GetTempUser(temp);
1445 if (at != current) {
Nicolas Geoffray39468442014-09-02 15:17:15 +01001446 temp_index = 0;
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001447 current = at;
Nicolas Geoffray39468442014-09-02 15:17:15 +01001448 }
Nicolas Geoffray01ef3452014-10-01 11:32:17 +01001449 LocationSummary* locations = at->GetLocations();
Roland Levillain5368c212014-11-27 15:03:41 +00001450 switch (temp->GetType()) {
1451 case Primitive::kPrimInt:
1452 locations->SetTempAt(
1453 temp_index++, Location::RegisterLocation(temp->GetRegister()));
1454 break;
1455
1456 case Primitive::kPrimDouble:
Nicolas Geoffray840e5462015-01-07 16:01:24 +00001457 if (codegen_->NeedsTwoRegisters(Primitive::kPrimDouble)) {
1458 Location location = Location::FpuRegisterPairLocation(
1459 temp->GetRegister(), temp->GetHighInterval()->GetRegister());
1460 locations->SetTempAt(temp_index++, location);
1461 } else {
1462 locations->SetTempAt(
1463 temp_index++, Location::FpuRegisterLocation(temp->GetRegister()));
1464 }
Roland Levillain5368c212014-11-27 15:03:41 +00001465 break;
1466
1467 default:
1468 LOG(FATAL) << "Unexpected type for temporary location "
1469 << temp->GetType();
1470 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01001471 }
Nicolas Geoffray31d76b42014-06-09 15:02:22 +01001472}
1473
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001474} // namespace art