blob: e6209b95836fcea621782fe3355002e265dd1dc4 [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)
38 : graph_(graph), worklist_(graph->GetArena(), kDefaultWorklistSize) {}
39
40 void Run();
41
42 private:
43 void VisitBasicBlock(HBasicBlock* block);
44 void ProcessWorklist();
45 void AddToWorklist(HPhi* phi);
46 void AddDependentInstructionsToWorklist(HPhi* phi);
47 bool UpdateType(HPhi* phi);
48
49 HGraph* const graph_;
50 GrowableArray<HPhi*> worklist_;
51
52 static constexpr size_t kDefaultWorklistSize = 8;
53
54 DISALLOW_COPY_AND_ASSIGN(DeadPhiHandling);
55};
56
57bool DeadPhiHandling::UpdateType(HPhi* phi) {
58 Primitive::Type existing = phi->GetType();
59 DCHECK(phi->IsLive());
60
61 bool conflict = false;
62 Primitive::Type new_type = existing;
63 for (size_t i = 0, e = phi->InputCount(); i < e; ++i) {
64 HInstruction* input = phi->InputAt(i);
65 if (input->IsPhi() && input->AsPhi()->IsDead()) {
66 // We are doing a reverse post order visit of the graph, reviving
67 // phis that have environment uses and updating their types. If an
68 // input is a phi, and it is dead (because its input types are
69 // conflicting), this phi must be marked dead as well.
70 conflict = true;
71 break;
72 }
73 Primitive::Type input_type = HPhi::ToPhiType(input->GetType());
74
75 // The only acceptable transitions are:
76 // - From void to typed: first time we update the type of this phi.
77 // - From int to reference (or reference to int): the phi has to change
78 // to reference type. If the integer input cannot be converted to a
79 // reference input, the phi will remain dead.
80 if (new_type == Primitive::kPrimVoid) {
81 new_type = input_type;
82 } else if (new_type == Primitive::kPrimNot && input_type == Primitive::kPrimInt) {
83 HInstruction* equivalent = SsaBuilder::GetReferenceTypeEquivalent(input);
84 if (equivalent == nullptr) {
85 conflict = true;
86 break;
87 } else {
88 phi->ReplaceInput(equivalent, i);
89 if (equivalent->IsPhi()) {
90 DCHECK_EQ(equivalent->GetType(), Primitive::kPrimNot);
91 // We created a new phi, but that phi has the same inputs as the old phi. We
92 // add it to the worklist to ensure its inputs can also be converted to reference.
93 // If not, it will remain dead, and the algorithm will make the current phi dead
94 // as well.
95 equivalent->AsPhi()->SetLive();
96 AddToWorklist(equivalent->AsPhi());
97 }
98 }
99 } else if (new_type == Primitive::kPrimInt && input_type == Primitive::kPrimNot) {
100 new_type = Primitive::kPrimNot;
101 // Start over, we may request reference equivalents for the inputs of the phi.
102 i = -1;
103 } else if (new_type != input_type) {
104 conflict = true;
105 break;
106 }
107 }
108
109 if (conflict) {
110 phi->SetType(Primitive::kPrimVoid);
111 phi->SetDead();
112 return true;
113 } else {
114 DCHECK(phi->IsLive());
115 phi->SetType(new_type);
116 return existing != new_type;
117 }
118}
119
120void DeadPhiHandling::VisitBasicBlock(HBasicBlock* block) {
121 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
122 HPhi* phi = it.Current()->AsPhi();
123 if (phi->IsDead() && phi->HasEnvironmentUses()) {
124 phi->SetLive();
125 if (block->IsLoopHeader()) {
126 // Give a type to the loop phi, to guarantee convergence of the algorithm.
127 phi->SetType(phi->InputAt(0)->GetType());
128 AddToWorklist(phi);
129 } else {
130 // Because we are doing a reverse post order visit, all inputs of
131 // this phi have been visited and therefore had their (initial) type set.
132 UpdateType(phi);
133 }
134 }
135 }
136}
137
138void DeadPhiHandling::ProcessWorklist() {
139 while (!worklist_.IsEmpty()) {
140 HPhi* instruction = worklist_.Pop();
141 // Note that the same equivalent phi can be added multiple times in the work list, if
142 // used by multiple phis. The first call to `UpdateType` will know whether the phi is
143 // dead or live.
144 if (instruction->IsLive() && UpdateType(instruction)) {
145 AddDependentInstructionsToWorklist(instruction);
146 }
147 }
148}
149
150void DeadPhiHandling::AddToWorklist(HPhi* instruction) {
151 DCHECK(instruction->IsLive());
152 worklist_.Add(instruction);
153}
154
155void DeadPhiHandling::AddDependentInstructionsToWorklist(HPhi* instruction) {
156 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
157 HPhi* phi = it.Current()->GetUser()->AsPhi();
158 if (phi != nullptr && !phi->IsDead()) {
159 AddToWorklist(phi);
160 }
161 }
162}
163
164void DeadPhiHandling::Run() {
165 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
166 VisitBasicBlock(it.Current());
167 }
168 ProcessWorklist();
169}
170
171static bool IsPhiEquivalentOf(HInstruction* instruction, HPhi* phi) {
172 return instruction != nullptr
173 && instruction->IsPhi()
174 && instruction->AsPhi()->GetRegNumber() == phi->GetRegNumber();
175}
176
Calin Juravlea4f88312015-04-16 12:57:19 +0100177void SsaBuilder::FixNullConstantType() {
178 // The order doesn't matter here.
179 for (HReversePostOrderIterator itb(*GetGraph()); !itb.Done(); itb.Advance()) {
180 for (HInstructionIterator it(itb.Current()->GetInstructions()); !it.Done(); it.Advance()) {
181 HInstruction* equality_instr = it.Current();
182 if (!equality_instr->IsEqual() && !equality_instr->IsNotEqual()) {
183 continue;
184 }
185 HInstruction* left = equality_instr->InputAt(0);
186 HInstruction* right = equality_instr->InputAt(1);
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100187 HInstruction* int_operand = nullptr;
Calin Juravlea4f88312015-04-16 12:57:19 +0100188
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100189 if ((left->GetType() == Primitive::kPrimNot) && (right->GetType() == Primitive::kPrimInt)) {
190 int_operand = right;
191 } else if ((right->GetType() == Primitive::kPrimNot)
192 && (left->GetType() == Primitive::kPrimInt)) {
193 int_operand = left;
Calin Juravlea4f88312015-04-16 12:57:19 +0100194 } else {
195 continue;
196 }
197
198 // If we got here, we are comparing against a reference and the int constant
199 // should be replaced with a null constant.
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100200 // Both type propagation and redundant phi elimination ensure `int_operand`
201 // can only be the 0 constant.
202 DCHECK(int_operand->IsIntConstant());
203 DCHECK_EQ(0, int_operand->AsIntConstant()->GetValue());
204 equality_instr->ReplaceInput(GetGraph()->GetNullConstant(), int_operand == right ? 1 : 0);
Calin Juravlea4f88312015-04-16 12:57:19 +0100205 }
206 }
207}
208
209void SsaBuilder::EquivalentPhisCleanup() {
210 // The order doesn't matter here.
211 for (HReversePostOrderIterator itb(*GetGraph()); !itb.Done(); itb.Advance()) {
212 for (HInstructionIterator it(itb.Current()->GetPhis()); !it.Done(); it.Advance()) {
213 HPhi* phi = it.Current()->AsPhi();
214 HPhi* next = phi->GetNextEquivalentPhiWithSameType();
215 if (next != nullptr) {
Nicolas Geoffray4230e182015-06-29 14:34:46 +0100216 // Make sure we do not replace a live phi with a dead phi. A live phi has been
217 // handled by the type propagation phase, unlike a dead phi.
218 if (next->IsLive()) {
219 phi->ReplaceWith(next);
220 } else {
221 next->ReplaceWith(phi);
222 }
Calin Juravlea4f88312015-04-16 12:57:19 +0100223 DCHECK(next->GetNextEquivalentPhiWithSameType() == nullptr)
224 << "More then one phi equivalent with type " << phi->GetType()
225 << " found for phi" << phi->GetId();
226 }
227 }
228 }
229}
230
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100231void SsaBuilder::BuildSsa() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100232 // 1) Visit in reverse post order. We need to have all predecessors of a block visited
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100233 // (with the exception of loops) in order to create the right environment for that
234 // block. For loops, we create phis whose inputs will be set in 2).
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100235 for (HReversePostOrderIterator it(*GetGraph()); !it.Done(); it.Advance()) {
236 VisitBasicBlock(it.Current());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100237 }
238
239 // 2) Set inputs of loop phis.
240 for (size_t i = 0; i < loop_headers_.Size(); i++) {
241 HBasicBlock* block = loop_headers_.Get(i);
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100242 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100243 HPhi* phi = it.Current()->AsPhi();
Vladimir Marko60584552015-09-03 13:35:12 +0000244 for (HBasicBlock* predecessor : block->GetPredecessors()) {
245 HInstruction* input = ValueOfLocal(predecessor, phi->GetRegNumber());
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100246 phi->AddInput(input);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100247 }
248 }
249 }
250
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000251 // 3) Mark dead phis. This will mark phis that are only used by environments:
Nicolas Geoffray31596742014-11-24 15:28:45 +0000252 // at the DEX level, the type of these phis does not need to be consistent, but
253 // our code generator will complain if the inputs of a phi do not have the same
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000254 // type. The marking allows the type propagation to know which phis it needs
255 // to handle. We mark but do not eliminate: the elimination will be done in
Nicolas Geoffrayb59dba02015-03-11 18:13:21 +0000256 // step 9).
257 SsaDeadPhiElimination dead_phis_for_type_propagation(GetGraph());
258 dead_phis_for_type_propagation.MarkDeadPhis();
Nicolas Geoffray31596742014-11-24 15:28:45 +0000259
260 // 4) Propagate types of phis. At this point, phis are typed void in the general
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000261 // case, or float/double/reference when we created an equivalent phi. So we
Nicolas Geoffray31596742014-11-24 15:28:45 +0000262 // need to propagate the types across phis to give them a correct type.
Calin Juravle10e244f2015-01-26 18:54:32 +0000263 PrimitiveTypePropagation type_propagation(GetGraph());
Nicolas Geoffray184d6402014-06-09 14:06:02 +0100264 type_propagation.Run();
265
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100266 // 5) When creating equivalent phis we copy the inputs of the original phi which
267 // may be improperly typed. This was fixed during the type propagation in 4) but
Calin Juravlea4f88312015-04-16 12:57:19 +0100268 // as a result we may end up with two equivalent phis with the same type for
269 // the same dex register. This pass cleans them up.
270 EquivalentPhisCleanup();
271
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100272 // 6) Mark dead phis again. Step 4) may have introduced new phis.
273 // Step 5) might enable the death of new phis.
Nicolas Geoffrayb59dba02015-03-11 18:13:21 +0000274 SsaDeadPhiElimination dead_phis(GetGraph());
275 dead_phis.MarkDeadPhis();
276
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100277 // 7) Now that the graph is correctly typed, we can get rid of redundant phis.
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000278 // Note that we cannot do this phase before type propagation, otherwise
279 // we could get rid of phi equivalents, whose presence is a requirement for the
280 // type propagation phase. Note that this is to satisfy statement (a) of the
281 // SsaBuilder (see ssa_builder.h).
282 SsaRedundantPhiElimination redundant_phi(GetGraph());
283 redundant_phi.Run();
284
Nicolas Geoffray51d400d2015-06-15 09:01:08 +0100285 // 8) Fix the type for null constants which are part of an equality comparison.
286 // We need to do this after redundant phi elimination, to ensure the only cases
287 // that we can see are reference comparison against 0. The redundant phi
288 // elimination ensures we do not see a phi taking two 0 constants in a HEqual
289 // or HNotEqual.
290 FixNullConstantType();
291
Calin Juravlea4f88312015-04-16 12:57:19 +0100292 // 9) Make sure environments use the right phi "equivalent": a phi marked dead
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000293 // can have a phi equivalent that is not dead. We must therefore update
294 // all environment uses of the dead phi to use its equivalent. Note that there
295 // can be multiple phis for the same Dex register that are live (for example
296 // when merging constants), in which case it is OK for the environments
297 // to just reference one.
298 for (HReversePostOrderIterator it(*GetGraph()); !it.Done(); it.Advance()) {
299 HBasicBlock* block = it.Current();
300 for (HInstructionIterator it_phis(block->GetPhis()); !it_phis.Done(); it_phis.Advance()) {
301 HPhi* phi = it_phis.Current()->AsPhi();
302 // If the phi is not dead, or has no environment uses, there is nothing to do.
303 if (!phi->IsDead() || !phi->HasEnvironmentUses()) continue;
304 HInstruction* next = phi->GetNext();
305 if (!IsPhiEquivalentOf(next, phi)) continue;
306 if (next->AsPhi()->IsDead()) {
307 // If the phi equivalent is dead, check if there is another one.
308 next = next->GetNext();
309 if (!IsPhiEquivalentOf(next, phi)) continue;
310 // There can be at most two phi equivalents.
311 DCHECK(!IsPhiEquivalentOf(next->GetNext(), phi));
312 if (next->AsPhi()->IsDead()) continue;
313 }
314 // We found a live phi equivalent. Update the environment uses of `phi` with it.
315 phi->ReplaceWith(next);
316 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000317 }
318
Calin Juravlea4f88312015-04-16 12:57:19 +0100319 // 10) Deal with phis to guarantee liveness of phis in case of a debuggable
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000320 // application. This is for satisfying statement (c) of the SsaBuilder
321 // (see ssa_builder.h).
322 if (GetGraph()->IsDebuggable()) {
323 DeadPhiHandling dead_phi_handler(GetGraph());
324 dead_phi_handler.Run();
325 }
326
Calin Juravlea4f88312015-04-16 12:57:19 +0100327 // 11) Now that the right phis are used for the environments, and we
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000328 // have potentially revive dead phis in case of a debuggable application,
329 // we can eliminate phis we do not need. Regardless of the debuggable status,
330 // this phase is necessary for statement (b) of the SsaBuilder (see ssa_builder.h),
331 // as well as for the code generation, which does not deal with phis of conflicting
332 // input types.
333 dead_phis.EliminateDeadPhis();
334
Calin Juravlea4f88312015-04-16 12:57:19 +0100335 // 12) Clear locals.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100336 for (HInstructionIterator it(GetGraph()->GetEntryBlock()->GetInstructions());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100337 !it.Done();
338 it.Advance()) {
339 HInstruction* current = it.Current();
Roland Levillain476df552014-10-09 17:51:36 +0100340 if (current->IsLocal()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100341 current->GetBlock()->RemoveInstruction(current);
342 }
343 }
344}
345
346HInstruction* SsaBuilder::ValueOfLocal(HBasicBlock* block, size_t local) {
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100347 return GetLocalsFor(block)->Get(local);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100348}
349
350void SsaBuilder::VisitBasicBlock(HBasicBlock* block) {
351 current_locals_ = GetLocalsFor(block);
352
David Brazdilffee3d32015-07-06 11:48:53 +0100353 if (block->IsCatchBlock()) {
354 // Catch phis were already created and inputs collected from throwing sites.
355 } else if (block->IsLoopHeader()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100356 // If the block is a loop header, we know we only have visited the pre header
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100357 // because we are visiting in reverse post order. We create phis for all initialized
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100358 // locals from the pre header. Their inputs will be populated at the end of
359 // the analysis.
360 for (size_t local = 0; local < current_locals_->Size(); local++) {
361 HInstruction* incoming = ValueOfLocal(block->GetLoopInformation()->GetPreHeader(), local);
362 if (incoming != nullptr) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100363 HPhi* phi = new (GetGraph()->GetArena()) HPhi(
364 GetGraph()->GetArena(), local, 0, Primitive::kPrimVoid);
365 block->AddPhi(phi);
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100366 current_locals_->Put(local, phi);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100367 }
368 }
369 // Save the loop header so that the last phase of the analysis knows which
370 // blocks need to be updated.
371 loop_headers_.Add(block);
Vladimir Marko60584552015-09-03 13:35:12 +0000372 } else if (block->GetPredecessors().size() > 0) {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100373 // All predecessors have already been visited because we are visiting in reverse post order.
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100374 // We merge the values of all locals, creating phis if those values differ.
375 for (size_t local = 0; local < current_locals_->Size(); local++) {
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100376 bool one_predecessor_has_no_value = false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100377 bool is_different = false;
Vladimir Marko60584552015-09-03 13:35:12 +0000378 HInstruction* value = ValueOfLocal(block->GetPredecessor(0), local);
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100379
Vladimir Marko60584552015-09-03 13:35:12 +0000380 for (HBasicBlock* predecessor : block->GetPredecessors()) {
381 HInstruction* current = ValueOfLocal(predecessor, local);
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100382 if (current == nullptr) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100383 one_predecessor_has_no_value = true;
384 break;
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100385 } else if (current != value) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100386 is_different = true;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100387 }
388 }
Nicolas Geoffray7c3560f2014-06-04 12:12:08 +0100389
390 if (one_predecessor_has_no_value) {
391 // If one predecessor has no value for this local, we trust the verifier has
392 // successfully checked that there is a store dominating any read after this block.
393 continue;
394 }
395
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100396 if (is_different) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100397 HPhi* phi = new (GetGraph()->GetArena()) HPhi(
Vladimir Marko60584552015-09-03 13:35:12 +0000398 GetGraph()->GetArena(), local, block->GetPredecessors().size(), Primitive::kPrimVoid);
399 for (size_t i = 0; i < block->GetPredecessors().size(); i++) {
400 HInstruction* pred_value = ValueOfLocal(block->GetPredecessor(i), local);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800401 phi->SetRawInputAt(i, pred_value);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100402 }
403 block->AddPhi(phi);
404 value = phi;
405 }
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100406 current_locals_->Put(local, value);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100407 }
408 }
409
410 // Visit all instructions. The instructions of interest are:
411 // - HLoadLocal: replace them with the current value of the local.
412 // - HStoreLocal: update current value of the local and remove the instruction.
413 // - Instructions that require an environment: populate their environment
414 // with the current values of the locals.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100415 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100416 it.Current()->Accept(this);
417 }
418}
419
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100420/**
421 * Constants in the Dex format are not typed. So the builder types them as
422 * integers, but when doing the SSA form, we might realize the constant
423 * is used for floating point operations. We create a floating-point equivalent
424 * constant to make the operations correctly typed.
425 */
David Brazdil8d5b8b22015-03-24 10:51:52 +0000426HFloatConstant* SsaBuilder::GetFloatEquivalent(HIntConstant* constant) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100427 // We place the floating point constant next to this constant.
428 HFloatConstant* result = constant->GetNext()->AsFloatConstant();
429 if (result == nullptr) {
430 HGraph* graph = constant->GetBlock()->GetGraph();
431 ArenaAllocator* allocator = graph->GetArena();
Roland Levillainda4d79b2015-03-24 14:36:11 +0000432 result = new (allocator) HFloatConstant(bit_cast<float, int32_t>(constant->GetValue()));
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100433 constant->GetBlock()->InsertInstructionBefore(result, constant->GetNext());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000434 graph->CacheFloatConstant(result);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100435 } else {
436 // If there is already a constant with the expected type, we know it is
437 // the floating point equivalent of this constant.
Roland Levillainda4d79b2015-03-24 14:36:11 +0000438 DCHECK_EQ((bit_cast<int32_t, float>(result->GetValue())), constant->GetValue());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100439 }
440 return result;
441}
442
443/**
444 * Wide constants in the Dex format are not typed. So the builder types them as
445 * longs, but when doing the SSA form, we might realize the constant
446 * is used for floating point operations. We create a floating-point equivalent
447 * constant to make the operations correctly typed.
448 */
David Brazdil8d5b8b22015-03-24 10:51:52 +0000449HDoubleConstant* SsaBuilder::GetDoubleEquivalent(HLongConstant* constant) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100450 // We place the floating point constant next to this constant.
451 HDoubleConstant* result = constant->GetNext()->AsDoubleConstant();
452 if (result == nullptr) {
453 HGraph* graph = constant->GetBlock()->GetGraph();
454 ArenaAllocator* allocator = graph->GetArena();
Roland Levillainda4d79b2015-03-24 14:36:11 +0000455 result = new (allocator) HDoubleConstant(bit_cast<double, int64_t>(constant->GetValue()));
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100456 constant->GetBlock()->InsertInstructionBefore(result, constant->GetNext());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000457 graph->CacheDoubleConstant(result);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100458 } else {
459 // If there is already a constant with the expected type, we know it is
460 // the floating point equivalent of this constant.
Roland Levillainda4d79b2015-03-24 14:36:11 +0000461 DCHECK_EQ((bit_cast<int64_t, double>(result->GetValue())), constant->GetValue());
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100462 }
463 return result;
464}
465
466/**
467 * Because of Dex format, we might end up having the same phi being
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000468 * used for non floating point operations and floating point / reference operations.
469 * Because we want the graph to be correctly typed (and thereafter avoid moves between
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100470 * floating point registers and core registers), we need to create a copy of the
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000471 * phi with a floating point / reference type.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100472 */
David Brazdil8d5b8b22015-03-24 10:51:52 +0000473HPhi* SsaBuilder::GetFloatDoubleOrReferenceEquivalentOfPhi(HPhi* phi, Primitive::Type type) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000474 // We place the floating point /reference phi next to this phi.
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100475 HInstruction* next = phi->GetNext();
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000476 if (next != nullptr
477 && next->AsPhi()->GetRegNumber() == phi->GetRegNumber()
478 && next->GetType() != type) {
479 // Move to the next phi to see if it is the one we are looking for.
480 next = next->GetNext();
481 }
482
483 if (next == nullptr
484 || (next->AsPhi()->GetRegNumber() != phi->GetRegNumber())
485 || (next->GetType() != type)) {
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100486 ArenaAllocator* allocator = phi->GetBlock()->GetGraph()->GetArena();
487 HPhi* new_phi = new (allocator) HPhi(allocator, phi->GetRegNumber(), phi->InputCount(), type);
488 for (size_t i = 0, e = phi->InputCount(); i < e; ++i) {
489 // Copy the inputs. Note that the graph may not be correctly typed by doing this copy,
490 // but the type propagation phase will fix it.
491 new_phi->SetRawInputAt(i, phi->InputAt(i));
492 }
493 phi->GetBlock()->InsertPhiAfter(new_phi, phi);
494 return new_phi;
495 } else {
Nicolas Geoffray21cc7982014-11-17 17:50:33 +0000496 DCHECK_EQ(next->GetType(), type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100497 return next->AsPhi();
498 }
499}
500
501HInstruction* SsaBuilder::GetFloatOrDoubleEquivalent(HInstruction* user,
502 HInstruction* value,
503 Primitive::Type type) {
504 if (value->IsArrayGet()) {
505 // The verifier has checked that values in arrays cannot be used for both
506 // floating point and non-floating point operations. It is therefore safe to just
507 // change the type of the operation.
508 value->AsArrayGet()->SetType(type);
509 return value;
510 } else if (value->IsLongConstant()) {
511 return GetDoubleEquivalent(value->AsLongConstant());
512 } else if (value->IsIntConstant()) {
513 return GetFloatEquivalent(value->AsIntConstant());
514 } else if (value->IsPhi()) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000515 return GetFloatDoubleOrReferenceEquivalentOfPhi(value->AsPhi(), type);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100516 } else {
517 // For other instructions, we assume the verifier has checked that the dex format is correctly
518 // typed and the value in a dex register will not be used for both floating point and
519 // non-floating point operations. So the only reason an instruction would want a floating
520 // 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 +0100521 DCHECK(user->IsPhi()) << "is actually " << user->DebugName() << " (" << user->GetId() << ")";
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100522 return value;
523 }
524}
525
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000526HInstruction* SsaBuilder::GetReferenceTypeEquivalent(HInstruction* value) {
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000527 if (value->IsIntConstant() && value->AsIntConstant()->GetValue() == 0) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000528 return value->GetBlock()->GetGraph()->GetNullConstant();
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000529 } else if (value->IsPhi()) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000530 return GetFloatDoubleOrReferenceEquivalentOfPhi(value->AsPhi(), Primitive::kPrimNot);
Nicolas Geoffraye0fe7ae2015-03-09 10:02:49 +0000531 } else {
532 return nullptr;
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000533 }
534}
535
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100536void SsaBuilder::VisitLoadLocal(HLoadLocal* load) {
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100537 HInstruction* value = current_locals_->Get(load->GetLocal()->GetRegNumber());
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000538 // If the operation requests a specific type, we make sure its input is of that type.
539 if (load->GetType() != value->GetType()) {
540 if (load->GetType() == Primitive::kPrimFloat || load->GetType() == Primitive::kPrimDouble) {
541 value = GetFloatOrDoubleEquivalent(load, value, load->GetType());
542 } else if (load->GetType() == Primitive::kPrimNot) {
543 value = GetReferenceTypeEquivalent(value);
544 }
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100545 }
546 load->ReplaceWith(value);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100547 load->GetBlock()->RemoveInstruction(load);
548}
549
550void SsaBuilder::VisitStoreLocal(HStoreLocal* store) {
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100551 current_locals_->Put(store->GetLocal()->GetRegNumber(), store->InputAt(1));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100552 store->GetBlock()->RemoveInstruction(store);
553}
554
555void SsaBuilder::VisitInstruction(HInstruction* instruction) {
David Brazdilffee3d32015-07-06 11:48:53 +0100556 if (instruction->NeedsEnvironment()) {
557 HEnvironment* environment = new (GetGraph()->GetArena()) HEnvironment(
558 GetGraph()->GetArena(),
559 current_locals_->Size(),
560 GetGraph()->GetDexFile(),
561 GetGraph()->GetMethodIdx(),
562 instruction->GetDexPc(),
563 GetGraph()->GetInvokeType(),
564 instruction);
565 environment->CopyFrom(*current_locals_);
566 instruction->SetRawEnvironment(environment);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100567 }
David Brazdilffee3d32015-07-06 11:48:53 +0100568
569 // If in a try block, propagate values of locals into catch blocks.
David Brazdilec16f792015-08-19 15:04:01 +0100570 if (instruction->CanThrowIntoCatchBlock()) {
571 const HTryBoundary& try_entry =
572 instruction->GetBlock()->GetTryCatchInformation()->GetTryEntry();
573 for (HExceptionHandlerIterator it(try_entry); !it.Done(); it.Advance()) {
David Brazdil29fc0082015-08-18 17:17:38 +0100574 GrowableArray<HInstruction*>* handler_locals = GetLocalsFor(it.Current());
David Brazdilffee3d32015-07-06 11:48:53 +0100575 for (size_t i = 0, e = current_locals_->Size(); i < e; ++i) {
576 HInstruction* local_value = current_locals_->Get(i);
577 if (local_value != nullptr) {
578 handler_locals->Get(i)->AsPhi()->AddInput(local_value);
579 }
580 }
581 }
582 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100583}
584
Nicolas Geoffray421e9f92014-11-11 18:21:53 +0000585void SsaBuilder::VisitTemporary(HTemporary* temp) {
586 // Temporaries are only used by the baseline register allocator.
587 temp->GetBlock()->RemoveInstruction(temp);
588}
589
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100590} // namespace art