blob: 9dcbea08c5fbc574918f16080dcf7458d3cfa912 [file] [log] [blame]
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +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 "ssa_builder.h"
Nicolas Geoffray184d6402014-06-09 14:06:02 +010018
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010019#include "nodes.h"
Calin Juravle10e244f2015-01-26 18:54:32 +000020#include "primitive_type_propagation.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000021#include "ssa_phi_elimination.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022
23namespace art {
24
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +000025/**
26 * A debuggable application may require to reviving phis, to ensure their
27 * associated DEX register is available to a debugger. This class implements
28 * the logic for statement (c) of the SsaBuilder (see ssa_builder.h). It
29 * also makes sure that phis with incompatible input types are not revived
30 * (statement (b) of the SsaBuilder).
31 *
32 * This phase must be run after detecting dead phis through the
33 * DeadPhiElimination phase, and before deleting the dead phis.
34 */
35class DeadPhiHandling : public ValueObject {
36 public:
37 explicit DeadPhiHandling(HGraph* graph)
Vladimir Marko71bf8092015-09-15 15:33:14 +010038 : graph_(graph), worklist_(graph->GetArena()->Adapter(kArenaAllocSsaBuilder)) {
39 worklist_.reserve(kDefaultWorklistSize);
40 }
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +000041
42 void Run();
43
44 private:
45 void VisitBasicBlock(HBasicBlock* block);
46 void ProcessWorklist();
47 void AddToWorklist(HPhi* phi);
48 void AddDependentInstructionsToWorklist(HPhi* phi);
49 bool UpdateType(HPhi* phi);
50
51 HGraph* const graph_;
Vladimir Marko71bf8092015-09-15 15:33:14 +010052 ArenaVector<HPhi*> worklist_;
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +000053
54 static constexpr size_t kDefaultWorklistSize = 8;
55
56 DISALLOW_COPY_AND_ASSIGN(DeadPhiHandling);
57};
58
59bool DeadPhiHandling::UpdateType(HPhi* phi) {
60 Primitive::Type existing = phi->GetType();
61 DCHECK(phi->IsLive());
62
63 bool conflict = false;
64 Primitive::Type new_type = existing;
65 for (size_t i = 0, e = phi->InputCount(); i < e; ++i) {
66 HInstruction* input = phi->InputAt(i);
67 if (input->IsPhi() && input->AsPhi()->IsDead()) {
68 // We are doing a reverse post order visit of the graph, reviving
69 // phis that have environment uses and updating their types. If an
70 // input is a phi, and it is dead (because its input types are
71 // conflicting), this phi must be marked dead as well.
72 conflict = true;
73 break;
74 }
75 Primitive::Type input_type = HPhi::ToPhiType(input->GetType());
76
77 // The only acceptable transitions are:
78 // - From void to typed: first time we update the type of this phi.
79 // - From int to reference (or reference to int): the phi has to change
80 // to reference type. If the integer input cannot be converted to a
81 // reference input, the phi will remain dead.
82 if (new_type == Primitive::kPrimVoid) {
83 new_type = input_type;
84 } else if (new_type == Primitive::kPrimNot && input_type == Primitive::kPrimInt) {
85 HInstruction* equivalent = SsaBuilder::GetReferenceTypeEquivalent(input);
86 if (equivalent == nullptr) {
87 conflict = true;
88 break;
89 } else {
90 phi->ReplaceInput(equivalent, i);
91 if (equivalent->IsPhi()) {
92 DCHECK_EQ(equivalent->GetType(), Primitive::kPrimNot);
93 // We created a new phi, but that phi has the same inputs as the old phi. We
94 // add it to the worklist to ensure its inputs can also be converted to reference.
95 // If not, it will remain dead, and the algorithm will make the current phi dead
96 // as well.
97 equivalent->AsPhi()->SetLive();
98 AddToWorklist(equivalent->AsPhi());
99 }
100 }
101 } else if (new_type == Primitive::kPrimInt && input_type == Primitive::kPrimNot) {
102 new_type = Primitive::kPrimNot;
103 // Start over, we may request reference equivalents for the inputs of the phi.
104 i = -1;
105 } else if (new_type != input_type) {
106 conflict = true;
107 break;
108 }
109 }
110
111 if (conflict) {
112 phi->SetType(Primitive::kPrimVoid);
113 phi->SetDead();
114 return true;
115 } else {
116 DCHECK(phi->IsLive());
117 phi->SetType(new_type);
118 return existing != new_type;
119 }
120}
121
122void DeadPhiHandling::VisitBasicBlock(HBasicBlock* block) {
123 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
124 HPhi* phi = it.Current()->AsPhi();
125 if (phi->IsDead() && phi->HasEnvironmentUses()) {
126 phi->SetLive();
127 if (block->IsLoopHeader()) {
128 // Give a type to the loop phi, to guarantee convergence of the algorithm.
129 phi->SetType(phi->InputAt(0)->GetType());
130 AddToWorklist(phi);
131 } else {
132 // Because we are doing a reverse post order visit, all inputs of
133 // this phi have been visited and therefore had their (initial) type set.
134 UpdateType(phi);
135 }
136 }
137 }
138}
139
140void DeadPhiHandling::ProcessWorklist() {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100141 while (!worklist_.empty()) {
142 HPhi* instruction = worklist_.back();
143 worklist_.pop_back();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000144 // Note that the same equivalent phi can be added multiple times in the work list, if
145 // used by multiple phis. The first call to `UpdateType` will know whether the phi is
146 // dead or live.
147 if (instruction->IsLive() && UpdateType(instruction)) {
148 AddDependentInstructionsToWorklist(instruction);
149 }
150 }
151}
152
153void DeadPhiHandling::AddToWorklist(HPhi* instruction) {
154 DCHECK(instruction->IsLive());
Vladimir Marko71bf8092015-09-15 15:33:14 +0100155 worklist_.push_back(instruction);
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000156}
157
158void DeadPhiHandling::AddDependentInstructionsToWorklist(HPhi* instruction) {
159 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
160 HPhi* phi = it.Current()->GetUser()->AsPhi();
161 if (phi != nullptr && !phi->IsDead()) {
162 AddToWorklist(phi);
163 }
164 }
165}
166
167void DeadPhiHandling::Run() {
168 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
169 VisitBasicBlock(it.Current());
170 }
171 ProcessWorklist();
172}
173
174static bool IsPhiEquivalentOf(HInstruction* instruction, HPhi* phi) {
175 return instruction != nullptr
176 && instruction->IsPhi()
177 && instruction->AsPhi()->GetRegNumber() == phi->GetRegNumber();
178}
179
Calin Juravlea4f88312015-04-16 12:57:19 +0100180void SsaBuilder::FixNullConstantType() {
181 // The order doesn't matter here.
182 for (HReversePostOrderIterator itb(*GetGraph()); !itb.Done(); itb.Advance()) {
183 for (HInstructionIterator it(itb.Current()->GetInstructions()); !it.Done(); it.Advance()) {
184 HInstruction* equality_instr = it.Current();
185 if (!equality_instr->IsEqual() && !equality_instr->IsNotEqual()) {
186 continue;
187 }
188 HInstruction* left = equality_instr->InputAt(0);
189 HInstruction* right = equality_instr->InputAt(1);
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100190 HInstruction* int_operand = nullptr;
Calin Juravlea4f88312015-04-16 12:57:19 +0100191
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100192 if ((left->GetType() == Primitive::kPrimNot) && (right->GetType() == Primitive::kPrimInt)) {
193 int_operand = right;
194 } else if ((right->GetType() == Primitive::kPrimNot)
195 && (left->GetType() == Primitive::kPrimInt)) {
196 int_operand = left;
Calin Juravlea4f88312015-04-16 12:57:19 +0100197 } else {
198 continue;
199 }
200
201 // If we got here, we are comparing against a reference and the int constant
202 // should be replaced with a null constant.
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100203 // Both type propagation and redundant phi elimination ensure `int_operand`
204 // can only be the 0 constant.
205 DCHECK(int_operand->IsIntConstant());
206 DCHECK_EQ(0, int_operand->AsIntConstant()->GetValue());
207 equality_instr->ReplaceInput(GetGraph()->GetNullConstant(), int_operand == right ? 1 : 0);
Calin Juravlea4f88312015-04-16 12:57:19 +0100208 }
209 }
210}
211
212void SsaBuilder::EquivalentPhisCleanup() {
213 // The order doesn't matter here.
214 for (HReversePostOrderIterator itb(*GetGraph()); !itb.Done(); itb.Advance()) {
215 for (HInstructionIterator it(itb.Current()->GetPhis()); !it.Done(); it.Advance()) {
216 HPhi* phi = it.Current()->AsPhi();
217 HPhi* next = phi->GetNextEquivalentPhiWithSameType();
218 if (next != nullptr) {
Nicolas Geoffray4230e182015-06-29 14:34:46 +0100219 // Make sure we do not replace a live phi with a dead phi. A live phi has been
220 // handled by the type propagation phase, unlike a dead phi.
221 if (next->IsLive()) {
222 phi->ReplaceWith(next);
223 } else {
224 next->ReplaceWith(phi);
225 }
Calin Juravlea4f88312015-04-16 12:57:19 +0100226 DCHECK(next->GetNextEquivalentPhiWithSameType() == nullptr)
227 << "More then one phi equivalent with type " << phi->GetType()
228 << " found for phi" << phi->GetId();
229 }
230 }
231 }
232}
233
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100234void SsaBuilder::BuildSsa() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100235 // 1) Visit in reverse post order. We need to have all predecessors of a block visited
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100236 // (with the exception of loops) in order to create the right environment for that
237 // block. For loops, we create phis whose inputs will be set in 2).
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100238 for (HReversePostOrderIterator it(*GetGraph()); !it.Done(); it.Advance()) {
239 VisitBasicBlock(it.Current());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100240 }
241
242 // 2) Set inputs of loop phis.
Vladimir Marko71bf8092015-09-15 15:33:14 +0100243 for (HBasicBlock* block : loop_headers_) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100244 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100245 HPhi* phi = it.Current()->AsPhi();
Vladimir Marko60584552015-09-03 13:35:12 +0000246 for (HBasicBlock* predecessor : block->GetPredecessors()) {
247 HInstruction* input = ValueOfLocal(predecessor, phi->GetRegNumber());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100248 phi->AddInput(input);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100249 }
250 }
251 }
252
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000253 // 3) Mark dead phis. This will mark phis that are only used by environments:
Nicolas Geoffray31596742014-11-24 15:28:45 +0000254 // at the DEX level, the type of these phis does not need to be consistent, but
255 // our code generator will complain if the inputs of a phi do not have the same
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000256 // type. The marking allows the type propagation to know which phis it needs
257 // to handle. We mark but do not eliminate: the elimination will be done in
Nicolas Geoffrayb59dba02015-03-11 18:13:21 +0000258 // step 9).
259 SsaDeadPhiElimination dead_phis_for_type_propagation(GetGraph());
260 dead_phis_for_type_propagation.MarkDeadPhis();
Nicolas Geoffray31596742014-11-24 15:28:45 +0000261
262 // 4) Propagate types of phis. At this point, phis are typed void in the general
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000263 // case, or float/double/reference when we created an equivalent phi. So we
Nicolas Geoffray31596742014-11-24 15:28:45 +0000264 // need to propagate the types across phis to give them a correct type.
Calin Juravle10e244f2015-01-26 18:54:32 +0000265 PrimitiveTypePropagation type_propagation(GetGraph());
Nicolas Geoffray184d6402014-06-09 14:06:02 +0100266 type_propagation.Run();
267
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100268 // 5) When creating equivalent phis we copy the inputs of the original phi which
269 // may be improperly typed. This was fixed during the type propagation in 4) but
Calin Juravlea4f88312015-04-16 12:57:19 +0100270 // as a result we may end up with two equivalent phis with the same type for
271 // the same dex register. This pass cleans them up.
272 EquivalentPhisCleanup();
273
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100274 // 6) Mark dead phis again. Step 4) may have introduced new phis.
275 // Step 5) might enable the death of new phis.
Nicolas Geoffrayb59dba02015-03-11 18:13:21 +0000276 SsaDeadPhiElimination dead_phis(GetGraph());
277 dead_phis.MarkDeadPhis();
278
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100279 // 7) Now that the graph is correctly typed, we can get rid of redundant phis.
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000280 // Note that we cannot do this phase before type propagation, otherwise
281 // we could get rid of phi equivalents, whose presence is a requirement for the
282 // type propagation phase. Note that this is to satisfy statement (a) of the
283 // SsaBuilder (see ssa_builder.h).
284 SsaRedundantPhiElimination redundant_phi(GetGraph());
285 redundant_phi.Run();
286
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100287 // 8) Fix the type for null constants which are part of an equality comparison.
288 // We need to do this after redundant phi elimination, to ensure the only cases
289 // that we can see are reference comparison against 0. The redundant phi
290 // elimination ensures we do not see a phi taking two 0 constants in a HEqual
291 // or HNotEqual.
292 FixNullConstantType();
293
Calin Juravlea4f88312015-04-16 12:57:19 +0100294 // 9) Make sure environments use the right phi "equivalent": a phi marked dead
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000295 // can have a phi equivalent that is not dead. We must therefore update
296 // all environment uses of the dead phi to use its equivalent. Note that there
297 // can be multiple phis for the same Dex register that are live (for example
298 // when merging constants), in which case it is OK for the environments
299 // to just reference one.
300 for (HReversePostOrderIterator it(*GetGraph()); !it.Done(); it.Advance()) {
301 HBasicBlock* block = it.Current();
302 for (HInstructionIterator it_phis(block->GetPhis()); !it_phis.Done(); it_phis.Advance()) {
303 HPhi* phi = it_phis.Current()->AsPhi();
304 // If the phi is not dead, or has no environment uses, there is nothing to do.
305 if (!phi->IsDead() || !phi->HasEnvironmentUses()) continue;
306 HInstruction* next = phi->GetNext();
307 if (!IsPhiEquivalentOf(next, phi)) continue;
308 if (next->AsPhi()->IsDead()) {
309 // If the phi equivalent is dead, check if there is another one.
310 next = next->GetNext();
311 if (!IsPhiEquivalentOf(next, phi)) continue;
312 // There can be at most two phi equivalents.
313 DCHECK(!IsPhiEquivalentOf(next->GetNext(), phi));
314 if (next->AsPhi()->IsDead()) continue;
315 }
316 // We found a live phi equivalent. Update the environment uses of `phi` with it.
317 phi->ReplaceWith(next);
318 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000319 }
320
Calin Juravlea4f88312015-04-16 12:57:19 +0100321 // 10) Deal with phis to guarantee liveness of phis in case of a debuggable
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000322 // application. This is for satisfying statement (c) of the SsaBuilder
323 // (see ssa_builder.h).
324 if (GetGraph()->IsDebuggable()) {
325 DeadPhiHandling dead_phi_handler(GetGraph());
326 dead_phi_handler.Run();
327 }
328
Calin Juravlea4f88312015-04-16 12:57:19 +0100329 // 11) Now that the right phis are used for the environments, and we
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000330 // have potentially revive dead phis in case of a debuggable application,
331 // we can eliminate phis we do not need. Regardless of the debuggable status,
332 // this phase is necessary for statement (b) of the SsaBuilder (see ssa_builder.h),
333 // as well as for the code generation, which does not deal with phis of conflicting
334 // input types.
335 dead_phis.EliminateDeadPhis();
336
Calin Juravlea4f88312015-04-16 12:57:19 +0100337 // 12) Clear locals.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100338 for (HInstructionIterator it(GetGraph()->GetEntryBlock()->GetInstructions());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100339 !it.Done();
340 it.Advance()) {
341 HInstruction* current = it.Current();
Roland Levillain476df552014-10-09 17:51:36 +0100342 if (current->IsLocal()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100343 current->GetBlock()->RemoveInstruction(current);
344 }
345 }
346}
347
348HInstruction* SsaBuilder::ValueOfLocal(HBasicBlock* block, size_t local) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100349 ArenaVector<HInstruction*>* locals = GetLocalsFor(block);
350 DCHECK_LT(local, locals->size());
351 return (*locals)[local];
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100352}
353
354void SsaBuilder::VisitBasicBlock(HBasicBlock* block) {
355 current_locals_ = GetLocalsFor(block);
356
David Brazdilffee3d32015-07-06 11:48:53 +0100357 if (block->IsCatchBlock()) {
358 // Catch phis were already created and inputs collected from throwing sites.
359 } else if (block->IsLoopHeader()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100360 // If the block is a loop header, we know we only have visited the pre header
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100361 // because we are visiting in reverse post order. We create phis for all initialized
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100362 // locals from the pre header. Their inputs will be populated at the end of
363 // the analysis.
Vladimir Marko71bf8092015-09-15 15:33:14 +0100364 for (size_t local = 0; local < current_locals_->size(); ++local) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100365 HInstruction* incoming = ValueOfLocal(block->GetLoopInformation()->GetPreHeader(), local);
366 if (incoming != nullptr) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100367 HPhi* phi = new (GetGraph()->GetArena()) HPhi(
368 GetGraph()->GetArena(), local, 0, Primitive::kPrimVoid);
369 block->AddPhi(phi);
Vladimir Marko71bf8092015-09-15 15:33:14 +0100370 (*current_locals_)[local] = phi;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100371 }
372 }
373 // Save the loop header so that the last phase of the analysis knows which
374 // blocks need to be updated.
Vladimir Marko71bf8092015-09-15 15:33:14 +0100375 loop_headers_.push_back(block);
Vladimir Marko60584552015-09-03 13:35:12 +0000376 } else if (block->GetPredecessors().size() > 0) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100377 // All predecessors have already been visited because we are visiting in reverse post order.
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100378 // We merge the values of all locals, creating phis if those values differ.
Vladimir Marko71bf8092015-09-15 15:33:14 +0100379 for (size_t local = 0; local < current_locals_->size(); ++local) {
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100380 bool one_predecessor_has_no_value = false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100381 bool is_different = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000382 HInstruction* value = ValueOfLocal(block->GetPredecessor(0), local);
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100383
Vladimir Marko60584552015-09-03 13:35:12 +0000384 for (HBasicBlock* predecessor : block->GetPredecessors()) {
385 HInstruction* current = ValueOfLocal(predecessor, local);
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100386 if (current == nullptr) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100387 one_predecessor_has_no_value = true;
388 break;
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100389 } else if (current != value) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100390 is_different = true;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100391 }
392 }
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100393
394 if (one_predecessor_has_no_value) {
395 // If one predecessor has no value for this local, we trust the verifier has
396 // successfully checked that there is a store dominating any read after this block.
397 continue;
398 }
399
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100400 if (is_different) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100401 HPhi* phi = new (GetGraph()->GetArena()) HPhi(
Vladimir Marko60584552015-09-03 13:35:12 +0000402 GetGraph()->GetArena(), local, block->GetPredecessors().size(), Primitive::kPrimVoid);
403 for (size_t i = 0; i < block->GetPredecessors().size(); i++) {
404 HInstruction* pred_value = ValueOfLocal(block->GetPredecessor(i), local);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800405 phi->SetRawInputAt(i, pred_value);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100406 }
407 block->AddPhi(phi);
408 value = phi;
409 }
Vladimir Marko71bf8092015-09-15 15:33:14 +0100410 (*current_locals_)[local] = value;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100411 }
412 }
413
414 // Visit all instructions. The instructions of interest are:
415 // - HLoadLocal: replace them with the current value of the local.
416 // - HStoreLocal: update current value of the local and remove the instruction.
417 // - Instructions that require an environment: populate their environment
418 // with the current values of the locals.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100419 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100420 it.Current()->Accept(this);
421 }
422}
423
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100424/**
425 * Constants in the Dex format are not typed. So the builder types them as
426 * integers, but when doing the SSA form, we might realize the constant
427 * is used for floating point operations. We create a floating-point equivalent
428 * constant to make the operations correctly typed.
429 */
David Brazdil8d5b8b22015-03-24 10:51:52 +0000430HFloatConstant* SsaBuilder::GetFloatEquivalent(HIntConstant* constant) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100431 // We place the floating point constant next to this constant.
432 HFloatConstant* result = constant->GetNext()->AsFloatConstant();
433 if (result == nullptr) {
434 HGraph* graph = constant->GetBlock()->GetGraph();
435 ArenaAllocator* allocator = graph->GetArena();
Roland Levillainda4d79b2015-03-24 14:36:11 +0000436 result = new (allocator) HFloatConstant(bit_cast<float, int32_t>(constant->GetValue()));
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100437 constant->GetBlock()->InsertInstructionBefore(result, constant->GetNext());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000438 graph->CacheFloatConstant(result);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100439 } else {
440 // If there is already a constant with the expected type, we know it is
441 // the floating point equivalent of this constant.
Roland Levillainda4d79b2015-03-24 14:36:11 +0000442 DCHECK_EQ((bit_cast<int32_t, float>(result->GetValue())), constant->GetValue());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100443 }
444 return result;
445}
446
447/**
448 * Wide constants in the Dex format are not typed. So the builder types them as
449 * longs, but when doing the SSA form, we might realize the constant
450 * is used for floating point operations. We create a floating-point equivalent
451 * constant to make the operations correctly typed.
452 */
David Brazdil8d5b8b22015-03-24 10:51:52 +0000453HDoubleConstant* SsaBuilder::GetDoubleEquivalent(HLongConstant* constant) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100454 // We place the floating point constant next to this constant.
455 HDoubleConstant* result = constant->GetNext()->AsDoubleConstant();
456 if (result == nullptr) {
457 HGraph* graph = constant->GetBlock()->GetGraph();
458 ArenaAllocator* allocator = graph->GetArena();
Roland Levillainda4d79b2015-03-24 14:36:11 +0000459 result = new (allocator) HDoubleConstant(bit_cast<double, int64_t>(constant->GetValue()));
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100460 constant->GetBlock()->InsertInstructionBefore(result, constant->GetNext());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000461 graph->CacheDoubleConstant(result);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100462 } else {
463 // If there is already a constant with the expected type, we know it is
464 // the floating point equivalent of this constant.
Roland Levillainda4d79b2015-03-24 14:36:11 +0000465 DCHECK_EQ((bit_cast<int64_t, double>(result->GetValue())), constant->GetValue());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100466 }
467 return result;
468}
469
470/**
471 * Because of Dex format, we might end up having the same phi being
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000472 * used for non floating point operations and floating point / reference operations.
473 * Because we want the graph to be correctly typed (and thereafter avoid moves between
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100474 * floating point registers and core registers), we need to create a copy of the
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000475 * phi with a floating point / reference type.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100476 */
David Brazdil8d5b8b22015-03-24 10:51:52 +0000477HPhi* SsaBuilder::GetFloatDoubleOrReferenceEquivalentOfPhi(HPhi* phi, Primitive::Type type) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000478 // We place the floating point /reference phi next to this phi.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100479 HInstruction* next = phi->GetNext();
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000480 if (next != nullptr
481 && next->AsPhi()->GetRegNumber() == phi->GetRegNumber()
482 && next->GetType() != type) {
483 // Move to the next phi to see if it is the one we are looking for.
484 next = next->GetNext();
485 }
486
487 if (next == nullptr
488 || (next->AsPhi()->GetRegNumber() != phi->GetRegNumber())
489 || (next->GetType() != type)) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100490 ArenaAllocator* allocator = phi->GetBlock()->GetGraph()->GetArena();
491 HPhi* new_phi = new (allocator) HPhi(allocator, phi->GetRegNumber(), phi->InputCount(), type);
492 for (size_t i = 0, e = phi->InputCount(); i < e; ++i) {
493 // Copy the inputs. Note that the graph may not be correctly typed by doing this copy,
494 // but the type propagation phase will fix it.
495 new_phi->SetRawInputAt(i, phi->InputAt(i));
496 }
497 phi->GetBlock()->InsertPhiAfter(new_phi, phi);
498 return new_phi;
499 } else {
Nicolas Geoffray21cc7982014-11-17 17:50:33 +0000500 DCHECK_EQ(next->GetType(), type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100501 return next->AsPhi();
502 }
503}
504
505HInstruction* SsaBuilder::GetFloatOrDoubleEquivalent(HInstruction* user,
506 HInstruction* value,
507 Primitive::Type type) {
508 if (value->IsArrayGet()) {
509 // The verifier has checked that values in arrays cannot be used for both
510 // floating point and non-floating point operations. It is therefore safe to just
511 // change the type of the operation.
512 value->AsArrayGet()->SetType(type);
513 return value;
514 } else if (value->IsLongConstant()) {
515 return GetDoubleEquivalent(value->AsLongConstant());
516 } else if (value->IsIntConstant()) {
517 return GetFloatEquivalent(value->AsIntConstant());
518 } else if (value->IsPhi()) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000519 return GetFloatDoubleOrReferenceEquivalentOfPhi(value->AsPhi(), type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100520 } else {
521 // For other instructions, we assume the verifier has checked that the dex format is correctly
522 // typed and the value in a dex register will not be used for both floating point and
523 // non-floating point operations. So the only reason an instruction would want a floating
524 // point equivalent is for an unused phi that will be removed by the dead phi elimination phase.
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100525 DCHECK(user->IsPhi()) << "is actually " << user->DebugName() << " (" << user->GetId() << ")";
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100526 return value;
527 }
528}
529
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000530HInstruction* SsaBuilder::GetReferenceTypeEquivalent(HInstruction* value) {
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000531 if (value->IsIntConstant() && value->AsIntConstant()->GetValue() == 0) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000532 return value->GetBlock()->GetGraph()->GetNullConstant();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000533 } else if (value->IsPhi()) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000534 return GetFloatDoubleOrReferenceEquivalentOfPhi(value->AsPhi(), Primitive::kPrimNot);
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000535 } else {
536 return nullptr;
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000537 }
538}
539
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100540void SsaBuilder::VisitLoadLocal(HLoadLocal* load) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100541 DCHECK_LT(load->GetLocal()->GetRegNumber(), current_locals_->size());
542 HInstruction* value = (*current_locals_)[load->GetLocal()->GetRegNumber()];
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000543 // If the operation requests a specific type, we make sure its input is of that type.
544 if (load->GetType() != value->GetType()) {
545 if (load->GetType() == Primitive::kPrimFloat || load->GetType() == Primitive::kPrimDouble) {
546 value = GetFloatOrDoubleEquivalent(load, value, load->GetType());
547 } else if (load->GetType() == Primitive::kPrimNot) {
548 value = GetReferenceTypeEquivalent(value);
549 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100550 }
551 load->ReplaceWith(value);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100552 load->GetBlock()->RemoveInstruction(load);
553}
554
555void SsaBuilder::VisitStoreLocal(HStoreLocal* store) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100556 DCHECK_LT(store->GetLocal()->GetRegNumber(), current_locals_->size());
557 (*current_locals_)[store->GetLocal()->GetRegNumber()] = store->InputAt(1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100558 store->GetBlock()->RemoveInstruction(store);
559}
560
561void SsaBuilder::VisitInstruction(HInstruction* instruction) {
David Brazdilffee3d32015-07-06 11:48:53 +0100562 if (instruction->NeedsEnvironment()) {
563 HEnvironment* environment = new (GetGraph()->GetArena()) HEnvironment(
564 GetGraph()->GetArena(),
Vladimir Marko71bf8092015-09-15 15:33:14 +0100565 current_locals_->size(),
David Brazdilffee3d32015-07-06 11:48:53 +0100566 GetGraph()->GetDexFile(),
567 GetGraph()->GetMethodIdx(),
568 instruction->GetDexPc(),
569 GetGraph()->GetInvokeType(),
570 instruction);
571 environment->CopyFrom(*current_locals_);
572 instruction->SetRawEnvironment(environment);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100573 }
David Brazdilffee3d32015-07-06 11:48:53 +0100574
575 // If in a try block, propagate values of locals into catch blocks.
David Brazdilec16f792015-08-19 15:04:01 +0100576 if (instruction->CanThrowIntoCatchBlock()) {
577 const HTryBoundary& try_entry =
578 instruction->GetBlock()->GetTryCatchInformation()->GetTryEntry();
579 for (HExceptionHandlerIterator it(try_entry); !it.Done(); it.Advance()) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100580 ArenaVector<HInstruction*>* handler_locals = GetLocalsFor(it.Current());
581 DCHECK_EQ(handler_locals->size(), current_locals_->size());
582 for (size_t i = 0, e = current_locals_->size(); i < e; ++i) {
583 HInstruction* local_value = (*current_locals_)[i];
David Brazdilffee3d32015-07-06 11:48:53 +0100584 if (local_value != nullptr) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100585 (*handler_locals)[i]->AsPhi()->AddInput(local_value);
David Brazdilffee3d32015-07-06 11:48:53 +0100586 }
587 }
588 }
589 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100590}
591
Nicolas Geoffray421e9f92014-11-11 18:21:53 +0000592void SsaBuilder::VisitTemporary(HTemporary* temp) {
593 // Temporaries are only used by the baseline register allocator.
594 temp->GetBlock()->RemoveInstruction(temp);
595}
596
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100597} // namespace art