blob: 82ba6e32401135797aec042728527eb2025026a9 [file] [log] [blame]
buzbee311ca162013-02-28 15:56:43 -08001/*
2 * Copyright (C) 2011 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 "compiler_internals.h"
18#include "local_value_numbering.h"
Ian Rogers8d3a1172013-06-04 01:13:28 -070019#include "dataflow_iterator-inl.h"
buzbee311ca162013-02-28 15:56:43 -080020
21namespace art {
22
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070023static unsigned int Predecessors(BasicBlock* bb) {
buzbee862a7602013-04-05 10:58:54 -070024 return bb->predecessors->Size();
buzbee311ca162013-02-28 15:56:43 -080025}
26
27/* Setup a constant value for opcodes thare have the DF_SETS_CONST attribute */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070028void MIRGraph::SetConstant(int32_t ssa_reg, int value) {
buzbee862a7602013-04-05 10:58:54 -070029 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080030 constant_values_[ssa_reg] = value;
31}
32
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070033void MIRGraph::SetConstantWide(int ssa_reg, int64_t value) {
buzbee862a7602013-04-05 10:58:54 -070034 is_constant_v_->SetBit(ssa_reg);
buzbee311ca162013-02-28 15:56:43 -080035 constant_values_[ssa_reg] = Low32Bits(value);
36 constant_values_[ssa_reg + 1] = High32Bits(value);
37}
38
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070039void MIRGraph::DoConstantPropogation(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -080040 MIR* mir;
buzbee311ca162013-02-28 15:56:43 -080041
42 for (mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
buzbee1fd33462013-03-25 13:40:45 -070043 int df_attributes = oat_data_flow_attributes_[mir->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -080044
45 DecodedInstruction *d_insn = &mir->dalvikInsn;
46
47 if (!(df_attributes & DF_HAS_DEFS)) continue;
48
49 /* Handle instructions that set up constants directly */
50 if (df_attributes & DF_SETS_CONST) {
51 if (df_attributes & DF_DA) {
52 int32_t vB = static_cast<int32_t>(d_insn->vB);
53 switch (d_insn->opcode) {
54 case Instruction::CONST_4:
55 case Instruction::CONST_16:
56 case Instruction::CONST:
57 SetConstant(mir->ssa_rep->defs[0], vB);
58 break;
59 case Instruction::CONST_HIGH16:
60 SetConstant(mir->ssa_rep->defs[0], vB << 16);
61 break;
62 case Instruction::CONST_WIDE_16:
63 case Instruction::CONST_WIDE_32:
64 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB));
65 break;
66 case Instruction::CONST_WIDE:
Brian Carlstromb1eba212013-07-17 18:07:19 -070067 SetConstantWide(mir->ssa_rep->defs[0], d_insn->vB_wide);
buzbee311ca162013-02-28 15:56:43 -080068 break;
69 case Instruction::CONST_WIDE_HIGH16:
70 SetConstantWide(mir->ssa_rep->defs[0], static_cast<int64_t>(vB) << 48);
71 break;
72 default:
73 break;
74 }
75 }
76 /* Handle instructions that set up constants directly */
77 } else if (df_attributes & DF_IS_MOVE) {
78 int i;
79
80 for (i = 0; i < mir->ssa_rep->num_uses; i++) {
buzbee862a7602013-04-05 10:58:54 -070081 if (!is_constant_v_->IsBitSet(mir->ssa_rep->uses[i])) break;
buzbee311ca162013-02-28 15:56:43 -080082 }
83 /* Move a register holding a constant to another register */
84 if (i == mir->ssa_rep->num_uses) {
85 SetConstant(mir->ssa_rep->defs[0], constant_values_[mir->ssa_rep->uses[0]]);
86 if (df_attributes & DF_A_WIDE) {
87 SetConstant(mir->ssa_rep->defs[1], constant_values_[mir->ssa_rep->uses[1]]);
88 }
89 }
90 }
91 }
92 /* TODO: implement code to handle arithmetic operations */
buzbee311ca162013-02-28 15:56:43 -080093}
94
Brian Carlstrom2ce745c2013-07-17 17:44:30 -070095void MIRGraph::PropagateConstants() {
buzbee862a7602013-04-05 10:58:54 -070096 is_constant_v_ = new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false);
97 constant_values_ = static_cast<int*>(arena_->NewMem(sizeof(int) * GetNumSSARegs(), true,
98 ArenaAllocator::kAllocDFInfo));
buzbee0665fe02013-03-21 12:32:21 -070099 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800100 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
101 DoConstantPropogation(bb);
102 }
buzbee311ca162013-02-28 15:56:43 -0800103}
104
105/* Advance to next strictly dominated MIR node in an extended basic block */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700106static MIR* AdvanceMIR(BasicBlock** p_bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800107 BasicBlock* bb = *p_bb;
108 if (mir != NULL) {
109 mir = mir->next;
110 if (mir == NULL) {
111 bb = bb->fall_through;
112 if ((bb == NULL) || Predecessors(bb) != 1) {
113 mir = NULL;
114 } else {
115 *p_bb = bb;
116 mir = bb->first_mir_insn;
117 }
118 }
119 }
120 return mir;
121}
122
123/*
124 * To be used at an invoke mir. If the logically next mir node represents
125 * a move-result, return it. Else, return NULL. If a move-result exists,
126 * it is required to immediately follow the invoke with no intervening
127 * opcodes or incoming arcs. However, if the result of the invoke is not
128 * used, a move-result may not be present.
129 */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700130MIR* MIRGraph::FindMoveResult(BasicBlock* bb, MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800131 BasicBlock* tbb = bb;
132 mir = AdvanceMIR(&tbb, mir);
133 while (mir != NULL) {
134 int opcode = mir->dalvikInsn.opcode;
135 if ((mir->dalvikInsn.opcode == Instruction::MOVE_RESULT) ||
136 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) ||
137 (mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_WIDE)) {
138 break;
139 }
140 // Keep going if pseudo op, otherwise terminate
141 if (opcode < kNumPackedOpcodes) {
142 mir = NULL;
143 } else {
144 mir = AdvanceMIR(&tbb, mir);
145 }
146 }
147 return mir;
148}
149
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700150static BasicBlock* NextDominatedBlock(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800151 if (bb->block_type == kDead) {
152 return NULL;
153 }
154 DCHECK((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
155 || (bb->block_type == kExitBlock));
buzbeecbcfaf32013-08-19 07:37:40 -0700156 if (((bb->taken != NULL) && (bb->fall_through == NULL)) &&
157 ((bb->taken->block_type == kDalvikByteCode) || (bb->taken->block_type == kExitBlock))) {
158 // Follow simple unconditional branches.
159 bb = bb->taken;
160 } else {
161 // Follow simple fallthrough
162 bb = (bb->taken != NULL) ? NULL : bb->fall_through;
163 }
buzbee311ca162013-02-28 15:56:43 -0800164 if (bb == NULL || (Predecessors(bb) != 1)) {
165 return NULL;
166 }
167 DCHECK((bb->block_type == kDalvikByteCode) || (bb->block_type == kExitBlock));
168 return bb;
169}
170
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700171static MIR* FindPhi(BasicBlock* bb, int ssa_name) {
buzbee311ca162013-02-28 15:56:43 -0800172 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
173 if (static_cast<int>(mir->dalvikInsn.opcode) == kMirOpPhi) {
174 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
175 if (mir->ssa_rep->uses[i] == ssa_name) {
176 return mir;
177 }
178 }
179 }
180 }
181 return NULL;
182}
183
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700184static SelectInstructionKind SelectKind(MIR* mir) {
buzbee311ca162013-02-28 15:56:43 -0800185 switch (mir->dalvikInsn.opcode) {
186 case Instruction::MOVE:
187 case Instruction::MOVE_OBJECT:
188 case Instruction::MOVE_16:
189 case Instruction::MOVE_OBJECT_16:
190 case Instruction::MOVE_FROM16:
191 case Instruction::MOVE_OBJECT_FROM16:
192 return kSelectMove;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700193 case Instruction::CONST:
194 case Instruction::CONST_4:
195 case Instruction::CONST_16:
buzbee311ca162013-02-28 15:56:43 -0800196 return kSelectConst;
Brian Carlstrom6f485c62013-07-18 15:35:35 -0700197 case Instruction::GOTO:
198 case Instruction::GOTO_16:
199 case Instruction::GOTO_32:
buzbee311ca162013-02-28 15:56:43 -0800200 return kSelectGoto;
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700201 default:
202 return kSelectNone;
buzbee311ca162013-02-28 15:56:43 -0800203 }
buzbee311ca162013-02-28 15:56:43 -0800204}
205
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700206int MIRGraph::GetSSAUseCount(int s_reg) {
buzbee862a7602013-04-05 10:58:54 -0700207 return raw_use_counts_.Get(s_reg);
buzbee311ca162013-02-28 15:56:43 -0800208}
209
210
211/* Do some MIR-level extended basic block optimizations */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700212bool MIRGraph::BasicBlockOpt(BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800213 if (bb->block_type == kDead) {
214 return true;
215 }
216 int num_temps = 0;
217 LocalValueNumbering local_valnum(cu_);
218 while (bb != NULL) {
219 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
220 // TUNING: use the returned value number for CSE.
221 local_valnum.GetValueNumber(mir);
222 // Look for interesting opcodes, skip otherwise
223 Instruction::Code opcode = mir->dalvikInsn.opcode;
224 switch (opcode) {
225 case Instruction::CMPL_FLOAT:
226 case Instruction::CMPL_DOUBLE:
227 case Instruction::CMPG_FLOAT:
228 case Instruction::CMPG_DOUBLE:
229 case Instruction::CMP_LONG:
buzbee1fd33462013-03-25 13:40:45 -0700230 if ((cu_->disable_opt & (1 << kBranchFusing)) != 0) {
buzbee311ca162013-02-28 15:56:43 -0800231 // Bitcode doesn't allow this optimization.
232 break;
233 }
234 if (mir->next != NULL) {
235 MIR* mir_next = mir->next;
236 Instruction::Code br_opcode = mir_next->dalvikInsn.opcode;
237 ConditionCode ccode = kCondNv;
Brian Carlstromdf629502013-07-17 22:39:56 -0700238 switch (br_opcode) {
buzbee311ca162013-02-28 15:56:43 -0800239 case Instruction::IF_EQZ:
240 ccode = kCondEq;
241 break;
242 case Instruction::IF_NEZ:
243 ccode = kCondNe;
244 break;
245 case Instruction::IF_LTZ:
246 ccode = kCondLt;
247 break;
248 case Instruction::IF_GEZ:
249 ccode = kCondGe;
250 break;
251 case Instruction::IF_GTZ:
252 ccode = kCondGt;
253 break;
254 case Instruction::IF_LEZ:
255 ccode = kCondLe;
256 break;
257 default:
258 break;
259 }
260 // Make sure result of cmp is used by next insn and nowhere else
261 if ((ccode != kCondNv) &&
262 (mir->ssa_rep->defs[0] == mir_next->ssa_rep->uses[0]) &&
263 (GetSSAUseCount(mir->ssa_rep->defs[0]) == 1)) {
264 mir_next->dalvikInsn.arg[0] = ccode;
Brian Carlstromdf629502013-07-17 22:39:56 -0700265 switch (opcode) {
buzbee311ca162013-02-28 15:56:43 -0800266 case Instruction::CMPL_FLOAT:
267 mir_next->dalvikInsn.opcode =
268 static_cast<Instruction::Code>(kMirOpFusedCmplFloat);
269 break;
270 case Instruction::CMPL_DOUBLE:
271 mir_next->dalvikInsn.opcode =
272 static_cast<Instruction::Code>(kMirOpFusedCmplDouble);
273 break;
274 case Instruction::CMPG_FLOAT:
275 mir_next->dalvikInsn.opcode =
276 static_cast<Instruction::Code>(kMirOpFusedCmpgFloat);
277 break;
278 case Instruction::CMPG_DOUBLE:
279 mir_next->dalvikInsn.opcode =
280 static_cast<Instruction::Code>(kMirOpFusedCmpgDouble);
281 break;
282 case Instruction::CMP_LONG:
283 mir_next->dalvikInsn.opcode =
284 static_cast<Instruction::Code>(kMirOpFusedCmpLong);
285 break;
286 default: LOG(ERROR) << "Unexpected opcode: " << opcode;
287 }
288 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
289 mir_next->ssa_rep->num_uses = mir->ssa_rep->num_uses;
290 mir_next->ssa_rep->uses = mir->ssa_rep->uses;
291 mir_next->ssa_rep->fp_use = mir->ssa_rep->fp_use;
292 mir_next->ssa_rep->num_defs = 0;
293 mir->ssa_rep->num_uses = 0;
294 mir->ssa_rep->num_defs = 0;
295 }
296 }
297 break;
298 case Instruction::GOTO:
299 case Instruction::GOTO_16:
300 case Instruction::GOTO_32:
301 case Instruction::IF_EQ:
302 case Instruction::IF_NE:
303 case Instruction::IF_LT:
304 case Instruction::IF_GE:
305 case Instruction::IF_GT:
306 case Instruction::IF_LE:
307 case Instruction::IF_EQZ:
308 case Instruction::IF_NEZ:
309 case Instruction::IF_LTZ:
310 case Instruction::IF_GEZ:
311 case Instruction::IF_GTZ:
312 case Instruction::IF_LEZ:
buzbeecbcfaf32013-08-19 07:37:40 -0700313 // If we've got a backwards branch to return, no need to suspend check.
314 if ((bb->taken->dominates_return) && (mir->backwards_branch)) {
buzbee311ca162013-02-28 15:56:43 -0800315 mir->optimization_flags |= MIR_IGNORE_SUSPEND_CHECK;
316 if (cu_->verbose) {
317 LOG(INFO) << "Suppressed suspend check on branch to return at 0x" << std::hex << mir->offset;
318 }
319 }
320 break;
321 default:
322 break;
323 }
324 // Is this the select pattern?
325 // TODO: flesh out support for Mips and X86. NOTE: llvm's select op doesn't quite work here.
326 // TUNING: expand to support IF_xx compare & branches
buzbee1fd33462013-03-25 13:40:45 -0700327 if (!(cu_->compiler_backend == kPortable) && (cu_->instruction_set == kThumb2) &&
buzbee311ca162013-02-28 15:56:43 -0800328 ((mir->dalvikInsn.opcode == Instruction::IF_EQZ) ||
329 (mir->dalvikInsn.opcode == Instruction::IF_NEZ))) {
330 BasicBlock* ft = bb->fall_through;
331 DCHECK(ft != NULL);
332 BasicBlock* ft_ft = ft->fall_through;
333 BasicBlock* ft_tk = ft->taken;
334
335 BasicBlock* tk = bb->taken;
336 DCHECK(tk != NULL);
337 BasicBlock* tk_ft = tk->fall_through;
338 BasicBlock* tk_tk = tk->taken;
339
340 /*
341 * In the select pattern, the taken edge goes to a block that unconditionally
342 * transfers to the rejoin block and the fall_though edge goes to a block that
343 * unconditionally falls through to the rejoin block.
344 */
345 if ((tk_ft == NULL) && (ft_tk == NULL) && (tk_tk == ft_ft) &&
346 (Predecessors(tk) == 1) && (Predecessors(ft) == 1)) {
347 /*
348 * Okay - we have the basic diamond shape. At the very least, we can eliminate the
349 * suspend check on the taken-taken branch back to the join point.
350 */
351 if (SelectKind(tk->last_mir_insn) == kSelectGoto) {
352 tk->last_mir_insn->optimization_flags |= (MIR_IGNORE_SUSPEND_CHECK);
353 }
354 // Are the block bodies something we can handle?
355 if ((ft->first_mir_insn == ft->last_mir_insn) &&
356 (tk->first_mir_insn != tk->last_mir_insn) &&
357 (tk->first_mir_insn->next == tk->last_mir_insn) &&
358 ((SelectKind(ft->first_mir_insn) == kSelectMove) ||
359 (SelectKind(ft->first_mir_insn) == kSelectConst)) &&
360 (SelectKind(ft->first_mir_insn) == SelectKind(tk->first_mir_insn)) &&
361 (SelectKind(tk->last_mir_insn) == kSelectGoto)) {
362 // Almost there. Are the instructions targeting the same vreg?
363 MIR* if_true = tk->first_mir_insn;
364 MIR* if_false = ft->first_mir_insn;
365 // It's possible that the target of the select isn't used - skip those (rare) cases.
366 MIR* phi = FindPhi(tk_tk, if_true->ssa_rep->defs[0]);
367 if ((phi != NULL) && (if_true->dalvikInsn.vA == if_false->dalvikInsn.vA)) {
368 /*
369 * We'll convert the IF_EQZ/IF_NEZ to a SELECT. We need to find the
370 * Phi node in the merge block and delete it (while using the SSA name
371 * of the merge as the target of the SELECT. Delete both taken and
372 * fallthrough blocks, and set fallthrough to merge block.
373 * NOTE: not updating other dataflow info (no longer used at this point).
374 * If this changes, need to update i_dom, etc. here (and in CombineBlocks).
375 */
376 if (opcode == Instruction::IF_NEZ) {
377 // Normalize.
378 MIR* tmp_mir = if_true;
379 if_true = if_false;
380 if_false = tmp_mir;
381 }
382 mir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpSelect);
383 bool const_form = (SelectKind(if_true) == kSelectConst);
384 if ((SelectKind(if_true) == kSelectMove)) {
385 if (IsConst(if_true->ssa_rep->uses[0]) &&
386 IsConst(if_false->ssa_rep->uses[0])) {
387 const_form = true;
388 if_true->dalvikInsn.vB = ConstantValue(if_true->ssa_rep->uses[0]);
389 if_false->dalvikInsn.vB = ConstantValue(if_false->ssa_rep->uses[0]);
390 }
391 }
392 if (const_form) {
393 // "true" set val in vB
394 mir->dalvikInsn.vB = if_true->dalvikInsn.vB;
395 // "false" set val in vC
396 mir->dalvikInsn.vC = if_false->dalvikInsn.vB;
397 } else {
398 DCHECK_EQ(SelectKind(if_true), kSelectMove);
399 DCHECK_EQ(SelectKind(if_false), kSelectMove);
buzbee862a7602013-04-05 10:58:54 -0700400 int* src_ssa =
401 static_cast<int*>(arena_->NewMem(sizeof(int) * 3, false,
402 ArenaAllocator::kAllocDFInfo));
buzbee311ca162013-02-28 15:56:43 -0800403 src_ssa[0] = mir->ssa_rep->uses[0];
404 src_ssa[1] = if_true->ssa_rep->uses[0];
405 src_ssa[2] = if_false->ssa_rep->uses[0];
406 mir->ssa_rep->uses = src_ssa;
407 mir->ssa_rep->num_uses = 3;
408 }
409 mir->ssa_rep->num_defs = 1;
buzbee862a7602013-04-05 10:58:54 -0700410 mir->ssa_rep->defs =
411 static_cast<int*>(arena_->NewMem(sizeof(int) * 1, false,
412 ArenaAllocator::kAllocDFInfo));
413 mir->ssa_rep->fp_def =
414 static_cast<bool*>(arena_->NewMem(sizeof(bool) * 1, false,
415 ArenaAllocator::kAllocDFInfo));
buzbee311ca162013-02-28 15:56:43 -0800416 mir->ssa_rep->fp_def[0] = if_true->ssa_rep->fp_def[0];
buzbee817e45a2013-05-30 18:59:12 -0700417 // Match type of uses to def.
418 mir->ssa_rep->fp_use =
419 static_cast<bool*>(arena_->NewMem(sizeof(bool) * mir->ssa_rep->num_uses, false,
420 ArenaAllocator::kAllocDFInfo));
421 for (int i = 0; i < mir->ssa_rep->num_uses; i++) {
422 mir->ssa_rep->fp_use[i] = mir->ssa_rep->fp_def[0];
423 }
buzbee311ca162013-02-28 15:56:43 -0800424 /*
425 * There is usually a Phi node in the join block for our two cases. If the
426 * Phi node only contains our two cases as input, we will use the result
427 * SSA name of the Phi node as our select result and delete the Phi. If
428 * the Phi node has more than two operands, we will arbitrarily use the SSA
429 * name of the "true" path, delete the SSA name of the "false" path from the
430 * Phi node (and fix up the incoming arc list).
431 */
432 if (phi->ssa_rep->num_uses == 2) {
433 mir->ssa_rep->defs[0] = phi->ssa_rep->defs[0];
434 phi->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
435 } else {
436 int dead_def = if_false->ssa_rep->defs[0];
437 int live_def = if_true->ssa_rep->defs[0];
438 mir->ssa_rep->defs[0] = live_def;
439 int* incoming = reinterpret_cast<int*>(phi->dalvikInsn.vB);
440 for (int i = 0; i < phi->ssa_rep->num_uses; i++) {
441 if (phi->ssa_rep->uses[i] == live_def) {
442 incoming[i] = bb->id;
443 }
444 }
445 for (int i = 0; i < phi->ssa_rep->num_uses; i++) {
446 if (phi->ssa_rep->uses[i] == dead_def) {
447 int last_slot = phi->ssa_rep->num_uses - 1;
448 phi->ssa_rep->uses[i] = phi->ssa_rep->uses[last_slot];
449 incoming[i] = incoming[last_slot];
450 }
451 }
452 }
453 phi->ssa_rep->num_uses--;
454 bb->taken = NULL;
455 tk->block_type = kDead;
456 for (MIR* tmir = ft->first_mir_insn; tmir != NULL; tmir = tmir->next) {
457 tmir->dalvikInsn.opcode = static_cast<Instruction::Code>(kMirOpNop);
458 }
459 }
460 }
461 }
462 }
463 }
464 bb = NextDominatedBlock(bb);
465 }
466
467 if (num_temps > cu_->num_compiler_temps) {
468 cu_->num_compiler_temps = num_temps;
469 }
470 return true;
471}
472
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700473void MIRGraph::NullCheckEliminationInit(struct BasicBlock* bb) {
buzbee862a7602013-04-05 10:58:54 -0700474 if (bb->data_flow_info != NULL) {
475 bb->data_flow_info->ending_null_check_v =
476 new (arena_) ArenaBitVector(arena_, GetNumSSARegs(), false, kBitMapNullCheck);
477 }
buzbee311ca162013-02-28 15:56:43 -0800478}
479
480/* Collect stats on number of checks removed */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700481void MIRGraph::CountChecks(struct BasicBlock* bb) {
buzbee862a7602013-04-05 10:58:54 -0700482 if (bb->data_flow_info != NULL) {
483 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
484 if (mir->ssa_rep == NULL) {
485 continue;
buzbee311ca162013-02-28 15:56:43 -0800486 }
buzbee862a7602013-04-05 10:58:54 -0700487 int df_attributes = oat_data_flow_attributes_[mir->dalvikInsn.opcode];
488 if (df_attributes & DF_HAS_NULL_CHKS) {
489 checkstats_->null_checks++;
490 if (mir->optimization_flags & MIR_IGNORE_NULL_CHECK) {
491 checkstats_->null_checks_eliminated++;
492 }
493 }
494 if (df_attributes & DF_HAS_RANGE_CHKS) {
495 checkstats_->range_checks++;
496 if (mir->optimization_flags & MIR_IGNORE_RANGE_CHECK) {
497 checkstats_->range_checks_eliminated++;
498 }
buzbee311ca162013-02-28 15:56:43 -0800499 }
500 }
501 }
buzbee311ca162013-02-28 15:56:43 -0800502}
503
504/* Try to make common case the fallthrough path */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700505static bool LayoutBlocks(struct BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800506 // TODO: For now, just looking for direct throws. Consider generalizing for profile feedback
507 if (!bb->explicit_throw) {
508 return false;
509 }
510 BasicBlock* walker = bb;
511 while (true) {
512 // Check termination conditions
513 if ((walker->block_type == kEntryBlock) || (Predecessors(walker) != 1)) {
514 break;
515 }
buzbee862a7602013-04-05 10:58:54 -0700516 BasicBlock* prev = walker->predecessors->Get(0);
buzbee311ca162013-02-28 15:56:43 -0800517 if (prev->conditional_branch) {
518 if (prev->fall_through == walker) {
519 // Already done - return
520 break;
521 }
522 DCHECK_EQ(walker, prev->taken);
523 // Got one. Flip it and exit
524 Instruction::Code opcode = prev->last_mir_insn->dalvikInsn.opcode;
525 switch (opcode) {
526 case Instruction::IF_EQ: opcode = Instruction::IF_NE; break;
527 case Instruction::IF_NE: opcode = Instruction::IF_EQ; break;
528 case Instruction::IF_LT: opcode = Instruction::IF_GE; break;
529 case Instruction::IF_GE: opcode = Instruction::IF_LT; break;
530 case Instruction::IF_GT: opcode = Instruction::IF_LE; break;
531 case Instruction::IF_LE: opcode = Instruction::IF_GT; break;
532 case Instruction::IF_EQZ: opcode = Instruction::IF_NEZ; break;
533 case Instruction::IF_NEZ: opcode = Instruction::IF_EQZ; break;
534 case Instruction::IF_LTZ: opcode = Instruction::IF_GEZ; break;
535 case Instruction::IF_GEZ: opcode = Instruction::IF_LTZ; break;
536 case Instruction::IF_GTZ: opcode = Instruction::IF_LEZ; break;
537 case Instruction::IF_LEZ: opcode = Instruction::IF_GTZ; break;
538 default: LOG(FATAL) << "Unexpected opcode " << opcode;
539 }
540 prev->last_mir_insn->dalvikInsn.opcode = opcode;
541 BasicBlock* t_bb = prev->taken;
542 prev->taken = prev->fall_through;
543 prev->fall_through = t_bb;
544 break;
545 }
546 walker = prev;
547 }
548 return false;
549}
550
551/* Combine any basic blocks terminated by instructions that we now know can't throw */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700552bool MIRGraph::CombineBlocks(struct BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800553 // Loop here to allow combining a sequence of blocks
554 while (true) {
555 // Check termination conditions
556 if ((bb->first_mir_insn == NULL)
557 || (bb->data_flow_info == NULL)
558 || (bb->block_type == kExceptionHandling)
559 || (bb->block_type == kExitBlock)
560 || (bb->block_type == kDead)
561 || ((bb->taken == NULL) || (bb->taken->block_type != kExceptionHandling))
562 || (bb->successor_block_list.block_list_type != kNotUsed)
563 || (static_cast<int>(bb->last_mir_insn->dalvikInsn.opcode) != kMirOpCheck)) {
564 break;
565 }
566
567 // Test the kMirOpCheck instruction
568 MIR* mir = bb->last_mir_insn;
569 // Grab the attributes from the paired opcode
570 MIR* throw_insn = mir->meta.throw_insn;
buzbee1fd33462013-03-25 13:40:45 -0700571 int df_attributes = oat_data_flow_attributes_[throw_insn->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800572 bool can_combine = true;
573 if (df_attributes & DF_HAS_NULL_CHKS) {
574 can_combine &= ((throw_insn->optimization_flags & MIR_IGNORE_NULL_CHECK) != 0);
575 }
576 if (df_attributes & DF_HAS_RANGE_CHKS) {
577 can_combine &= ((throw_insn->optimization_flags & MIR_IGNORE_RANGE_CHECK) != 0);
578 }
579 if (!can_combine) {
580 break;
581 }
582 // OK - got one. Combine
583 BasicBlock* bb_next = bb->fall_through;
584 DCHECK(!bb_next->catch_entry);
585 DCHECK_EQ(Predecessors(bb_next), 1U);
586 MIR* t_mir = bb->last_mir_insn->prev;
587 // Overwrite the kOpCheck insn with the paired opcode
588 DCHECK_EQ(bb_next->first_mir_insn, throw_insn);
589 *bb->last_mir_insn = *throw_insn;
590 bb->last_mir_insn->prev = t_mir;
591 // Use the successor info from the next block
592 bb->successor_block_list = bb_next->successor_block_list;
593 // Use the ending block linkage from the next block
594 bb->fall_through = bb_next->fall_through;
595 bb->taken->block_type = kDead; // Kill the unused exception block
596 bb->taken = bb_next->taken;
597 // Include the rest of the instructions
598 bb->last_mir_insn = bb_next->last_mir_insn;
599 /*
600 * If lower-half of pair of blocks to combine contained a return, move the flag
601 * to the newly combined block.
602 */
603 bb->terminated_by_return = bb_next->terminated_by_return;
604
605 /*
606 * NOTE: we aren't updating all dataflow info here. Should either make sure this pass
607 * happens after uses of i_dominated, dom_frontier or update the dataflow info here.
608 */
609
610 // Kill bb_next and remap now-dead id to parent
611 bb_next->block_type = kDead;
buzbee1fd33462013-03-25 13:40:45 -0700612 block_id_map_.Overwrite(bb_next->id, bb->id);
buzbee311ca162013-02-28 15:56:43 -0800613
614 // Now, loop back and see if we can keep going
615 }
616 return false;
617}
618
619/* Eliminate unnecessary null checks for a basic block. */
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700620bool MIRGraph::EliminateNullChecks(struct BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800621 if (bb->data_flow_info == NULL) return false;
622
623 /*
624 * Set initial state. Be conservative with catch
625 * blocks and start with no assumptions about null check
626 * status (except for "this").
627 */
628 if ((bb->block_type == kEntryBlock) | bb->catch_entry) {
buzbee862a7602013-04-05 10:58:54 -0700629 temp_ssa_register_v_->ClearAllBits();
buzbee311ca162013-02-28 15:56:43 -0800630 if ((cu_->access_flags & kAccStatic) == 0) {
631 // If non-static method, mark "this" as non-null
632 int this_reg = cu_->num_dalvik_registers - cu_->num_ins;
buzbee862a7602013-04-05 10:58:54 -0700633 temp_ssa_register_v_->SetBit(this_reg);
buzbee311ca162013-02-28 15:56:43 -0800634 }
Ian Rogers22fd6a02013-06-13 15:06:54 -0700635 } else if (bb->predecessors->Size() == 1) {
636 BasicBlock* pred_bb = bb->predecessors->Get(0);
637 temp_ssa_register_v_->Copy(pred_bb->data_flow_info->ending_null_check_v);
638 if (pred_bb->block_type == kDalvikByteCode) {
639 // Check to see if predecessor had an explicit null-check.
640 MIR* last_insn = pred_bb->last_mir_insn;
641 Instruction::Code last_opcode = last_insn->dalvikInsn.opcode;
642 if (last_opcode == Instruction::IF_EQZ) {
643 if (pred_bb->fall_through == bb) {
644 // The fall-through of a block following a IF_EQZ, set the vA of the IF_EQZ to show that
645 // it can't be null.
646 temp_ssa_register_v_->SetBit(last_insn->ssa_rep->uses[0]);
647 }
648 } else if (last_opcode == Instruction::IF_NEZ) {
649 if (pred_bb->taken == bb) {
650 // The taken block following a IF_NEZ, set the vA of the IF_NEZ to show that it can't be
651 // null.
652 temp_ssa_register_v_->SetBit(last_insn->ssa_rep->uses[0]);
653 }
654 }
655 }
buzbee311ca162013-02-28 15:56:43 -0800656 } else {
Ian Rogers22fd6a02013-06-13 15:06:54 -0700657 // Starting state is intersection of all incoming arcs
buzbee862a7602013-04-05 10:58:54 -0700658 GrowableArray<BasicBlock*>::Iterator iter(bb->predecessors);
659 BasicBlock* pred_bb = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800660 DCHECK(pred_bb != NULL);
buzbee862a7602013-04-05 10:58:54 -0700661 temp_ssa_register_v_->Copy(pred_bb->data_flow_info->ending_null_check_v);
buzbee311ca162013-02-28 15:56:43 -0800662 while (true) {
buzbee862a7602013-04-05 10:58:54 -0700663 pred_bb = iter.Next();
buzbee311ca162013-02-28 15:56:43 -0800664 if (!pred_bb) break;
665 if ((pred_bb->data_flow_info == NULL) ||
666 (pred_bb->data_flow_info->ending_null_check_v == NULL)) {
667 continue;
668 }
buzbee862a7602013-04-05 10:58:54 -0700669 temp_ssa_register_v_->Intersect(pred_bb->data_flow_info->ending_null_check_v);
buzbee311ca162013-02-28 15:56:43 -0800670 }
671 }
672
673 // Walk through the instruction in the block, updating as necessary
674 for (MIR* mir = bb->first_mir_insn; mir != NULL; mir = mir->next) {
675 if (mir->ssa_rep == NULL) {
676 continue;
677 }
buzbee1fd33462013-03-25 13:40:45 -0700678 int df_attributes = oat_data_flow_attributes_[mir->dalvikInsn.opcode];
buzbee311ca162013-02-28 15:56:43 -0800679
680 // Mark target of NEW* as non-null
681 if (df_attributes & DF_NON_NULL_DST) {
buzbee862a7602013-04-05 10:58:54 -0700682 temp_ssa_register_v_->SetBit(mir->ssa_rep->defs[0]);
buzbee311ca162013-02-28 15:56:43 -0800683 }
684
685 // Mark non-null returns from invoke-style NEW*
686 if (df_attributes & DF_NON_NULL_RET) {
687 MIR* next_mir = mir->next;
688 // Next should be an MOVE_RESULT_OBJECT
689 if (next_mir &&
690 next_mir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) {
691 // Mark as null checked
buzbee862a7602013-04-05 10:58:54 -0700692 temp_ssa_register_v_->SetBit(next_mir->ssa_rep->defs[0]);
buzbee311ca162013-02-28 15:56:43 -0800693 } else {
694 if (next_mir) {
695 LOG(WARNING) << "Unexpected opcode following new: " << next_mir->dalvikInsn.opcode;
696 } else if (bb->fall_through) {
697 // Look in next basic block
698 struct BasicBlock* next_bb = bb->fall_through;
699 for (MIR* tmir = next_bb->first_mir_insn; tmir != NULL;
700 tmir =tmir->next) {
701 if (static_cast<int>(tmir->dalvikInsn.opcode) >= static_cast<int>(kMirOpFirst)) {
702 continue;
703 }
704 // First non-pseudo should be MOVE_RESULT_OBJECT
705 if (tmir->dalvikInsn.opcode == Instruction::MOVE_RESULT_OBJECT) {
706 // Mark as null checked
buzbee862a7602013-04-05 10:58:54 -0700707 temp_ssa_register_v_->SetBit(tmir->ssa_rep->defs[0]);
buzbee311ca162013-02-28 15:56:43 -0800708 } else {
709 LOG(WARNING) << "Unexpected op after new: " << tmir->dalvikInsn.opcode;
710 }
711 break;
712 }
713 }
714 }
715 }
716
717 /*
718 * Propagate nullcheck state on register copies (including
719 * Phi pseudo copies. For the latter, nullcheck state is
720 * the "and" of all the Phi's operands.
721 */
722 if (df_attributes & (DF_NULL_TRANSFER_0 | DF_NULL_TRANSFER_N)) {
723 int tgt_sreg = mir->ssa_rep->defs[0];
724 int operands = (df_attributes & DF_NULL_TRANSFER_0) ? 1 :
725 mir->ssa_rep->num_uses;
726 bool null_checked = true;
727 for (int i = 0; i < operands; i++) {
buzbee862a7602013-04-05 10:58:54 -0700728 null_checked &= temp_ssa_register_v_->IsBitSet(mir->ssa_rep->uses[i]);
buzbee311ca162013-02-28 15:56:43 -0800729 }
730 if (null_checked) {
buzbee862a7602013-04-05 10:58:54 -0700731 temp_ssa_register_v_->SetBit(tgt_sreg);
buzbee311ca162013-02-28 15:56:43 -0800732 }
733 }
734
735 // Already nullchecked?
736 if ((df_attributes & DF_HAS_NULL_CHKS) && !(mir->optimization_flags & MIR_IGNORE_NULL_CHECK)) {
737 int src_idx;
738 if (df_attributes & DF_NULL_CHK_1) {
739 src_idx = 1;
740 } else if (df_attributes & DF_NULL_CHK_2) {
741 src_idx = 2;
742 } else {
743 src_idx = 0;
744 }
745 int src_sreg = mir->ssa_rep->uses[src_idx];
buzbee862a7602013-04-05 10:58:54 -0700746 if (temp_ssa_register_v_->IsBitSet(src_sreg)) {
buzbee311ca162013-02-28 15:56:43 -0800747 // Eliminate the null check
748 mir->optimization_flags |= MIR_IGNORE_NULL_CHECK;
749 } else {
750 // Mark s_reg as null-checked
buzbee862a7602013-04-05 10:58:54 -0700751 temp_ssa_register_v_->SetBit(src_sreg);
buzbee311ca162013-02-28 15:56:43 -0800752 }
753 }
754 }
755
756 // Did anything change?
buzbee862a7602013-04-05 10:58:54 -0700757 bool changed = !temp_ssa_register_v_->Equal(bb->data_flow_info->ending_null_check_v);
758 if (changed) {
759 bb->data_flow_info->ending_null_check_v->Copy(temp_ssa_register_v_);
buzbee311ca162013-02-28 15:56:43 -0800760 }
buzbee862a7602013-04-05 10:58:54 -0700761 return changed;
buzbee311ca162013-02-28 15:56:43 -0800762}
763
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700764void MIRGraph::NullCheckElimination() {
buzbee311ca162013-02-28 15:56:43 -0800765 if (!(cu_->disable_opt & (1 << kNullCheckElimination))) {
766 DCHECK(temp_ssa_register_v_ != NULL);
buzbee0665fe02013-03-21 12:32:21 -0700767 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800768 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
769 NullCheckEliminationInit(bb);
770 }
buzbee0665fe02013-03-21 12:32:21 -0700771 PreOrderDfsIterator iter2(this, true /* iterative */);
buzbee311ca162013-02-28 15:56:43 -0800772 bool change = false;
773 for (BasicBlock* bb = iter2.Next(change); bb != NULL; bb = iter2.Next(change)) {
774 change = EliminateNullChecks(bb);
775 }
776 }
777 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
778 DumpCFG("/sdcard/4_post_nce_cfg/", false);
779 }
780}
781
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700782void MIRGraph::BasicBlockCombine() {
buzbee0665fe02013-03-21 12:32:21 -0700783 PreOrderDfsIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800784 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
785 CombineBlocks(bb);
786 }
787 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
788 DumpCFG("/sdcard/5_post_bbcombine_cfg/", false);
789 }
790}
791
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700792void MIRGraph::CodeLayout() {
buzbee1fd33462013-03-25 13:40:45 -0700793 if (cu_->enable_debug & (1 << kDebugVerifyDataflow)) {
794 VerifyDataflow();
795 }
buzbee0665fe02013-03-21 12:32:21 -0700796 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800797 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
798 LayoutBlocks(bb);
799 }
800 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
801 DumpCFG("/sdcard/2_post_layout_cfg/", true);
802 }
803}
804
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700805void MIRGraph::DumpCheckStats() {
buzbee311ca162013-02-28 15:56:43 -0800806 Checkstats* stats =
buzbee862a7602013-04-05 10:58:54 -0700807 static_cast<Checkstats*>(arena_->NewMem(sizeof(Checkstats), true,
808 ArenaAllocator::kAllocDFInfo));
buzbee1fd33462013-03-25 13:40:45 -0700809 checkstats_ = stats;
buzbee0665fe02013-03-21 12:32:21 -0700810 AllNodesIterator iter(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800811 for (BasicBlock* bb = iter.Next(); bb != NULL; bb = iter.Next()) {
812 CountChecks(bb);
813 }
814 if (stats->null_checks > 0) {
815 float eliminated = static_cast<float>(stats->null_checks_eliminated);
816 float checks = static_cast<float>(stats->null_checks);
817 LOG(INFO) << "Null Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
818 << stats->null_checks_eliminated << " of " << stats->null_checks << " -> "
819 << (eliminated/checks) * 100.0 << "%";
820 }
821 if (stats->range_checks > 0) {
822 float eliminated = static_cast<float>(stats->range_checks_eliminated);
823 float checks = static_cast<float>(stats->range_checks);
824 LOG(INFO) << "Range Checks: " << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
825 << stats->range_checks_eliminated << " of " << stats->range_checks << " -> "
826 << (eliminated/checks) * 100.0 << "%";
827 }
828}
829
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700830bool MIRGraph::BuildExtendedBBList(struct BasicBlock* bb) {
buzbee311ca162013-02-28 15:56:43 -0800831 if (bb->visited) return false;
832 if (!((bb->block_type == kEntryBlock) || (bb->block_type == kDalvikByteCode)
833 || (bb->block_type == kExitBlock))) {
834 // Ignore special blocks
835 bb->visited = true;
836 return false;
837 }
838 // Must be head of extended basic block.
839 BasicBlock* start_bb = bb;
840 extended_basic_blocks_.push_back(bb);
841 bool terminated_by_return = false;
842 // Visit blocks strictly dominated by this head.
843 while (bb != NULL) {
844 bb->visited = true;
845 terminated_by_return |= bb->terminated_by_return;
846 bb = NextDominatedBlock(bb);
847 }
848 if (terminated_by_return) {
849 // This extended basic block contains a return, so mark all members.
850 bb = start_bb;
851 while (bb != NULL) {
852 bb->dominates_return = true;
853 bb = NextDominatedBlock(bb);
854 }
855 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700856 return false; // Not iterative - return value will be ignored
buzbee311ca162013-02-28 15:56:43 -0800857}
858
859
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700860void MIRGraph::BasicBlockOptimization() {
buzbee311ca162013-02-28 15:56:43 -0800861 if (!(cu_->disable_opt & (1 << kBBOpt))) {
buzbee311ca162013-02-28 15:56:43 -0800862 DCHECK_EQ(cu_->num_compiler_temps, 0);
buzbeea5abf702013-04-12 14:39:29 -0700863 ClearAllVisitedFlags();
buzbee0665fe02013-03-21 12:32:21 -0700864 PreOrderDfsIterator iter2(this, false /* not iterative */);
buzbee311ca162013-02-28 15:56:43 -0800865 for (BasicBlock* bb = iter2.Next(); bb != NULL; bb = iter2.Next()) {
866 BuildExtendedBBList(bb);
867 }
868 // Perform extended basic block optimizations.
869 for (unsigned int i = 0; i < extended_basic_blocks_.size(); i++) {
870 BasicBlockOpt(extended_basic_blocks_[i]);
871 }
872 }
873 if (cu_->enable_debug & (1 << kDebugDumpCFG)) {
874 DumpCFG("/sdcard/6_post_bbo_cfg/", false);
875 }
876}
877
878} // namespace art