blob: afac5f9cf1e0bfd94b8e193c2e9c1ed11e48fde6 [file] [log] [blame]
David Brazdildee58d62016-04-07 09:54:26 +00001/*
2 * Copyright (C) 2016 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 "instruction_builder.h"
18
Matthew Gharrity465ecc82016-07-19 21:32:52 +000019#include "art_method-inl.h"
David Brazdildee58d62016-04-07 09:54:26 +000020#include "bytecode_utils.h"
21#include "class_linker.h"
22#include "driver/compiler_options.h"
23#include "scoped_thread_state_change.h"
24
25namespace art {
26
27void HInstructionBuilder::MaybeRecordStat(MethodCompilationStat compilation_stat) {
28 if (compilation_stats_ != nullptr) {
29 compilation_stats_->RecordStat(compilation_stat);
30 }
31}
32
33HBasicBlock* HInstructionBuilder::FindBlockStartingAt(uint32_t dex_pc) const {
34 return block_builder_->GetBlockAt(dex_pc);
35}
36
37ArenaVector<HInstruction*>* HInstructionBuilder::GetLocalsFor(HBasicBlock* block) {
38 ArenaVector<HInstruction*>* locals = &locals_for_[block->GetBlockId()];
39 const size_t vregs = graph_->GetNumberOfVRegs();
40 if (locals->size() != vregs) {
41 locals->resize(vregs, nullptr);
42
43 if (block->IsCatchBlock()) {
44 // We record incoming inputs of catch phis at throwing instructions and
45 // must therefore eagerly create the phis. Phis for undefined vregs will
46 // be deleted when the first throwing instruction with the vreg undefined
47 // is encountered. Unused phis will be removed by dead phi analysis.
48 for (size_t i = 0; i < vregs; ++i) {
49 // No point in creating the catch phi if it is already undefined at
50 // the first throwing instruction.
51 HInstruction* current_local_value = (*current_locals_)[i];
52 if (current_local_value != nullptr) {
53 HPhi* phi = new (arena_) HPhi(
54 arena_,
55 i,
56 0,
57 current_local_value->GetType());
58 block->AddPhi(phi);
59 (*locals)[i] = phi;
60 }
61 }
62 }
63 }
64 return locals;
65}
66
67HInstruction* HInstructionBuilder::ValueOfLocalAt(HBasicBlock* block, size_t local) {
68 ArenaVector<HInstruction*>* locals = GetLocalsFor(block);
69 return (*locals)[local];
70}
71
72void HInstructionBuilder::InitializeBlockLocals() {
73 current_locals_ = GetLocalsFor(current_block_);
74
75 if (current_block_->IsCatchBlock()) {
76 // Catch phis were already created and inputs collected from throwing sites.
77 if (kIsDebugBuild) {
78 // Make sure there was at least one throwing instruction which initialized
79 // locals (guaranteed by HGraphBuilder) and that all try blocks have been
80 // visited already (from HTryBoundary scoping and reverse post order).
81 bool catch_block_visited = false;
82 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
83 HBasicBlock* current = it.Current();
84 if (current == current_block_) {
85 catch_block_visited = true;
86 } else if (current->IsTryBlock()) {
87 const HTryBoundary& try_entry = current->GetTryCatchInformation()->GetTryEntry();
88 if (try_entry.HasExceptionHandler(*current_block_)) {
89 DCHECK(!catch_block_visited) << "Catch block visited before its try block.";
90 }
91 }
92 }
93 DCHECK_EQ(current_locals_->size(), graph_->GetNumberOfVRegs())
94 << "No instructions throwing into a live catch block.";
95 }
96 } else if (current_block_->IsLoopHeader()) {
97 // If the block is a loop header, we know we only have visited the pre header
98 // because we are visiting in reverse post order. We create phis for all initialized
99 // locals from the pre header. Their inputs will be populated at the end of
100 // the analysis.
101 for (size_t local = 0; local < current_locals_->size(); ++local) {
102 HInstruction* incoming =
103 ValueOfLocalAt(current_block_->GetLoopInformation()->GetPreHeader(), local);
104 if (incoming != nullptr) {
105 HPhi* phi = new (arena_) HPhi(
106 arena_,
107 local,
108 0,
109 incoming->GetType());
110 current_block_->AddPhi(phi);
111 (*current_locals_)[local] = phi;
112 }
113 }
114
115 // Save the loop header so that the last phase of the analysis knows which
116 // blocks need to be updated.
117 loop_headers_.push_back(current_block_);
118 } else if (current_block_->GetPredecessors().size() > 0) {
119 // All predecessors have already been visited because we are visiting in reverse post order.
120 // We merge the values of all locals, creating phis if those values differ.
121 for (size_t local = 0; local < current_locals_->size(); ++local) {
122 bool one_predecessor_has_no_value = false;
123 bool is_different = false;
124 HInstruction* value = ValueOfLocalAt(current_block_->GetPredecessors()[0], local);
125
126 for (HBasicBlock* predecessor : current_block_->GetPredecessors()) {
127 HInstruction* current = ValueOfLocalAt(predecessor, local);
128 if (current == nullptr) {
129 one_predecessor_has_no_value = true;
130 break;
131 } else if (current != value) {
132 is_different = true;
133 }
134 }
135
136 if (one_predecessor_has_no_value) {
137 // If one predecessor has no value for this local, we trust the verifier has
138 // successfully checked that there is a store dominating any read after this block.
139 continue;
140 }
141
142 if (is_different) {
143 HInstruction* first_input = ValueOfLocalAt(current_block_->GetPredecessors()[0], local);
144 HPhi* phi = new (arena_) HPhi(
145 arena_,
146 local,
147 current_block_->GetPredecessors().size(),
148 first_input->GetType());
149 for (size_t i = 0; i < current_block_->GetPredecessors().size(); i++) {
150 HInstruction* pred_value = ValueOfLocalAt(current_block_->GetPredecessors()[i], local);
151 phi->SetRawInputAt(i, pred_value);
152 }
153 current_block_->AddPhi(phi);
154 value = phi;
155 }
156 (*current_locals_)[local] = value;
157 }
158 }
159}
160
161void HInstructionBuilder::PropagateLocalsToCatchBlocks() {
162 const HTryBoundary& try_entry = current_block_->GetTryCatchInformation()->GetTryEntry();
163 for (HBasicBlock* catch_block : try_entry.GetExceptionHandlers()) {
164 ArenaVector<HInstruction*>* handler_locals = GetLocalsFor(catch_block);
165 DCHECK_EQ(handler_locals->size(), current_locals_->size());
166 for (size_t vreg = 0, e = current_locals_->size(); vreg < e; ++vreg) {
167 HInstruction* handler_value = (*handler_locals)[vreg];
168 if (handler_value == nullptr) {
169 // Vreg was undefined at a previously encountered throwing instruction
170 // and the catch phi was deleted. Do not record the local value.
171 continue;
172 }
173 DCHECK(handler_value->IsPhi());
174
175 HInstruction* local_value = (*current_locals_)[vreg];
176 if (local_value == nullptr) {
177 // This is the first instruction throwing into `catch_block` where
178 // `vreg` is undefined. Delete the catch phi.
179 catch_block->RemovePhi(handler_value->AsPhi());
180 (*handler_locals)[vreg] = nullptr;
181 } else {
182 // Vreg has been defined at all instructions throwing into `catch_block`
183 // encountered so far. Record the local value in the catch phi.
184 handler_value->AsPhi()->AddInput(local_value);
185 }
186 }
187 }
188}
189
190void HInstructionBuilder::AppendInstruction(HInstruction* instruction) {
191 current_block_->AddInstruction(instruction);
192 InitializeInstruction(instruction);
193}
194
195void HInstructionBuilder::InsertInstructionAtTop(HInstruction* instruction) {
196 if (current_block_->GetInstructions().IsEmpty()) {
197 current_block_->AddInstruction(instruction);
198 } else {
199 current_block_->InsertInstructionBefore(instruction, current_block_->GetFirstInstruction());
200 }
201 InitializeInstruction(instruction);
202}
203
204void HInstructionBuilder::InitializeInstruction(HInstruction* instruction) {
205 if (instruction->NeedsEnvironment()) {
206 HEnvironment* environment = new (arena_) HEnvironment(
207 arena_,
208 current_locals_->size(),
209 graph_->GetDexFile(),
210 graph_->GetMethodIdx(),
211 instruction->GetDexPc(),
212 graph_->GetInvokeType(),
213 instruction);
214 environment->CopyFrom(*current_locals_);
215 instruction->SetRawEnvironment(environment);
216 }
217}
218
David Brazdilc120bbe2016-04-22 16:57:00 +0100219HInstruction* HInstructionBuilder::LoadNullCheckedLocal(uint32_t register_index, uint32_t dex_pc) {
220 HInstruction* ref = LoadLocal(register_index, Primitive::kPrimNot);
221 if (!ref->CanBeNull()) {
222 return ref;
223 }
224
225 HNullCheck* null_check = new (arena_) HNullCheck(ref, dex_pc);
226 AppendInstruction(null_check);
227 return null_check;
228}
229
David Brazdildee58d62016-04-07 09:54:26 +0000230void HInstructionBuilder::SetLoopHeaderPhiInputs() {
231 for (size_t i = loop_headers_.size(); i > 0; --i) {
232 HBasicBlock* block = loop_headers_[i - 1];
233 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
234 HPhi* phi = it.Current()->AsPhi();
235 size_t vreg = phi->GetRegNumber();
236 for (HBasicBlock* predecessor : block->GetPredecessors()) {
237 HInstruction* value = ValueOfLocalAt(predecessor, vreg);
238 if (value == nullptr) {
239 // Vreg is undefined at this predecessor. Mark it dead and leave with
240 // fewer inputs than predecessors. SsaChecker will fail if not removed.
241 phi->SetDead();
242 break;
243 } else {
244 phi->AddInput(value);
245 }
246 }
247 }
248 }
249}
250
251static bool IsBlockPopulated(HBasicBlock* block) {
252 if (block->IsLoopHeader()) {
253 // Suspend checks were inserted into loop headers during building of dominator tree.
254 DCHECK(block->GetFirstInstruction()->IsSuspendCheck());
255 return block->GetFirstInstruction() != block->GetLastInstruction();
256 } else {
257 return !block->GetInstructions().IsEmpty();
258 }
259}
260
261bool HInstructionBuilder::Build() {
262 locals_for_.resize(graph_->GetBlocks().size(),
263 ArenaVector<HInstruction*>(arena_->Adapter(kArenaAllocGraphBuilder)));
264
265 // Find locations where we want to generate extra stackmaps for native debugging.
266 // This allows us to generate the info only at interesting points (for example,
267 // at start of java statement) rather than before every dex instruction.
268 const bool native_debuggable = compiler_driver_ != nullptr &&
269 compiler_driver_->GetCompilerOptions().GetNativeDebuggable();
270 ArenaBitVector* native_debug_info_locations = nullptr;
271 if (native_debuggable) {
272 const uint32_t num_instructions = code_item_.insns_size_in_code_units_;
273 native_debug_info_locations = new (arena_) ArenaBitVector (arena_, num_instructions, false);
274 FindNativeDebugInfoLocations(native_debug_info_locations);
275 }
276
277 for (HReversePostOrderIterator block_it(*graph_); !block_it.Done(); block_it.Advance()) {
278 current_block_ = block_it.Current();
279 uint32_t block_dex_pc = current_block_->GetDexPc();
280
281 InitializeBlockLocals();
282
283 if (current_block_->IsEntryBlock()) {
284 InitializeParameters();
285 AppendInstruction(new (arena_) HSuspendCheck(0u));
286 AppendInstruction(new (arena_) HGoto(0u));
287 continue;
288 } else if (current_block_->IsExitBlock()) {
289 AppendInstruction(new (arena_) HExit());
290 continue;
291 } else if (current_block_->IsLoopHeader()) {
292 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(current_block_->GetDexPc());
293 current_block_->GetLoopInformation()->SetSuspendCheck(suspend_check);
294 // This is slightly odd because the loop header might not be empty (TryBoundary).
295 // But we're still creating the environment with locals from the top of the block.
296 InsertInstructionAtTop(suspend_check);
297 }
298
299 if (block_dex_pc == kNoDexPc || current_block_ != block_builder_->GetBlockAt(block_dex_pc)) {
300 // Synthetic block that does not need to be populated.
301 DCHECK(IsBlockPopulated(current_block_));
302 continue;
303 }
304
305 DCHECK(!IsBlockPopulated(current_block_));
306
307 for (CodeItemIterator it(code_item_, block_dex_pc); !it.Done(); it.Advance()) {
308 if (current_block_ == nullptr) {
309 // The previous instruction ended this block.
310 break;
311 }
312
313 uint32_t dex_pc = it.CurrentDexPc();
314 if (dex_pc != block_dex_pc && FindBlockStartingAt(dex_pc) != nullptr) {
315 // This dex_pc starts a new basic block.
316 break;
317 }
318
319 if (current_block_->IsTryBlock() && IsThrowingDexInstruction(it.CurrentInstruction())) {
320 PropagateLocalsToCatchBlocks();
321 }
322
323 if (native_debuggable && native_debug_info_locations->IsBitSet(dex_pc)) {
324 AppendInstruction(new (arena_) HNativeDebugInfo(dex_pc));
325 }
326
327 if (!ProcessDexInstruction(it.CurrentInstruction(), dex_pc)) {
328 return false;
329 }
330 }
331
332 if (current_block_ != nullptr) {
333 // Branching instructions clear current_block, so we know the last
334 // instruction of the current block is not a branching instruction.
335 // We add an unconditional Goto to the next block.
336 DCHECK_EQ(current_block_->GetSuccessors().size(), 1u);
337 AppendInstruction(new (arena_) HGoto());
338 }
339 }
340
341 SetLoopHeaderPhiInputs();
342
343 return true;
344}
345
346void HInstructionBuilder::FindNativeDebugInfoLocations(ArenaBitVector* locations) {
347 // The callback gets called when the line number changes.
348 // In other words, it marks the start of new java statement.
349 struct Callback {
350 static bool Position(void* ctx, const DexFile::PositionInfo& entry) {
351 static_cast<ArenaBitVector*>(ctx)->SetBit(entry.address_);
352 return false;
353 }
354 };
355 dex_file_->DecodeDebugPositionInfo(&code_item_, Callback::Position, locations);
356 // Instruction-specific tweaks.
357 const Instruction* const begin = Instruction::At(code_item_.insns_);
358 const Instruction* const end = begin->RelativeAt(code_item_.insns_size_in_code_units_);
359 for (const Instruction* inst = begin; inst < end; inst = inst->Next()) {
360 switch (inst->Opcode()) {
361 case Instruction::MOVE_EXCEPTION: {
362 // Stop in native debugger after the exception has been moved.
363 // The compiler also expects the move at the start of basic block so
364 // we do not want to interfere by inserting native-debug-info before it.
365 locations->ClearBit(inst->GetDexPc(code_item_.insns_));
366 const Instruction* next = inst->Next();
367 if (next < end) {
368 locations->SetBit(next->GetDexPc(code_item_.insns_));
369 }
370 break;
371 }
372 default:
373 break;
374 }
375 }
376}
377
378HInstruction* HInstructionBuilder::LoadLocal(uint32_t reg_number, Primitive::Type type) const {
379 HInstruction* value = (*current_locals_)[reg_number];
380 DCHECK(value != nullptr);
381
382 // If the operation requests a specific type, we make sure its input is of that type.
383 if (type != value->GetType()) {
384 if (Primitive::IsFloatingPointType(type)) {
Aart Bik31883642016-06-06 15:02:44 -0700385 value = ssa_builder_->GetFloatOrDoubleEquivalent(value, type);
David Brazdildee58d62016-04-07 09:54:26 +0000386 } else if (type == Primitive::kPrimNot) {
Aart Bik31883642016-06-06 15:02:44 -0700387 value = ssa_builder_->GetReferenceTypeEquivalent(value);
David Brazdildee58d62016-04-07 09:54:26 +0000388 }
Aart Bik31883642016-06-06 15:02:44 -0700389 DCHECK(value != nullptr);
David Brazdildee58d62016-04-07 09:54:26 +0000390 }
391
392 return value;
393}
394
395void HInstructionBuilder::UpdateLocal(uint32_t reg_number, HInstruction* stored_value) {
396 Primitive::Type stored_type = stored_value->GetType();
397 DCHECK_NE(stored_type, Primitive::kPrimVoid);
398
399 // Storing into vreg `reg_number` may implicitly invalidate the surrounding
400 // registers. Consider the following cases:
401 // (1) Storing a wide value must overwrite previous values in both `reg_number`
402 // and `reg_number+1`. We store `nullptr` in `reg_number+1`.
403 // (2) If vreg `reg_number-1` holds a wide value, writing into `reg_number`
404 // must invalidate it. We store `nullptr` in `reg_number-1`.
405 // Consequently, storing a wide value into the high vreg of another wide value
406 // will invalidate both `reg_number-1` and `reg_number+1`.
407
408 if (reg_number != 0) {
409 HInstruction* local_low = (*current_locals_)[reg_number - 1];
410 if (local_low != nullptr && Primitive::Is64BitType(local_low->GetType())) {
411 // The vreg we are storing into was previously the high vreg of a pair.
412 // We need to invalidate its low vreg.
413 DCHECK((*current_locals_)[reg_number] == nullptr);
414 (*current_locals_)[reg_number - 1] = nullptr;
415 }
416 }
417
418 (*current_locals_)[reg_number] = stored_value;
419 if (Primitive::Is64BitType(stored_type)) {
420 // We are storing a pair. Invalidate the instruction in the high vreg.
421 (*current_locals_)[reg_number + 1] = nullptr;
422 }
423}
424
425void HInstructionBuilder::InitializeParameters() {
426 DCHECK(current_block_->IsEntryBlock());
427
428 // dex_compilation_unit_ is null only when unit testing.
429 if (dex_compilation_unit_ == nullptr) {
430 return;
431 }
432
433 const char* shorty = dex_compilation_unit_->GetShorty();
434 uint16_t number_of_parameters = graph_->GetNumberOfInVRegs();
435 uint16_t locals_index = graph_->GetNumberOfLocalVRegs();
436 uint16_t parameter_index = 0;
437
438 const DexFile::MethodId& referrer_method_id =
439 dex_file_->GetMethodId(dex_compilation_unit_->GetDexMethodIndex());
440 if (!dex_compilation_unit_->IsStatic()) {
441 // Add the implicit 'this' argument, not expressed in the signature.
442 HParameterValue* parameter = new (arena_) HParameterValue(*dex_file_,
443 referrer_method_id.class_idx_,
444 parameter_index++,
445 Primitive::kPrimNot,
446 true);
447 AppendInstruction(parameter);
448 UpdateLocal(locals_index++, parameter);
449 number_of_parameters--;
450 }
451
452 const DexFile::ProtoId& proto = dex_file_->GetMethodPrototype(referrer_method_id);
453 const DexFile::TypeList* arg_types = dex_file_->GetProtoParameters(proto);
454 for (int i = 0, shorty_pos = 1; i < number_of_parameters; i++) {
455 HParameterValue* parameter = new (arena_) HParameterValue(
456 *dex_file_,
457 arg_types->GetTypeItem(shorty_pos - 1).type_idx_,
458 parameter_index++,
459 Primitive::GetType(shorty[shorty_pos]),
460 false);
461 ++shorty_pos;
462 AppendInstruction(parameter);
463 // Store the parameter value in the local that the dex code will use
464 // to reference that parameter.
465 UpdateLocal(locals_index++, parameter);
466 if (Primitive::Is64BitType(parameter->GetType())) {
467 i++;
468 locals_index++;
469 parameter_index++;
470 }
471 }
472}
473
474template<typename T>
475void HInstructionBuilder::If_22t(const Instruction& instruction, uint32_t dex_pc) {
476 HInstruction* first = LoadLocal(instruction.VRegA(), Primitive::kPrimInt);
477 HInstruction* second = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
478 T* comparison = new (arena_) T(first, second, dex_pc);
479 AppendInstruction(comparison);
480 AppendInstruction(new (arena_) HIf(comparison, dex_pc));
481 current_block_ = nullptr;
482}
483
484template<typename T>
485void HInstructionBuilder::If_21t(const Instruction& instruction, uint32_t dex_pc) {
486 HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt);
487 T* comparison = new (arena_) T(value, graph_->GetIntConstant(0, dex_pc), dex_pc);
488 AppendInstruction(comparison);
489 AppendInstruction(new (arena_) HIf(comparison, dex_pc));
490 current_block_ = nullptr;
491}
492
493template<typename T>
494void HInstructionBuilder::Unop_12x(const Instruction& instruction,
495 Primitive::Type type,
496 uint32_t dex_pc) {
497 HInstruction* first = LoadLocal(instruction.VRegB(), type);
498 AppendInstruction(new (arena_) T(type, first, dex_pc));
499 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
500}
501
502void HInstructionBuilder::Conversion_12x(const Instruction& instruction,
503 Primitive::Type input_type,
504 Primitive::Type result_type,
505 uint32_t dex_pc) {
506 HInstruction* first = LoadLocal(instruction.VRegB(), input_type);
507 AppendInstruction(new (arena_) HTypeConversion(result_type, first, dex_pc));
508 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
509}
510
511template<typename T>
512void HInstructionBuilder::Binop_23x(const Instruction& instruction,
513 Primitive::Type type,
514 uint32_t dex_pc) {
515 HInstruction* first = LoadLocal(instruction.VRegB(), type);
516 HInstruction* second = LoadLocal(instruction.VRegC(), type);
517 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
518 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
519}
520
521template<typename T>
522void HInstructionBuilder::Binop_23x_shift(const Instruction& instruction,
523 Primitive::Type type,
524 uint32_t dex_pc) {
525 HInstruction* first = LoadLocal(instruction.VRegB(), type);
526 HInstruction* second = LoadLocal(instruction.VRegC(), Primitive::kPrimInt);
527 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
528 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
529}
530
531void HInstructionBuilder::Binop_23x_cmp(const Instruction& instruction,
532 Primitive::Type type,
533 ComparisonBias bias,
534 uint32_t dex_pc) {
535 HInstruction* first = LoadLocal(instruction.VRegB(), type);
536 HInstruction* second = LoadLocal(instruction.VRegC(), type);
537 AppendInstruction(new (arena_) HCompare(type, first, second, bias, dex_pc));
538 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
539}
540
541template<typename T>
542void HInstructionBuilder::Binop_12x_shift(const Instruction& instruction,
543 Primitive::Type type,
544 uint32_t dex_pc) {
545 HInstruction* first = LoadLocal(instruction.VRegA(), type);
546 HInstruction* second = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
547 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
548 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
549}
550
551template<typename T>
552void HInstructionBuilder::Binop_12x(const Instruction& instruction,
553 Primitive::Type type,
554 uint32_t dex_pc) {
555 HInstruction* first = LoadLocal(instruction.VRegA(), type);
556 HInstruction* second = LoadLocal(instruction.VRegB(), type);
557 AppendInstruction(new (arena_) T(type, first, second, dex_pc));
558 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
559}
560
561template<typename T>
562void HInstructionBuilder::Binop_22s(const Instruction& instruction, bool reverse, uint32_t dex_pc) {
563 HInstruction* first = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
564 HInstruction* second = graph_->GetIntConstant(instruction.VRegC_22s(), dex_pc);
565 if (reverse) {
566 std::swap(first, second);
567 }
568 AppendInstruction(new (arena_) T(Primitive::kPrimInt, first, second, dex_pc));
569 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
570}
571
572template<typename T>
573void HInstructionBuilder::Binop_22b(const Instruction& instruction, bool reverse, uint32_t dex_pc) {
574 HInstruction* first = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
575 HInstruction* second = graph_->GetIntConstant(instruction.VRegC_22b(), dex_pc);
576 if (reverse) {
577 std::swap(first, second);
578 }
579 AppendInstruction(new (arena_) T(Primitive::kPrimInt, first, second, dex_pc));
580 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
581}
582
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700583static bool RequiresConstructorBarrier(const DexCompilationUnit* cu, CompilerDriver* driver) {
David Brazdildee58d62016-04-07 09:54:26 +0000584 Thread* self = Thread::Current();
585 return cu->IsConstructor()
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700586 && driver->RequiresConstructorBarrier(self, cu->GetDexFile(), cu->GetClassDefIndex());
David Brazdildee58d62016-04-07 09:54:26 +0000587}
588
589// Returns true if `block` has only one successor which starts at the next
590// dex_pc after `instruction` at `dex_pc`.
591static bool IsFallthroughInstruction(const Instruction& instruction,
592 uint32_t dex_pc,
593 HBasicBlock* block) {
594 uint32_t next_dex_pc = dex_pc + instruction.SizeInCodeUnits();
595 return block->GetSingleSuccessor()->GetDexPc() == next_dex_pc;
596}
597
598void HInstructionBuilder::BuildSwitch(const Instruction& instruction, uint32_t dex_pc) {
599 HInstruction* value = LoadLocal(instruction.VRegA(), Primitive::kPrimInt);
600 DexSwitchTable table(instruction, dex_pc);
601
602 if (table.GetNumEntries() == 0) {
603 // Empty Switch. Code falls through to the next block.
604 DCHECK(IsFallthroughInstruction(instruction, dex_pc, current_block_));
605 AppendInstruction(new (arena_) HGoto(dex_pc));
606 } else if (table.ShouldBuildDecisionTree()) {
607 for (DexSwitchTableIterator it(table); !it.Done(); it.Advance()) {
608 HInstruction* case_value = graph_->GetIntConstant(it.CurrentKey(), dex_pc);
609 HEqual* comparison = new (arena_) HEqual(value, case_value, dex_pc);
610 AppendInstruction(comparison);
611 AppendInstruction(new (arena_) HIf(comparison, dex_pc));
612
613 if (!it.IsLast()) {
614 current_block_ = FindBlockStartingAt(it.GetDexPcForCurrentIndex());
615 }
616 }
617 } else {
618 AppendInstruction(
619 new (arena_) HPackedSwitch(table.GetEntryAt(0), table.GetNumEntries(), value, dex_pc));
620 }
621
622 current_block_ = nullptr;
623}
624
625void HInstructionBuilder::BuildReturn(const Instruction& instruction,
626 Primitive::Type type,
627 uint32_t dex_pc) {
628 if (type == Primitive::kPrimVoid) {
629 if (graph_->ShouldGenerateConstructorBarrier()) {
630 // The compilation unit is null during testing.
631 if (dex_compilation_unit_ != nullptr) {
Mathieu Chartierc4ae9162016-04-07 13:19:19 -0700632 DCHECK(RequiresConstructorBarrier(dex_compilation_unit_, compiler_driver_))
David Brazdildee58d62016-04-07 09:54:26 +0000633 << "Inconsistent use of ShouldGenerateConstructorBarrier. Should not generate a barrier.";
634 }
635 AppendInstruction(new (arena_) HMemoryBarrier(kStoreStore, dex_pc));
636 }
637 AppendInstruction(new (arena_) HReturnVoid(dex_pc));
638 } else {
639 HInstruction* value = LoadLocal(instruction.VRegA(), type);
640 AppendInstruction(new (arena_) HReturn(value, dex_pc));
641 }
642 current_block_ = nullptr;
643}
644
645static InvokeType GetInvokeTypeFromOpCode(Instruction::Code opcode) {
646 switch (opcode) {
647 case Instruction::INVOKE_STATIC:
648 case Instruction::INVOKE_STATIC_RANGE:
649 return kStatic;
650 case Instruction::INVOKE_DIRECT:
651 case Instruction::INVOKE_DIRECT_RANGE:
652 return kDirect;
653 case Instruction::INVOKE_VIRTUAL:
654 case Instruction::INVOKE_VIRTUAL_QUICK:
655 case Instruction::INVOKE_VIRTUAL_RANGE:
656 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK:
657 return kVirtual;
658 case Instruction::INVOKE_INTERFACE:
659 case Instruction::INVOKE_INTERFACE_RANGE:
660 return kInterface;
661 case Instruction::INVOKE_SUPER_RANGE:
662 case Instruction::INVOKE_SUPER:
663 return kSuper;
664 default:
665 LOG(FATAL) << "Unexpected invoke opcode: " << opcode;
666 UNREACHABLE();
667 }
668}
669
670ArtMethod* HInstructionBuilder::ResolveMethod(uint16_t method_idx, InvokeType invoke_type) {
671 ScopedObjectAccess soa(Thread::Current());
672 StackHandleScope<3> hs(soa.Self());
673
674 ClassLinker* class_linker = dex_compilation_unit_->GetClassLinker();
675 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
676 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
677 Handle<mirror::Class> compiling_class(hs.NewHandle(GetCompilingClass()));
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100678 // We fetch the referenced class eagerly (that is, the class pointed by in the MethodId
679 // at method_idx), as `CanAccessResolvedMethod` expects it be be in the dex cache.
680 Handle<mirror::Class> methods_class(hs.NewHandle(class_linker->ResolveReferencedClassOfMethod(
681 method_idx, dex_compilation_unit_->GetDexCache(), class_loader)));
682
683 if (UNLIKELY(methods_class.Get() == nullptr)) {
684 // Clean up any exception left by type resolution.
685 soa.Self()->ClearException();
686 return nullptr;
687 }
David Brazdildee58d62016-04-07 09:54:26 +0000688
689 ArtMethod* resolved_method = class_linker->ResolveMethod<ClassLinker::kForceICCECheck>(
690 *dex_compilation_unit_->GetDexFile(),
691 method_idx,
692 dex_compilation_unit_->GetDexCache(),
693 class_loader,
694 /* referrer */ nullptr,
695 invoke_type);
696
697 if (UNLIKELY(resolved_method == nullptr)) {
698 // Clean up any exception left by type resolution.
699 soa.Self()->ClearException();
700 return nullptr;
701 }
702
703 // Check access. The class linker has a fast path for looking into the dex cache
704 // and does not check the access if it hits it.
705 if (compiling_class.Get() == nullptr) {
706 if (!resolved_method->IsPublic()) {
707 return nullptr;
708 }
709 } else if (!compiling_class->CanAccessResolvedMethod(resolved_method->GetDeclaringClass(),
710 resolved_method,
711 dex_compilation_unit_->GetDexCache().Get(),
712 method_idx)) {
713 return nullptr;
714 }
715
716 // We have to special case the invoke-super case, as ClassLinker::ResolveMethod does not.
717 // We need to look at the referrer's super class vtable. We need to do this to know if we need to
718 // make this an invoke-unresolved to handle cross-dex invokes or abstract super methods, both of
719 // which require runtime handling.
720 if (invoke_type == kSuper) {
721 if (compiling_class.Get() == nullptr) {
722 // We could not determine the method's class we need to wait until runtime.
723 DCHECK(Runtime::Current()->IsAotCompiler());
724 return nullptr;
725 }
Aart Bikf663e342016-04-04 17:28:59 -0700726 if (!methods_class->IsAssignableFrom(compiling_class.Get())) {
727 // We cannot statically determine the target method. The runtime will throw a
728 // NoSuchMethodError on this one.
729 return nullptr;
730 }
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100731 ArtMethod* actual_method;
732 if (methods_class->IsInterface()) {
733 actual_method = methods_class->FindVirtualMethodForInterfaceSuper(
734 resolved_method, class_linker->GetImagePointerSize());
David Brazdildee58d62016-04-07 09:54:26 +0000735 } else {
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100736 uint16_t vtable_index = resolved_method->GetMethodIndex();
737 actual_method = compiling_class->GetSuperClass()->GetVTableEntry(
738 vtable_index, class_linker->GetImagePointerSize());
David Brazdildee58d62016-04-07 09:54:26 +0000739 }
Nicolas Geoffray393fdb82016-04-25 14:58:06 +0100740 if (actual_method != resolved_method &&
741 !IsSameDexFile(*actual_method->GetDexFile(), *dex_compilation_unit_->GetDexFile())) {
742 // The back-end code generator relies on this check in order to ensure that it will not
743 // attempt to read the dex_cache with a dex_method_index that is not from the correct
744 // dex_file. If we didn't do this check then the dex_method_index will not be updated in the
745 // builder, which means that the code-generator (and compiler driver during sharpening and
746 // inliner, maybe) might invoke an incorrect method.
747 // TODO: The actual method could still be referenced in the current dex file, so we
748 // could try locating it.
749 // TODO: Remove the dex_file restriction.
750 return nullptr;
751 }
752 if (!actual_method->IsInvokable()) {
753 // Fail if the actual method cannot be invoked. Otherwise, the runtime resolution stub
754 // could resolve the callee to the wrong method.
755 return nullptr;
756 }
757 resolved_method = actual_method;
David Brazdildee58d62016-04-07 09:54:26 +0000758 }
759
760 // Check for incompatible class changes. The class linker has a fast path for
761 // looking into the dex cache and does not check incompatible class changes if it hits it.
762 if (resolved_method->CheckIncompatibleClassChange(invoke_type)) {
763 return nullptr;
764 }
765
766 return resolved_method;
767}
768
769bool HInstructionBuilder::BuildInvoke(const Instruction& instruction,
770 uint32_t dex_pc,
771 uint32_t method_idx,
772 uint32_t number_of_vreg_arguments,
773 bool is_range,
774 uint32_t* args,
775 uint32_t register_index) {
776 InvokeType invoke_type = GetInvokeTypeFromOpCode(instruction.Opcode());
777 const char* descriptor = dex_file_->GetMethodShorty(method_idx);
778 Primitive::Type return_type = Primitive::GetType(descriptor[0]);
779
780 // Remove the return type from the 'proto'.
781 size_t number_of_arguments = strlen(descriptor) - 1;
782 if (invoke_type != kStatic) { // instance call
783 // One extra argument for 'this'.
784 number_of_arguments++;
785 }
786
787 MethodReference target_method(dex_file_, method_idx);
788
789 // Special handling for string init.
790 int32_t string_init_offset = 0;
791 bool is_string_init = compiler_driver_->IsStringInit(method_idx,
792 dex_file_,
793 &string_init_offset);
794 // Replace calls to String.<init> with StringFactory.
795 if (is_string_init) {
796 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
797 HInvokeStaticOrDirect::MethodLoadKind::kStringInit,
798 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
799 dchecked_integral_cast<uint64_t>(string_init_offset),
800 0U
801 };
802 HInvoke* invoke = new (arena_) HInvokeStaticOrDirect(
803 arena_,
804 number_of_arguments - 1,
805 Primitive::kPrimNot /*return_type */,
806 dex_pc,
807 method_idx,
808 target_method,
809 dispatch_info,
810 invoke_type,
811 kStatic /* optimized_invoke_type */,
812 HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit);
813 return HandleStringInit(invoke,
814 number_of_vreg_arguments,
815 args,
816 register_index,
817 is_range,
818 descriptor);
819 }
820
821 ArtMethod* resolved_method = ResolveMethod(method_idx, invoke_type);
822
823 if (UNLIKELY(resolved_method == nullptr)) {
824 MaybeRecordStat(MethodCompilationStat::kUnresolvedMethod);
825 HInvoke* invoke = new (arena_) HInvokeUnresolved(arena_,
826 number_of_arguments,
827 return_type,
828 dex_pc,
829 method_idx,
830 invoke_type);
831 return HandleInvoke(invoke,
832 number_of_vreg_arguments,
833 args,
834 register_index,
835 is_range,
836 descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -0700837 nullptr, /* clinit_check */
838 true /* is_unresolved */);
David Brazdildee58d62016-04-07 09:54:26 +0000839 }
840
841 // Potential class initialization check, in the case of a static method call.
842 HClinitCheck* clinit_check = nullptr;
843 HInvoke* invoke = nullptr;
844 if (invoke_type == kDirect || invoke_type == kStatic || invoke_type == kSuper) {
845 // By default, consider that the called method implicitly requires
846 // an initialization check of its declaring method.
847 HInvokeStaticOrDirect::ClinitCheckRequirement clinit_check_requirement
848 = HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit;
849 ScopedObjectAccess soa(Thread::Current());
850 if (invoke_type == kStatic) {
851 clinit_check = ProcessClinitCheckForInvoke(
852 dex_pc, resolved_method, method_idx, &clinit_check_requirement);
853 } else if (invoke_type == kSuper) {
854 if (IsSameDexFile(*resolved_method->GetDexFile(), *dex_compilation_unit_->GetDexFile())) {
855 // Update the target method to the one resolved. Note that this may be a no-op if
856 // we resolved to the method referenced by the instruction.
857 method_idx = resolved_method->GetDexMethodIndex();
858 target_method = MethodReference(dex_file_, method_idx);
859 }
860 }
861
862 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
863 HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod,
864 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
865 0u,
866 0U
867 };
868 invoke = new (arena_) HInvokeStaticOrDirect(arena_,
869 number_of_arguments,
870 return_type,
871 dex_pc,
872 method_idx,
873 target_method,
874 dispatch_info,
875 invoke_type,
876 invoke_type,
877 clinit_check_requirement);
878 } else if (invoke_type == kVirtual) {
879 ScopedObjectAccess soa(Thread::Current()); // Needed for the method index
880 invoke = new (arena_) HInvokeVirtual(arena_,
881 number_of_arguments,
882 return_type,
883 dex_pc,
884 method_idx,
885 resolved_method->GetMethodIndex());
886 } else {
887 DCHECK_EQ(invoke_type, kInterface);
888 ScopedObjectAccess soa(Thread::Current()); // Needed for the method index
889 invoke = new (arena_) HInvokeInterface(arena_,
890 number_of_arguments,
891 return_type,
892 dex_pc,
893 method_idx,
Matthew Gharrity465ecc82016-07-19 21:32:52 +0000894 resolved_method->GetImtIndex());
David Brazdildee58d62016-04-07 09:54:26 +0000895 }
896
897 return HandleInvoke(invoke,
898 number_of_vreg_arguments,
899 args,
900 register_index,
901 is_range,
902 descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -0700903 clinit_check,
904 false /* is_unresolved */);
David Brazdildee58d62016-04-07 09:54:26 +0000905}
906
907bool HInstructionBuilder::BuildNewInstance(uint16_t type_index, uint32_t dex_pc) {
Vladimir Marko3cd50df2016-04-13 19:29:26 +0100908 ScopedObjectAccess soa(Thread::Current());
909 StackHandleScope<1> hs(soa.Self());
910 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
911 Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
912 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
913 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
914
David Brazdildee58d62016-04-07 09:54:26 +0000915 bool finalizable;
Mingyao Yang062157f2016-03-02 10:15:36 -0800916 bool needs_access_check = NeedsAccessCheck(type_index, dex_cache, &finalizable);
David Brazdildee58d62016-04-07 09:54:26 +0000917
918 // Only the non-resolved entrypoint handles the finalizable class case. If we
919 // need access checks, then we haven't resolved the method and the class may
920 // again be finalizable.
Mingyao Yang062157f2016-03-02 10:15:36 -0800921 QuickEntrypointEnum entrypoint = (finalizable || needs_access_check)
David Brazdildee58d62016-04-07 09:54:26 +0000922 ? kQuickAllocObject
923 : kQuickAllocObjectInitialized;
924
David Brazdildee58d62016-04-07 09:54:26 +0000925 if (outer_dex_cache.Get() != dex_cache.Get()) {
926 // We currently do not support inlining allocations across dex files.
927 return false;
928 }
929
930 HLoadClass* load_class = new (arena_) HLoadClass(
931 graph_->GetCurrentMethod(),
932 type_index,
933 outer_dex_file,
934 IsOutermostCompilingClass(type_index),
935 dex_pc,
Mingyao Yang062157f2016-03-02 10:15:36 -0800936 needs_access_check,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +0100937 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +0000938
939 AppendInstruction(load_class);
940 HInstruction* cls = load_class;
941 if (!IsInitialized(resolved_class)) {
942 cls = new (arena_) HClinitCheck(load_class, dex_pc);
943 AppendInstruction(cls);
944 }
945
946 AppendInstruction(new (arena_) HNewInstance(
947 cls,
948 graph_->GetCurrentMethod(),
949 dex_pc,
950 type_index,
951 *dex_compilation_unit_->GetDexFile(),
Mingyao Yang062157f2016-03-02 10:15:36 -0800952 needs_access_check,
David Brazdildee58d62016-04-07 09:54:26 +0000953 finalizable,
954 entrypoint));
955 return true;
956}
957
958static bool IsSubClass(mirror::Class* to_test, mirror::Class* super_class)
959 SHARED_REQUIRES(Locks::mutator_lock_) {
960 return to_test != nullptr && !to_test->IsInterface() && to_test->IsSubClass(super_class);
961}
962
963bool HInstructionBuilder::IsInitialized(Handle<mirror::Class> cls) const {
964 if (cls.Get() == nullptr) {
965 return false;
966 }
967
968 // `CanAssumeClassIsLoaded` will return true if we're JITting, or will
969 // check whether the class is in an image for the AOT compilation.
970 if (cls->IsInitialized() &&
971 compiler_driver_->CanAssumeClassIsLoaded(cls.Get())) {
972 return true;
973 }
974
975 if (IsSubClass(GetOutermostCompilingClass(), cls.Get())) {
976 return true;
977 }
978
979 // TODO: We should walk over the inlined methods, but we don't pass
980 // that information to the builder.
981 if (IsSubClass(GetCompilingClass(), cls.Get())) {
982 return true;
983 }
984
985 return false;
986}
987
988HClinitCheck* HInstructionBuilder::ProcessClinitCheckForInvoke(
989 uint32_t dex_pc,
990 ArtMethod* resolved_method,
991 uint32_t method_idx,
992 HInvokeStaticOrDirect::ClinitCheckRequirement* clinit_check_requirement) {
993 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
994 Thread* self = Thread::Current();
Vladimir Marko3cd50df2016-04-13 19:29:26 +0100995 StackHandleScope<2> hs(self);
996 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
997 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +0000998 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
999 Handle<mirror::Class> resolved_method_class(hs.NewHandle(resolved_method->GetDeclaringClass()));
1000
1001 // The index at which the method's class is stored in the DexCache's type array.
1002 uint32_t storage_index = DexFile::kDexNoIndex;
1003 bool is_outer_class = (resolved_method->GetDeclaringClass() == outer_class.Get());
1004 if (is_outer_class) {
1005 storage_index = outer_class->GetDexTypeIndex();
1006 } else if (outer_dex_cache.Get() == dex_cache.Get()) {
1007 // Get `storage_index` from IsClassOfStaticMethodAvailableToReferrer.
1008 compiler_driver_->IsClassOfStaticMethodAvailableToReferrer(outer_dex_cache.Get(),
1009 GetCompilingClass(),
1010 resolved_method,
1011 method_idx,
1012 &storage_index);
1013 }
1014
1015 HClinitCheck* clinit_check = nullptr;
1016
1017 if (IsInitialized(resolved_method_class)) {
1018 *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kNone;
1019 } else if (storage_index != DexFile::kDexNoIndex) {
1020 *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit;
1021 HLoadClass* load_class = new (arena_) HLoadClass(
1022 graph_->GetCurrentMethod(),
1023 storage_index,
1024 outer_dex_file,
1025 is_outer_class,
1026 dex_pc,
1027 /*needs_access_check*/ false,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001028 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001029 AppendInstruction(load_class);
1030 clinit_check = new (arena_) HClinitCheck(load_class, dex_pc);
1031 AppendInstruction(clinit_check);
1032 }
1033 return clinit_check;
1034}
1035
1036bool HInstructionBuilder::SetupInvokeArguments(HInvoke* invoke,
1037 uint32_t number_of_vreg_arguments,
1038 uint32_t* args,
1039 uint32_t register_index,
1040 bool is_range,
1041 const char* descriptor,
1042 size_t start_index,
1043 size_t* argument_index) {
1044 uint32_t descriptor_index = 1; // Skip the return type.
1045
1046 for (size_t i = start_index;
1047 // Make sure we don't go over the expected arguments or over the number of
1048 // dex registers given. If the instruction was seen as dead by the verifier,
1049 // it hasn't been properly checked.
1050 (i < number_of_vreg_arguments) && (*argument_index < invoke->GetNumberOfArguments());
1051 i++, (*argument_index)++) {
1052 Primitive::Type type = Primitive::GetType(descriptor[descriptor_index++]);
1053 bool is_wide = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble);
1054 if (!is_range
1055 && is_wide
1056 && ((i + 1 == number_of_vreg_arguments) || (args[i] + 1 != args[i + 1]))) {
1057 // Longs and doubles should be in pairs, that is, sequential registers. The verifier should
1058 // reject any class where this is violated. However, the verifier only does these checks
1059 // on non trivially dead instructions, so we just bailout the compilation.
1060 VLOG(compiler) << "Did not compile "
1061 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1062 << " because of non-sequential dex register pair in wide argument";
1063 MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1064 return false;
1065 }
1066 HInstruction* arg = LoadLocal(is_range ? register_index + i : args[i], type);
1067 invoke->SetArgumentAt(*argument_index, arg);
1068 if (is_wide) {
1069 i++;
1070 }
1071 }
1072
1073 if (*argument_index != invoke->GetNumberOfArguments()) {
1074 VLOG(compiler) << "Did not compile "
1075 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1076 << " because of wrong number of arguments in invoke instruction";
1077 MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1078 return false;
1079 }
1080
1081 if (invoke->IsInvokeStaticOrDirect() &&
1082 HInvokeStaticOrDirect::NeedsCurrentMethodInput(
1083 invoke->AsInvokeStaticOrDirect()->GetMethodLoadKind())) {
1084 invoke->SetArgumentAt(*argument_index, graph_->GetCurrentMethod());
1085 (*argument_index)++;
1086 }
1087
1088 return true;
1089}
1090
1091bool HInstructionBuilder::HandleInvoke(HInvoke* invoke,
1092 uint32_t number_of_vreg_arguments,
1093 uint32_t* args,
1094 uint32_t register_index,
1095 bool is_range,
1096 const char* descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -07001097 HClinitCheck* clinit_check,
1098 bool is_unresolved) {
David Brazdildee58d62016-04-07 09:54:26 +00001099 DCHECK(!invoke->IsInvokeStaticOrDirect() || !invoke->AsInvokeStaticOrDirect()->IsStringInit());
1100
1101 size_t start_index = 0;
1102 size_t argument_index = 0;
1103 if (invoke->GetOriginalInvokeType() != InvokeType::kStatic) { // Instance call.
Aart Bik296fbb42016-06-07 13:49:12 -07001104 uint32_t obj_reg = is_range ? register_index : args[0];
1105 HInstruction* arg = is_unresolved
1106 ? LoadLocal(obj_reg, Primitive::kPrimNot)
1107 : LoadNullCheckedLocal(obj_reg, invoke->GetDexPc());
David Brazdilc120bbe2016-04-22 16:57:00 +01001108 invoke->SetArgumentAt(0, arg);
David Brazdildee58d62016-04-07 09:54:26 +00001109 start_index = 1;
1110 argument_index = 1;
1111 }
1112
1113 if (!SetupInvokeArguments(invoke,
1114 number_of_vreg_arguments,
1115 args,
1116 register_index,
1117 is_range,
1118 descriptor,
1119 start_index,
1120 &argument_index)) {
1121 return false;
1122 }
1123
1124 if (clinit_check != nullptr) {
1125 // Add the class initialization check as last input of `invoke`.
1126 DCHECK(invoke->IsInvokeStaticOrDirect());
1127 DCHECK(invoke->AsInvokeStaticOrDirect()->GetClinitCheckRequirement()
1128 == HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit);
1129 invoke->SetArgumentAt(argument_index, clinit_check);
1130 argument_index++;
1131 }
1132
1133 AppendInstruction(invoke);
1134 latest_result_ = invoke;
1135
1136 return true;
1137}
1138
1139bool HInstructionBuilder::HandleStringInit(HInvoke* invoke,
1140 uint32_t number_of_vreg_arguments,
1141 uint32_t* args,
1142 uint32_t register_index,
1143 bool is_range,
1144 const char* descriptor) {
1145 DCHECK(invoke->IsInvokeStaticOrDirect());
1146 DCHECK(invoke->AsInvokeStaticOrDirect()->IsStringInit());
1147
1148 size_t start_index = 1;
1149 size_t argument_index = 0;
1150 if (!SetupInvokeArguments(invoke,
1151 number_of_vreg_arguments,
1152 args,
1153 register_index,
1154 is_range,
1155 descriptor,
1156 start_index,
1157 &argument_index)) {
1158 return false;
1159 }
1160
1161 AppendInstruction(invoke);
1162
1163 // This is a StringFactory call, not an actual String constructor. Its result
1164 // replaces the empty String pre-allocated by NewInstance.
1165 uint32_t orig_this_reg = is_range ? register_index : args[0];
1166 HInstruction* arg_this = LoadLocal(orig_this_reg, Primitive::kPrimNot);
1167
1168 // Replacing the NewInstance might render it redundant. Keep a list of these
1169 // to be visited once it is clear whether it is has remaining uses.
1170 if (arg_this->IsNewInstance()) {
1171 ssa_builder_->AddUninitializedString(arg_this->AsNewInstance());
1172 } else {
1173 DCHECK(arg_this->IsPhi());
1174 // NewInstance is not the direct input of the StringFactory call. It might
1175 // be redundant but optimizing this case is not worth the effort.
1176 }
1177
1178 // Walk over all vregs and replace any occurrence of `arg_this` with `invoke`.
1179 for (size_t vreg = 0, e = current_locals_->size(); vreg < e; ++vreg) {
1180 if ((*current_locals_)[vreg] == arg_this) {
1181 (*current_locals_)[vreg] = invoke;
1182 }
1183 }
1184
1185 return true;
1186}
1187
1188static Primitive::Type GetFieldAccessType(const DexFile& dex_file, uint16_t field_index) {
1189 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_index);
1190 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
1191 return Primitive::GetType(type[0]);
1192}
1193
1194bool HInstructionBuilder::BuildInstanceFieldAccess(const Instruction& instruction,
1195 uint32_t dex_pc,
1196 bool is_put) {
1197 uint32_t source_or_dest_reg = instruction.VRegA_22c();
1198 uint32_t obj_reg = instruction.VRegB_22c();
1199 uint16_t field_index;
1200 if (instruction.IsQuickened()) {
1201 if (!CanDecodeQuickenedInfo()) {
1202 return false;
1203 }
1204 field_index = LookupQuickenedInfo(dex_pc);
1205 } else {
1206 field_index = instruction.VRegC_22c();
1207 }
1208
1209 ScopedObjectAccess soa(Thread::Current());
1210 ArtField* resolved_field =
1211 compiler_driver_->ComputeInstanceFieldInfo(field_index, dex_compilation_unit_, is_put, soa);
1212
1213
Aart Bik14154132016-06-02 17:53:58 -07001214 // Generate an explicit null check on the reference, unless the field access
1215 // is unresolved. In that case, we rely on the runtime to perform various
1216 // checks first, followed by a null check.
1217 HInstruction* object = (resolved_field == nullptr)
1218 ? LoadLocal(obj_reg, Primitive::kPrimNot)
1219 : LoadNullCheckedLocal(obj_reg, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001220
1221 Primitive::Type field_type = (resolved_field == nullptr)
1222 ? GetFieldAccessType(*dex_file_, field_index)
1223 : resolved_field->GetTypeAsPrimitiveType();
1224 if (is_put) {
1225 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1226 HInstruction* field_set = nullptr;
1227 if (resolved_field == nullptr) {
1228 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
David Brazdilc120bbe2016-04-22 16:57:00 +01001229 field_set = new (arena_) HUnresolvedInstanceFieldSet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001230 value,
1231 field_type,
1232 field_index,
1233 dex_pc);
1234 } else {
1235 uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
David Brazdilc120bbe2016-04-22 16:57:00 +01001236 field_set = new (arena_) HInstanceFieldSet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001237 value,
1238 field_type,
1239 resolved_field->GetOffset(),
1240 resolved_field->IsVolatile(),
1241 field_index,
1242 class_def_index,
1243 *dex_file_,
1244 dex_compilation_unit_->GetDexCache(),
1245 dex_pc);
1246 }
1247 AppendInstruction(field_set);
1248 } else {
1249 HInstruction* field_get = nullptr;
1250 if (resolved_field == nullptr) {
1251 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
David Brazdilc120bbe2016-04-22 16:57:00 +01001252 field_get = new (arena_) HUnresolvedInstanceFieldGet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001253 field_type,
1254 field_index,
1255 dex_pc);
1256 } else {
1257 uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
David Brazdilc120bbe2016-04-22 16:57:00 +01001258 field_get = new (arena_) HInstanceFieldGet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001259 field_type,
1260 resolved_field->GetOffset(),
1261 resolved_field->IsVolatile(),
1262 field_index,
1263 class_def_index,
1264 *dex_file_,
1265 dex_compilation_unit_->GetDexCache(),
1266 dex_pc);
1267 }
1268 AppendInstruction(field_get);
1269 UpdateLocal(source_or_dest_reg, field_get);
1270 }
1271
1272 return true;
1273}
1274
1275static mirror::Class* GetClassFrom(CompilerDriver* driver,
1276 const DexCompilationUnit& compilation_unit) {
1277 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001278 StackHandleScope<1> hs(soa.Self());
David Brazdildee58d62016-04-07 09:54:26 +00001279 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1280 soa.Decode<mirror::ClassLoader*>(compilation_unit.GetClassLoader())));
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001281 Handle<mirror::DexCache> dex_cache = compilation_unit.GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001282
1283 return driver->ResolveCompilingMethodsClass(soa, dex_cache, class_loader, &compilation_unit);
1284}
1285
1286mirror::Class* HInstructionBuilder::GetOutermostCompilingClass() const {
1287 return GetClassFrom(compiler_driver_, *outer_compilation_unit_);
1288}
1289
1290mirror::Class* HInstructionBuilder::GetCompilingClass() const {
1291 return GetClassFrom(compiler_driver_, *dex_compilation_unit_);
1292}
1293
1294bool HInstructionBuilder::IsOutermostCompilingClass(uint16_t type_index) const {
1295 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001296 StackHandleScope<3> hs(soa.Self());
1297 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001298 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1299 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1300 Handle<mirror::Class> cls(hs.NewHandle(compiler_driver_->ResolveClass(
1301 soa, dex_cache, class_loader, type_index, dex_compilation_unit_)));
1302 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1303
1304 // GetOutermostCompilingClass returns null when the class is unresolved
1305 // (e.g. if it derives from an unresolved class). This is bogus knowing that
1306 // we are compiling it.
1307 // When this happens we cannot establish a direct relation between the current
1308 // class and the outer class, so we return false.
1309 // (Note that this is only used for optimizing invokes and field accesses)
1310 return (cls.Get() != nullptr) && (outer_class.Get() == cls.Get());
1311}
1312
1313void HInstructionBuilder::BuildUnresolvedStaticFieldAccess(const Instruction& instruction,
1314 uint32_t dex_pc,
1315 bool is_put,
1316 Primitive::Type field_type) {
1317 uint32_t source_or_dest_reg = instruction.VRegA_21c();
1318 uint16_t field_index = instruction.VRegB_21c();
1319
1320 if (is_put) {
1321 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1322 AppendInstruction(
1323 new (arena_) HUnresolvedStaticFieldSet(value, field_type, field_index, dex_pc));
1324 } else {
1325 AppendInstruction(new (arena_) HUnresolvedStaticFieldGet(field_type, field_index, dex_pc));
1326 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1327 }
1328}
1329
1330bool HInstructionBuilder::BuildStaticFieldAccess(const Instruction& instruction,
1331 uint32_t dex_pc,
1332 bool is_put) {
1333 uint32_t source_or_dest_reg = instruction.VRegA_21c();
1334 uint16_t field_index = instruction.VRegB_21c();
1335
1336 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001337 StackHandleScope<3> hs(soa.Self());
1338 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001339 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1340 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1341 ArtField* resolved_field = compiler_driver_->ResolveField(
1342 soa, dex_cache, class_loader, dex_compilation_unit_, field_index, true);
1343
1344 if (resolved_field == nullptr) {
1345 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
1346 Primitive::Type field_type = GetFieldAccessType(*dex_file_, field_index);
1347 BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1348 return true;
1349 }
1350
1351 Primitive::Type field_type = resolved_field->GetTypeAsPrimitiveType();
1352 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001353 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001354 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1355
1356 // The index at which the field's class is stored in the DexCache's type array.
1357 uint32_t storage_index;
1358 bool is_outer_class = (outer_class.Get() == resolved_field->GetDeclaringClass());
1359 if (is_outer_class) {
1360 storage_index = outer_class->GetDexTypeIndex();
1361 } else if (outer_dex_cache.Get() != dex_cache.Get()) {
1362 // The compiler driver cannot currently understand multiple dex caches involved. Just bailout.
1363 return false;
1364 } else {
1365 // TODO: This is rather expensive. Perf it and cache the results if needed.
1366 std::pair<bool, bool> pair = compiler_driver_->IsFastStaticField(
1367 outer_dex_cache.Get(),
1368 GetCompilingClass(),
1369 resolved_field,
1370 field_index,
1371 &storage_index);
1372 bool can_easily_access = is_put ? pair.second : pair.first;
1373 if (!can_easily_access) {
1374 MaybeRecordStat(MethodCompilationStat::kUnresolvedFieldNotAFastAccess);
1375 BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1376 return true;
1377 }
1378 }
1379
David Brazdildee58d62016-04-07 09:54:26 +00001380 HLoadClass* constant = new (arena_) HLoadClass(graph_->GetCurrentMethod(),
1381 storage_index,
1382 outer_dex_file,
1383 is_outer_class,
1384 dex_pc,
1385 /*needs_access_check*/ false,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001386 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001387 AppendInstruction(constant);
1388
1389 HInstruction* cls = constant;
1390
1391 Handle<mirror::Class> klass(hs.NewHandle(resolved_field->GetDeclaringClass()));
1392 if (!IsInitialized(klass)) {
1393 cls = new (arena_) HClinitCheck(constant, dex_pc);
1394 AppendInstruction(cls);
1395 }
1396
1397 uint16_t class_def_index = klass->GetDexClassDefIndex();
1398 if (is_put) {
1399 // We need to keep the class alive before loading the value.
1400 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1401 DCHECK_EQ(HPhi::ToPhiType(value->GetType()), HPhi::ToPhiType(field_type));
1402 AppendInstruction(new (arena_) HStaticFieldSet(cls,
1403 value,
1404 field_type,
1405 resolved_field->GetOffset(),
1406 resolved_field->IsVolatile(),
1407 field_index,
1408 class_def_index,
1409 *dex_file_,
1410 dex_cache_,
1411 dex_pc));
1412 } else {
1413 AppendInstruction(new (arena_) HStaticFieldGet(cls,
1414 field_type,
1415 resolved_field->GetOffset(),
1416 resolved_field->IsVolatile(),
1417 field_index,
1418 class_def_index,
1419 *dex_file_,
1420 dex_cache_,
1421 dex_pc));
1422 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1423 }
1424 return true;
1425}
1426
1427void HInstructionBuilder::BuildCheckedDivRem(uint16_t out_vreg,
1428 uint16_t first_vreg,
1429 int64_t second_vreg_or_constant,
1430 uint32_t dex_pc,
1431 Primitive::Type type,
1432 bool second_is_constant,
1433 bool isDiv) {
1434 DCHECK(type == Primitive::kPrimInt || type == Primitive::kPrimLong);
1435
1436 HInstruction* first = LoadLocal(first_vreg, type);
1437 HInstruction* second = nullptr;
1438 if (second_is_constant) {
1439 if (type == Primitive::kPrimInt) {
1440 second = graph_->GetIntConstant(second_vreg_or_constant, dex_pc);
1441 } else {
1442 second = graph_->GetLongConstant(second_vreg_or_constant, dex_pc);
1443 }
1444 } else {
1445 second = LoadLocal(second_vreg_or_constant, type);
1446 }
1447
1448 if (!second_is_constant
1449 || (type == Primitive::kPrimInt && second->AsIntConstant()->GetValue() == 0)
1450 || (type == Primitive::kPrimLong && second->AsLongConstant()->GetValue() == 0)) {
1451 second = new (arena_) HDivZeroCheck(second, dex_pc);
1452 AppendInstruction(second);
1453 }
1454
1455 if (isDiv) {
1456 AppendInstruction(new (arena_) HDiv(type, first, second, dex_pc));
1457 } else {
1458 AppendInstruction(new (arena_) HRem(type, first, second, dex_pc));
1459 }
1460 UpdateLocal(out_vreg, current_block_->GetLastInstruction());
1461}
1462
1463void HInstructionBuilder::BuildArrayAccess(const Instruction& instruction,
1464 uint32_t dex_pc,
1465 bool is_put,
1466 Primitive::Type anticipated_type) {
1467 uint8_t source_or_dest_reg = instruction.VRegA_23x();
1468 uint8_t array_reg = instruction.VRegB_23x();
1469 uint8_t index_reg = instruction.VRegC_23x();
1470
David Brazdilc120bbe2016-04-22 16:57:00 +01001471 HInstruction* object = LoadNullCheckedLocal(array_reg, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001472 HInstruction* length = new (arena_) HArrayLength(object, dex_pc);
1473 AppendInstruction(length);
1474 HInstruction* index = LoadLocal(index_reg, Primitive::kPrimInt);
1475 index = new (arena_) HBoundsCheck(index, length, dex_pc);
1476 AppendInstruction(index);
1477 if (is_put) {
1478 HInstruction* value = LoadLocal(source_or_dest_reg, anticipated_type);
1479 // TODO: Insert a type check node if the type is Object.
1480 HArraySet* aset = new (arena_) HArraySet(object, index, value, anticipated_type, dex_pc);
1481 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1482 AppendInstruction(aset);
1483 } else {
1484 HArrayGet* aget = new (arena_) HArrayGet(object, index, anticipated_type, dex_pc);
1485 ssa_builder_->MaybeAddAmbiguousArrayGet(aget);
1486 AppendInstruction(aget);
1487 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1488 }
1489 graph_->SetHasBoundsChecks(true);
1490}
1491
1492void HInstructionBuilder::BuildFilledNewArray(uint32_t dex_pc,
1493 uint32_t type_index,
1494 uint32_t number_of_vreg_arguments,
1495 bool is_range,
1496 uint32_t* args,
1497 uint32_t register_index) {
1498 HInstruction* length = graph_->GetIntConstant(number_of_vreg_arguments, dex_pc);
1499 bool finalizable;
1500 QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
1501 ? kQuickAllocArrayWithAccessCheck
1502 : kQuickAllocArray;
1503 HInstruction* object = new (arena_) HNewArray(length,
1504 graph_->GetCurrentMethod(),
1505 dex_pc,
1506 type_index,
1507 *dex_compilation_unit_->GetDexFile(),
1508 entrypoint);
1509 AppendInstruction(object);
1510
1511 const char* descriptor = dex_file_->StringByTypeIdx(type_index);
1512 DCHECK_EQ(descriptor[0], '[') << descriptor;
1513 char primitive = descriptor[1];
1514 DCHECK(primitive == 'I'
1515 || primitive == 'L'
1516 || primitive == '[') << descriptor;
1517 bool is_reference_array = (primitive == 'L') || (primitive == '[');
1518 Primitive::Type type = is_reference_array ? Primitive::kPrimNot : Primitive::kPrimInt;
1519
1520 for (size_t i = 0; i < number_of_vreg_arguments; ++i) {
1521 HInstruction* value = LoadLocal(is_range ? register_index + i : args[i], type);
1522 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1523 HArraySet* aset = new (arena_) HArraySet(object, index, value, type, dex_pc);
1524 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1525 AppendInstruction(aset);
1526 }
1527 latest_result_ = object;
1528}
1529
1530template <typename T>
1531void HInstructionBuilder::BuildFillArrayData(HInstruction* object,
1532 const T* data,
1533 uint32_t element_count,
1534 Primitive::Type anticipated_type,
1535 uint32_t dex_pc) {
1536 for (uint32_t i = 0; i < element_count; ++i) {
1537 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1538 HInstruction* value = graph_->GetIntConstant(data[i], dex_pc);
1539 HArraySet* aset = new (arena_) HArraySet(object, index, value, anticipated_type, dex_pc);
1540 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1541 AppendInstruction(aset);
1542 }
1543}
1544
1545void HInstructionBuilder::BuildFillArrayData(const Instruction& instruction, uint32_t dex_pc) {
David Brazdilc120bbe2016-04-22 16:57:00 +01001546 HInstruction* array = LoadNullCheckedLocal(instruction.VRegA_31t(), dex_pc);
1547 HInstruction* length = new (arena_) HArrayLength(array, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001548 AppendInstruction(length);
1549
1550 int32_t payload_offset = instruction.VRegB_31t() + dex_pc;
1551 const Instruction::ArrayDataPayload* payload =
1552 reinterpret_cast<const Instruction::ArrayDataPayload*>(code_item_.insns_ + payload_offset);
1553 const uint8_t* data = payload->data;
1554 uint32_t element_count = payload->element_count;
1555
1556 // Implementation of this DEX instruction seems to be that the bounds check is
1557 // done before doing any stores.
1558 HInstruction* last_index = graph_->GetIntConstant(payload->element_count - 1, dex_pc);
1559 AppendInstruction(new (arena_) HBoundsCheck(last_index, length, dex_pc));
1560
1561 switch (payload->element_width) {
1562 case 1:
David Brazdilc120bbe2016-04-22 16:57:00 +01001563 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001564 reinterpret_cast<const int8_t*>(data),
1565 element_count,
1566 Primitive::kPrimByte,
1567 dex_pc);
1568 break;
1569 case 2:
David Brazdilc120bbe2016-04-22 16:57:00 +01001570 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001571 reinterpret_cast<const int16_t*>(data),
1572 element_count,
1573 Primitive::kPrimShort,
1574 dex_pc);
1575 break;
1576 case 4:
David Brazdilc120bbe2016-04-22 16:57:00 +01001577 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001578 reinterpret_cast<const int32_t*>(data),
1579 element_count,
1580 Primitive::kPrimInt,
1581 dex_pc);
1582 break;
1583 case 8:
David Brazdilc120bbe2016-04-22 16:57:00 +01001584 BuildFillWideArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001585 reinterpret_cast<const int64_t*>(data),
1586 element_count,
1587 dex_pc);
1588 break;
1589 default:
1590 LOG(FATAL) << "Unknown element width for " << payload->element_width;
1591 }
1592 graph_->SetHasBoundsChecks(true);
1593}
1594
1595void HInstructionBuilder::BuildFillWideArrayData(HInstruction* object,
1596 const int64_t* data,
1597 uint32_t element_count,
1598 uint32_t dex_pc) {
1599 for (uint32_t i = 0; i < element_count; ++i) {
1600 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1601 HInstruction* value = graph_->GetLongConstant(data[i], dex_pc);
1602 HArraySet* aset = new (arena_) HArraySet(object, index, value, Primitive::kPrimLong, dex_pc);
1603 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1604 AppendInstruction(aset);
1605 }
1606}
1607
1608static TypeCheckKind ComputeTypeCheckKind(Handle<mirror::Class> cls)
1609 SHARED_REQUIRES(Locks::mutator_lock_) {
1610 if (cls.Get() == nullptr) {
1611 return TypeCheckKind::kUnresolvedCheck;
1612 } else if (cls->IsInterface()) {
1613 return TypeCheckKind::kInterfaceCheck;
1614 } else if (cls->IsArrayClass()) {
1615 if (cls->GetComponentType()->IsObjectClass()) {
1616 return TypeCheckKind::kArrayObjectCheck;
1617 } else if (cls->CannotBeAssignedFromOtherTypes()) {
1618 return TypeCheckKind::kExactCheck;
1619 } else {
1620 return TypeCheckKind::kArrayCheck;
1621 }
1622 } else if (cls->IsFinal()) {
1623 return TypeCheckKind::kExactCheck;
1624 } else if (cls->IsAbstract()) {
1625 return TypeCheckKind::kAbstractClassCheck;
1626 } else {
1627 return TypeCheckKind::kClassHierarchyCheck;
1628 }
1629}
1630
1631void HInstructionBuilder::BuildTypeCheck(const Instruction& instruction,
1632 uint8_t destination,
1633 uint8_t reference,
1634 uint16_t type_index,
1635 uint32_t dex_pc) {
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001636 ScopedObjectAccess soa(Thread::Current());
1637 StackHandleScope<1> hs(soa.Self());
1638 const DexFile& dex_file = *dex_compilation_unit_->GetDexFile();
1639 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
1640 Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
1641
David Brazdildee58d62016-04-07 09:54:26 +00001642 bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
1643 dex_compilation_unit_->GetDexMethodIndex(),
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001644 dex_cache,
1645 type_index);
David Brazdildee58d62016-04-07 09:54:26 +00001646
1647 HInstruction* object = LoadLocal(reference, Primitive::kPrimNot);
1648 HLoadClass* cls = new (arena_) HLoadClass(
1649 graph_->GetCurrentMethod(),
1650 type_index,
1651 dex_file,
1652 IsOutermostCompilingClass(type_index),
1653 dex_pc,
1654 !can_access,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001655 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001656 AppendInstruction(cls);
1657
1658 TypeCheckKind check_kind = ComputeTypeCheckKind(resolved_class);
1659 if (instruction.Opcode() == Instruction::INSTANCE_OF) {
1660 AppendInstruction(new (arena_) HInstanceOf(object, cls, check_kind, dex_pc));
1661 UpdateLocal(destination, current_block_->GetLastInstruction());
1662 } else {
1663 DCHECK_EQ(instruction.Opcode(), Instruction::CHECK_CAST);
1664 // We emit a CheckCast followed by a BoundType. CheckCast is a statement
1665 // which may throw. If it succeeds BoundType sets the new type of `object`
1666 // for all subsequent uses.
1667 AppendInstruction(new (arena_) HCheckCast(object, cls, check_kind, dex_pc));
1668 AppendInstruction(new (arena_) HBoundType(object, dex_pc));
1669 UpdateLocal(reference, current_block_->GetLastInstruction());
1670 }
1671}
1672
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001673bool HInstructionBuilder::NeedsAccessCheck(uint32_t type_index,
1674 Handle<mirror::DexCache> dex_cache,
1675 bool* finalizable) const {
David Brazdildee58d62016-04-07 09:54:26 +00001676 return !compiler_driver_->CanAccessInstantiableTypeWithoutChecks(
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001677 dex_compilation_unit_->GetDexMethodIndex(), dex_cache, type_index, finalizable);
1678}
1679
1680bool HInstructionBuilder::NeedsAccessCheck(uint32_t type_index, bool* finalizable) const {
1681 ScopedObjectAccess soa(Thread::Current());
1682 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
1683 return NeedsAccessCheck(type_index, dex_cache, finalizable);
David Brazdildee58d62016-04-07 09:54:26 +00001684}
1685
1686bool HInstructionBuilder::CanDecodeQuickenedInfo() const {
1687 return interpreter_metadata_ != nullptr;
1688}
1689
1690uint16_t HInstructionBuilder::LookupQuickenedInfo(uint32_t dex_pc) {
1691 DCHECK(interpreter_metadata_ != nullptr);
1692
1693 // First check if the info has already been decoded from `interpreter_metadata_`.
1694 auto it = skipped_interpreter_metadata_.find(dex_pc);
1695 if (it != skipped_interpreter_metadata_.end()) {
1696 // Remove the entry from the map and return the parsed info.
1697 uint16_t value_in_map = it->second;
1698 skipped_interpreter_metadata_.erase(it);
1699 return value_in_map;
1700 }
1701
1702 // Otherwise start parsing `interpreter_metadata_` until the slot for `dex_pc`
1703 // is found. Store skipped values in the `skipped_interpreter_metadata_` map.
1704 while (true) {
1705 uint32_t dex_pc_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1706 uint16_t value_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1707 DCHECK_LE(dex_pc_in_map, dex_pc);
1708
1709 if (dex_pc_in_map == dex_pc) {
1710 return value_in_map;
1711 } else {
1712 skipped_interpreter_metadata_.Put(dex_pc_in_map, value_in_map);
1713 }
1714 }
1715}
1716
1717bool HInstructionBuilder::ProcessDexInstruction(const Instruction& instruction, uint32_t dex_pc) {
1718 switch (instruction.Opcode()) {
1719 case Instruction::CONST_4: {
1720 int32_t register_index = instruction.VRegA();
1721 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_11n(), dex_pc);
1722 UpdateLocal(register_index, constant);
1723 break;
1724 }
1725
1726 case Instruction::CONST_16: {
1727 int32_t register_index = instruction.VRegA();
1728 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21s(), dex_pc);
1729 UpdateLocal(register_index, constant);
1730 break;
1731 }
1732
1733 case Instruction::CONST: {
1734 int32_t register_index = instruction.VRegA();
1735 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_31i(), dex_pc);
1736 UpdateLocal(register_index, constant);
1737 break;
1738 }
1739
1740 case Instruction::CONST_HIGH16: {
1741 int32_t register_index = instruction.VRegA();
1742 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21h() << 16, dex_pc);
1743 UpdateLocal(register_index, constant);
1744 break;
1745 }
1746
1747 case Instruction::CONST_WIDE_16: {
1748 int32_t register_index = instruction.VRegA();
1749 // Get 16 bits of constant value, sign extended to 64 bits.
1750 int64_t value = instruction.VRegB_21s();
1751 value <<= 48;
1752 value >>= 48;
1753 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1754 UpdateLocal(register_index, constant);
1755 break;
1756 }
1757
1758 case Instruction::CONST_WIDE_32: {
1759 int32_t register_index = instruction.VRegA();
1760 // Get 32 bits of constant value, sign extended to 64 bits.
1761 int64_t value = instruction.VRegB_31i();
1762 value <<= 32;
1763 value >>= 32;
1764 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1765 UpdateLocal(register_index, constant);
1766 break;
1767 }
1768
1769 case Instruction::CONST_WIDE: {
1770 int32_t register_index = instruction.VRegA();
1771 HLongConstant* constant = graph_->GetLongConstant(instruction.VRegB_51l(), dex_pc);
1772 UpdateLocal(register_index, constant);
1773 break;
1774 }
1775
1776 case Instruction::CONST_WIDE_HIGH16: {
1777 int32_t register_index = instruction.VRegA();
1778 int64_t value = static_cast<int64_t>(instruction.VRegB_21h()) << 48;
1779 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1780 UpdateLocal(register_index, constant);
1781 break;
1782 }
1783
1784 // Note that the SSA building will refine the types.
1785 case Instruction::MOVE:
1786 case Instruction::MOVE_FROM16:
1787 case Instruction::MOVE_16: {
1788 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
1789 UpdateLocal(instruction.VRegA(), value);
1790 break;
1791 }
1792
1793 // Note that the SSA building will refine the types.
1794 case Instruction::MOVE_WIDE:
1795 case Instruction::MOVE_WIDE_FROM16:
1796 case Instruction::MOVE_WIDE_16: {
1797 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimLong);
1798 UpdateLocal(instruction.VRegA(), value);
1799 break;
1800 }
1801
1802 case Instruction::MOVE_OBJECT:
1803 case Instruction::MOVE_OBJECT_16:
1804 case Instruction::MOVE_OBJECT_FROM16: {
1805 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimNot);
1806 UpdateLocal(instruction.VRegA(), value);
1807 break;
1808 }
1809
1810 case Instruction::RETURN_VOID_NO_BARRIER:
1811 case Instruction::RETURN_VOID: {
1812 BuildReturn(instruction, Primitive::kPrimVoid, dex_pc);
1813 break;
1814 }
1815
1816#define IF_XX(comparison, cond) \
1817 case Instruction::IF_##cond: If_22t<comparison>(instruction, dex_pc); break; \
1818 case Instruction::IF_##cond##Z: If_21t<comparison>(instruction, dex_pc); break
1819
1820 IF_XX(HEqual, EQ);
1821 IF_XX(HNotEqual, NE);
1822 IF_XX(HLessThan, LT);
1823 IF_XX(HLessThanOrEqual, LE);
1824 IF_XX(HGreaterThan, GT);
1825 IF_XX(HGreaterThanOrEqual, GE);
1826
1827 case Instruction::GOTO:
1828 case Instruction::GOTO_16:
1829 case Instruction::GOTO_32: {
1830 AppendInstruction(new (arena_) HGoto(dex_pc));
1831 current_block_ = nullptr;
1832 break;
1833 }
1834
1835 case Instruction::RETURN: {
1836 BuildReturn(instruction, return_type_, dex_pc);
1837 break;
1838 }
1839
1840 case Instruction::RETURN_OBJECT: {
1841 BuildReturn(instruction, return_type_, dex_pc);
1842 break;
1843 }
1844
1845 case Instruction::RETURN_WIDE: {
1846 BuildReturn(instruction, return_type_, dex_pc);
1847 break;
1848 }
1849
1850 case Instruction::INVOKE_DIRECT:
1851 case Instruction::INVOKE_INTERFACE:
1852 case Instruction::INVOKE_STATIC:
1853 case Instruction::INVOKE_SUPER:
1854 case Instruction::INVOKE_VIRTUAL:
1855 case Instruction::INVOKE_VIRTUAL_QUICK: {
1856 uint16_t method_idx;
1857 if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_QUICK) {
1858 if (!CanDecodeQuickenedInfo()) {
1859 return false;
1860 }
1861 method_idx = LookupQuickenedInfo(dex_pc);
1862 } else {
1863 method_idx = instruction.VRegB_35c();
1864 }
1865 uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
1866 uint32_t args[5];
1867 instruction.GetVarArgs(args);
1868 if (!BuildInvoke(instruction, dex_pc, method_idx,
1869 number_of_vreg_arguments, false, args, -1)) {
1870 return false;
1871 }
1872 break;
1873 }
1874
1875 case Instruction::INVOKE_DIRECT_RANGE:
1876 case Instruction::INVOKE_INTERFACE_RANGE:
1877 case Instruction::INVOKE_STATIC_RANGE:
1878 case Instruction::INVOKE_SUPER_RANGE:
1879 case Instruction::INVOKE_VIRTUAL_RANGE:
1880 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
1881 uint16_t method_idx;
1882 if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK) {
1883 if (!CanDecodeQuickenedInfo()) {
1884 return false;
1885 }
1886 method_idx = LookupQuickenedInfo(dex_pc);
1887 } else {
1888 method_idx = instruction.VRegB_3rc();
1889 }
1890 uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
1891 uint32_t register_index = instruction.VRegC();
1892 if (!BuildInvoke(instruction, dex_pc, method_idx,
1893 number_of_vreg_arguments, true, nullptr, register_index)) {
1894 return false;
1895 }
1896 break;
1897 }
1898
1899 case Instruction::NEG_INT: {
1900 Unop_12x<HNeg>(instruction, Primitive::kPrimInt, dex_pc);
1901 break;
1902 }
1903
1904 case Instruction::NEG_LONG: {
1905 Unop_12x<HNeg>(instruction, Primitive::kPrimLong, dex_pc);
1906 break;
1907 }
1908
1909 case Instruction::NEG_FLOAT: {
1910 Unop_12x<HNeg>(instruction, Primitive::kPrimFloat, dex_pc);
1911 break;
1912 }
1913
1914 case Instruction::NEG_DOUBLE: {
1915 Unop_12x<HNeg>(instruction, Primitive::kPrimDouble, dex_pc);
1916 break;
1917 }
1918
1919 case Instruction::NOT_INT: {
1920 Unop_12x<HNot>(instruction, Primitive::kPrimInt, dex_pc);
1921 break;
1922 }
1923
1924 case Instruction::NOT_LONG: {
1925 Unop_12x<HNot>(instruction, Primitive::kPrimLong, dex_pc);
1926 break;
1927 }
1928
1929 case Instruction::INT_TO_LONG: {
1930 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimLong, dex_pc);
1931 break;
1932 }
1933
1934 case Instruction::INT_TO_FLOAT: {
1935 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimFloat, dex_pc);
1936 break;
1937 }
1938
1939 case Instruction::INT_TO_DOUBLE: {
1940 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimDouble, dex_pc);
1941 break;
1942 }
1943
1944 case Instruction::LONG_TO_INT: {
1945 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimInt, dex_pc);
1946 break;
1947 }
1948
1949 case Instruction::LONG_TO_FLOAT: {
1950 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimFloat, dex_pc);
1951 break;
1952 }
1953
1954 case Instruction::LONG_TO_DOUBLE: {
1955 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimDouble, dex_pc);
1956 break;
1957 }
1958
1959 case Instruction::FLOAT_TO_INT: {
1960 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimInt, dex_pc);
1961 break;
1962 }
1963
1964 case Instruction::FLOAT_TO_LONG: {
1965 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimLong, dex_pc);
1966 break;
1967 }
1968
1969 case Instruction::FLOAT_TO_DOUBLE: {
1970 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimDouble, dex_pc);
1971 break;
1972 }
1973
1974 case Instruction::DOUBLE_TO_INT: {
1975 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimInt, dex_pc);
1976 break;
1977 }
1978
1979 case Instruction::DOUBLE_TO_LONG: {
1980 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimLong, dex_pc);
1981 break;
1982 }
1983
1984 case Instruction::DOUBLE_TO_FLOAT: {
1985 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimFloat, dex_pc);
1986 break;
1987 }
1988
1989 case Instruction::INT_TO_BYTE: {
1990 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimByte, dex_pc);
1991 break;
1992 }
1993
1994 case Instruction::INT_TO_SHORT: {
1995 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimShort, dex_pc);
1996 break;
1997 }
1998
1999 case Instruction::INT_TO_CHAR: {
2000 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimChar, dex_pc);
2001 break;
2002 }
2003
2004 case Instruction::ADD_INT: {
2005 Binop_23x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2006 break;
2007 }
2008
2009 case Instruction::ADD_LONG: {
2010 Binop_23x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2011 break;
2012 }
2013
2014 case Instruction::ADD_DOUBLE: {
2015 Binop_23x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2016 break;
2017 }
2018
2019 case Instruction::ADD_FLOAT: {
2020 Binop_23x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2021 break;
2022 }
2023
2024 case Instruction::SUB_INT: {
2025 Binop_23x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2026 break;
2027 }
2028
2029 case Instruction::SUB_LONG: {
2030 Binop_23x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2031 break;
2032 }
2033
2034 case Instruction::SUB_FLOAT: {
2035 Binop_23x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2036 break;
2037 }
2038
2039 case Instruction::SUB_DOUBLE: {
2040 Binop_23x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2041 break;
2042 }
2043
2044 case Instruction::ADD_INT_2ADDR: {
2045 Binop_12x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2046 break;
2047 }
2048
2049 case Instruction::MUL_INT: {
2050 Binop_23x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2051 break;
2052 }
2053
2054 case Instruction::MUL_LONG: {
2055 Binop_23x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2056 break;
2057 }
2058
2059 case Instruction::MUL_FLOAT: {
2060 Binop_23x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2061 break;
2062 }
2063
2064 case Instruction::MUL_DOUBLE: {
2065 Binop_23x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2066 break;
2067 }
2068
2069 case Instruction::DIV_INT: {
2070 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2071 dex_pc, Primitive::kPrimInt, false, true);
2072 break;
2073 }
2074
2075 case Instruction::DIV_LONG: {
2076 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2077 dex_pc, Primitive::kPrimLong, false, true);
2078 break;
2079 }
2080
2081 case Instruction::DIV_FLOAT: {
2082 Binop_23x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2083 break;
2084 }
2085
2086 case Instruction::DIV_DOUBLE: {
2087 Binop_23x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2088 break;
2089 }
2090
2091 case Instruction::REM_INT: {
2092 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2093 dex_pc, Primitive::kPrimInt, false, false);
2094 break;
2095 }
2096
2097 case Instruction::REM_LONG: {
2098 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2099 dex_pc, Primitive::kPrimLong, false, false);
2100 break;
2101 }
2102
2103 case Instruction::REM_FLOAT: {
2104 Binop_23x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2105 break;
2106 }
2107
2108 case Instruction::REM_DOUBLE: {
2109 Binop_23x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2110 break;
2111 }
2112
2113 case Instruction::AND_INT: {
2114 Binop_23x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2115 break;
2116 }
2117
2118 case Instruction::AND_LONG: {
2119 Binop_23x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2120 break;
2121 }
2122
2123 case Instruction::SHL_INT: {
2124 Binop_23x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2125 break;
2126 }
2127
2128 case Instruction::SHL_LONG: {
2129 Binop_23x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2130 break;
2131 }
2132
2133 case Instruction::SHR_INT: {
2134 Binop_23x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2135 break;
2136 }
2137
2138 case Instruction::SHR_LONG: {
2139 Binop_23x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2140 break;
2141 }
2142
2143 case Instruction::USHR_INT: {
2144 Binop_23x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2145 break;
2146 }
2147
2148 case Instruction::USHR_LONG: {
2149 Binop_23x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2150 break;
2151 }
2152
2153 case Instruction::OR_INT: {
2154 Binop_23x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2155 break;
2156 }
2157
2158 case Instruction::OR_LONG: {
2159 Binop_23x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2160 break;
2161 }
2162
2163 case Instruction::XOR_INT: {
2164 Binop_23x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2165 break;
2166 }
2167
2168 case Instruction::XOR_LONG: {
2169 Binop_23x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2170 break;
2171 }
2172
2173 case Instruction::ADD_LONG_2ADDR: {
2174 Binop_12x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2175 break;
2176 }
2177
2178 case Instruction::ADD_DOUBLE_2ADDR: {
2179 Binop_12x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2180 break;
2181 }
2182
2183 case Instruction::ADD_FLOAT_2ADDR: {
2184 Binop_12x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2185 break;
2186 }
2187
2188 case Instruction::SUB_INT_2ADDR: {
2189 Binop_12x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2190 break;
2191 }
2192
2193 case Instruction::SUB_LONG_2ADDR: {
2194 Binop_12x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2195 break;
2196 }
2197
2198 case Instruction::SUB_FLOAT_2ADDR: {
2199 Binop_12x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2200 break;
2201 }
2202
2203 case Instruction::SUB_DOUBLE_2ADDR: {
2204 Binop_12x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2205 break;
2206 }
2207
2208 case Instruction::MUL_INT_2ADDR: {
2209 Binop_12x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2210 break;
2211 }
2212
2213 case Instruction::MUL_LONG_2ADDR: {
2214 Binop_12x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2215 break;
2216 }
2217
2218 case Instruction::MUL_FLOAT_2ADDR: {
2219 Binop_12x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2220 break;
2221 }
2222
2223 case Instruction::MUL_DOUBLE_2ADDR: {
2224 Binop_12x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2225 break;
2226 }
2227
2228 case Instruction::DIV_INT_2ADDR: {
2229 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2230 dex_pc, Primitive::kPrimInt, false, true);
2231 break;
2232 }
2233
2234 case Instruction::DIV_LONG_2ADDR: {
2235 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2236 dex_pc, Primitive::kPrimLong, false, true);
2237 break;
2238 }
2239
2240 case Instruction::REM_INT_2ADDR: {
2241 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2242 dex_pc, Primitive::kPrimInt, false, false);
2243 break;
2244 }
2245
2246 case Instruction::REM_LONG_2ADDR: {
2247 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2248 dex_pc, Primitive::kPrimLong, false, false);
2249 break;
2250 }
2251
2252 case Instruction::REM_FLOAT_2ADDR: {
2253 Binop_12x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2254 break;
2255 }
2256
2257 case Instruction::REM_DOUBLE_2ADDR: {
2258 Binop_12x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2259 break;
2260 }
2261
2262 case Instruction::SHL_INT_2ADDR: {
2263 Binop_12x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2264 break;
2265 }
2266
2267 case Instruction::SHL_LONG_2ADDR: {
2268 Binop_12x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2269 break;
2270 }
2271
2272 case Instruction::SHR_INT_2ADDR: {
2273 Binop_12x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2274 break;
2275 }
2276
2277 case Instruction::SHR_LONG_2ADDR: {
2278 Binop_12x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2279 break;
2280 }
2281
2282 case Instruction::USHR_INT_2ADDR: {
2283 Binop_12x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2284 break;
2285 }
2286
2287 case Instruction::USHR_LONG_2ADDR: {
2288 Binop_12x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2289 break;
2290 }
2291
2292 case Instruction::DIV_FLOAT_2ADDR: {
2293 Binop_12x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2294 break;
2295 }
2296
2297 case Instruction::DIV_DOUBLE_2ADDR: {
2298 Binop_12x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2299 break;
2300 }
2301
2302 case Instruction::AND_INT_2ADDR: {
2303 Binop_12x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2304 break;
2305 }
2306
2307 case Instruction::AND_LONG_2ADDR: {
2308 Binop_12x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2309 break;
2310 }
2311
2312 case Instruction::OR_INT_2ADDR: {
2313 Binop_12x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2314 break;
2315 }
2316
2317 case Instruction::OR_LONG_2ADDR: {
2318 Binop_12x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2319 break;
2320 }
2321
2322 case Instruction::XOR_INT_2ADDR: {
2323 Binop_12x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2324 break;
2325 }
2326
2327 case Instruction::XOR_LONG_2ADDR: {
2328 Binop_12x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2329 break;
2330 }
2331
2332 case Instruction::ADD_INT_LIT16: {
2333 Binop_22s<HAdd>(instruction, false, dex_pc);
2334 break;
2335 }
2336
2337 case Instruction::AND_INT_LIT16: {
2338 Binop_22s<HAnd>(instruction, false, dex_pc);
2339 break;
2340 }
2341
2342 case Instruction::OR_INT_LIT16: {
2343 Binop_22s<HOr>(instruction, false, dex_pc);
2344 break;
2345 }
2346
2347 case Instruction::XOR_INT_LIT16: {
2348 Binop_22s<HXor>(instruction, false, dex_pc);
2349 break;
2350 }
2351
2352 case Instruction::RSUB_INT: {
2353 Binop_22s<HSub>(instruction, true, dex_pc);
2354 break;
2355 }
2356
2357 case Instruction::MUL_INT_LIT16: {
2358 Binop_22s<HMul>(instruction, false, dex_pc);
2359 break;
2360 }
2361
2362 case Instruction::ADD_INT_LIT8: {
2363 Binop_22b<HAdd>(instruction, false, dex_pc);
2364 break;
2365 }
2366
2367 case Instruction::AND_INT_LIT8: {
2368 Binop_22b<HAnd>(instruction, false, dex_pc);
2369 break;
2370 }
2371
2372 case Instruction::OR_INT_LIT8: {
2373 Binop_22b<HOr>(instruction, false, dex_pc);
2374 break;
2375 }
2376
2377 case Instruction::XOR_INT_LIT8: {
2378 Binop_22b<HXor>(instruction, false, dex_pc);
2379 break;
2380 }
2381
2382 case Instruction::RSUB_INT_LIT8: {
2383 Binop_22b<HSub>(instruction, true, dex_pc);
2384 break;
2385 }
2386
2387 case Instruction::MUL_INT_LIT8: {
2388 Binop_22b<HMul>(instruction, false, dex_pc);
2389 break;
2390 }
2391
2392 case Instruction::DIV_INT_LIT16:
2393 case Instruction::DIV_INT_LIT8: {
2394 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2395 dex_pc, Primitive::kPrimInt, true, true);
2396 break;
2397 }
2398
2399 case Instruction::REM_INT_LIT16:
2400 case Instruction::REM_INT_LIT8: {
2401 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2402 dex_pc, Primitive::kPrimInt, true, false);
2403 break;
2404 }
2405
2406 case Instruction::SHL_INT_LIT8: {
2407 Binop_22b<HShl>(instruction, false, dex_pc);
2408 break;
2409 }
2410
2411 case Instruction::SHR_INT_LIT8: {
2412 Binop_22b<HShr>(instruction, false, dex_pc);
2413 break;
2414 }
2415
2416 case Instruction::USHR_INT_LIT8: {
2417 Binop_22b<HUShr>(instruction, false, dex_pc);
2418 break;
2419 }
2420
2421 case Instruction::NEW_INSTANCE: {
2422 if (!BuildNewInstance(instruction.VRegB_21c(), dex_pc)) {
2423 return false;
2424 }
2425 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
2426 break;
2427 }
2428
2429 case Instruction::NEW_ARRAY: {
2430 uint16_t type_index = instruction.VRegC_22c();
2431 HInstruction* length = LoadLocal(instruction.VRegB_22c(), Primitive::kPrimInt);
2432 bool finalizable;
2433 QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
2434 ? kQuickAllocArrayWithAccessCheck
2435 : kQuickAllocArray;
2436 AppendInstruction(new (arena_) HNewArray(length,
2437 graph_->GetCurrentMethod(),
2438 dex_pc,
2439 type_index,
2440 *dex_compilation_unit_->GetDexFile(),
2441 entrypoint));
2442 UpdateLocal(instruction.VRegA_22c(), current_block_->GetLastInstruction());
2443 break;
2444 }
2445
2446 case Instruction::FILLED_NEW_ARRAY: {
2447 uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
2448 uint32_t type_index = instruction.VRegB_35c();
2449 uint32_t args[5];
2450 instruction.GetVarArgs(args);
2451 BuildFilledNewArray(dex_pc, type_index, number_of_vreg_arguments, false, args, 0);
2452 break;
2453 }
2454
2455 case Instruction::FILLED_NEW_ARRAY_RANGE: {
2456 uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
2457 uint32_t type_index = instruction.VRegB_3rc();
2458 uint32_t register_index = instruction.VRegC_3rc();
2459 BuildFilledNewArray(
2460 dex_pc, type_index, number_of_vreg_arguments, true, nullptr, register_index);
2461 break;
2462 }
2463
2464 case Instruction::FILL_ARRAY_DATA: {
2465 BuildFillArrayData(instruction, dex_pc);
2466 break;
2467 }
2468
2469 case Instruction::MOVE_RESULT:
2470 case Instruction::MOVE_RESULT_WIDE:
2471 case Instruction::MOVE_RESULT_OBJECT: {
2472 DCHECK(latest_result_ != nullptr);
2473 UpdateLocal(instruction.VRegA(), latest_result_);
2474 latest_result_ = nullptr;
2475 break;
2476 }
2477
2478 case Instruction::CMP_LONG: {
2479 Binop_23x_cmp(instruction, Primitive::kPrimLong, ComparisonBias::kNoBias, dex_pc);
2480 break;
2481 }
2482
2483 case Instruction::CMPG_FLOAT: {
2484 Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kGtBias, dex_pc);
2485 break;
2486 }
2487
2488 case Instruction::CMPG_DOUBLE: {
2489 Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kGtBias, dex_pc);
2490 break;
2491 }
2492
2493 case Instruction::CMPL_FLOAT: {
2494 Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kLtBias, dex_pc);
2495 break;
2496 }
2497
2498 case Instruction::CMPL_DOUBLE: {
2499 Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kLtBias, dex_pc);
2500 break;
2501 }
2502
2503 case Instruction::NOP:
2504 break;
2505
2506 case Instruction::IGET:
2507 case Instruction::IGET_QUICK:
2508 case Instruction::IGET_WIDE:
2509 case Instruction::IGET_WIDE_QUICK:
2510 case Instruction::IGET_OBJECT:
2511 case Instruction::IGET_OBJECT_QUICK:
2512 case Instruction::IGET_BOOLEAN:
2513 case Instruction::IGET_BOOLEAN_QUICK:
2514 case Instruction::IGET_BYTE:
2515 case Instruction::IGET_BYTE_QUICK:
2516 case Instruction::IGET_CHAR:
2517 case Instruction::IGET_CHAR_QUICK:
2518 case Instruction::IGET_SHORT:
2519 case Instruction::IGET_SHORT_QUICK: {
2520 if (!BuildInstanceFieldAccess(instruction, dex_pc, false)) {
2521 return false;
2522 }
2523 break;
2524 }
2525
2526 case Instruction::IPUT:
2527 case Instruction::IPUT_QUICK:
2528 case Instruction::IPUT_WIDE:
2529 case Instruction::IPUT_WIDE_QUICK:
2530 case Instruction::IPUT_OBJECT:
2531 case Instruction::IPUT_OBJECT_QUICK:
2532 case Instruction::IPUT_BOOLEAN:
2533 case Instruction::IPUT_BOOLEAN_QUICK:
2534 case Instruction::IPUT_BYTE:
2535 case Instruction::IPUT_BYTE_QUICK:
2536 case Instruction::IPUT_CHAR:
2537 case Instruction::IPUT_CHAR_QUICK:
2538 case Instruction::IPUT_SHORT:
2539 case Instruction::IPUT_SHORT_QUICK: {
2540 if (!BuildInstanceFieldAccess(instruction, dex_pc, true)) {
2541 return false;
2542 }
2543 break;
2544 }
2545
2546 case Instruction::SGET:
2547 case Instruction::SGET_WIDE:
2548 case Instruction::SGET_OBJECT:
2549 case Instruction::SGET_BOOLEAN:
2550 case Instruction::SGET_BYTE:
2551 case Instruction::SGET_CHAR:
2552 case Instruction::SGET_SHORT: {
2553 if (!BuildStaticFieldAccess(instruction, dex_pc, false)) {
2554 return false;
2555 }
2556 break;
2557 }
2558
2559 case Instruction::SPUT:
2560 case Instruction::SPUT_WIDE:
2561 case Instruction::SPUT_OBJECT:
2562 case Instruction::SPUT_BOOLEAN:
2563 case Instruction::SPUT_BYTE:
2564 case Instruction::SPUT_CHAR:
2565 case Instruction::SPUT_SHORT: {
2566 if (!BuildStaticFieldAccess(instruction, dex_pc, true)) {
2567 return false;
2568 }
2569 break;
2570 }
2571
2572#define ARRAY_XX(kind, anticipated_type) \
2573 case Instruction::AGET##kind: { \
2574 BuildArrayAccess(instruction, dex_pc, false, anticipated_type); \
2575 break; \
2576 } \
2577 case Instruction::APUT##kind: { \
2578 BuildArrayAccess(instruction, dex_pc, true, anticipated_type); \
2579 break; \
2580 }
2581
2582 ARRAY_XX(, Primitive::kPrimInt);
2583 ARRAY_XX(_WIDE, Primitive::kPrimLong);
2584 ARRAY_XX(_OBJECT, Primitive::kPrimNot);
2585 ARRAY_XX(_BOOLEAN, Primitive::kPrimBoolean);
2586 ARRAY_XX(_BYTE, Primitive::kPrimByte);
2587 ARRAY_XX(_CHAR, Primitive::kPrimChar);
2588 ARRAY_XX(_SHORT, Primitive::kPrimShort);
2589
2590 case Instruction::ARRAY_LENGTH: {
David Brazdilc120bbe2016-04-22 16:57:00 +01002591 HInstruction* object = LoadNullCheckedLocal(instruction.VRegB_12x(), dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00002592 AppendInstruction(new (arena_) HArrayLength(object, dex_pc));
2593 UpdateLocal(instruction.VRegA_12x(), current_block_->GetLastInstruction());
2594 break;
2595 }
2596
2597 case Instruction::CONST_STRING: {
2598 uint32_t string_index = instruction.VRegB_21c();
2599 AppendInstruction(
2600 new (arena_) HLoadString(graph_->GetCurrentMethod(), string_index, *dex_file_, dex_pc));
2601 UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction());
2602 break;
2603 }
2604
2605 case Instruction::CONST_STRING_JUMBO: {
2606 uint32_t string_index = instruction.VRegB_31c();
2607 AppendInstruction(
2608 new (arena_) HLoadString(graph_->GetCurrentMethod(), string_index, *dex_file_, dex_pc));
2609 UpdateLocal(instruction.VRegA_31c(), current_block_->GetLastInstruction());
2610 break;
2611 }
2612
2613 case Instruction::CONST_CLASS: {
2614 uint16_t type_index = instruction.VRegB_21c();
David Brazdildee58d62016-04-07 09:54:26 +00002615 // `CanAccessTypeWithoutChecks` will tell whether the method being
2616 // built is trying to access its own class, so that the generated
2617 // code can optimize for this case. However, the optimization does not
2618 // work for inlining, so we use `IsOutermostCompilingClass` instead.
Vladimir Marko3cd50df2016-04-13 19:29:26 +01002619 ScopedObjectAccess soa(Thread::Current());
2620 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00002621 bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
Vladimir Marko3cd50df2016-04-13 19:29:26 +01002622 dex_compilation_unit_->GetDexMethodIndex(), dex_cache, type_index);
David Brazdildee58d62016-04-07 09:54:26 +00002623 AppendInstruction(new (arena_) HLoadClass(
2624 graph_->GetCurrentMethod(),
2625 type_index,
2626 *dex_file_,
2627 IsOutermostCompilingClass(type_index),
2628 dex_pc,
2629 !can_access,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002630 /* is_in_dex_cache */ false));
David Brazdildee58d62016-04-07 09:54:26 +00002631 UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction());
2632 break;
2633 }
2634
2635 case Instruction::MOVE_EXCEPTION: {
2636 AppendInstruction(new (arena_) HLoadException(dex_pc));
2637 UpdateLocal(instruction.VRegA_11x(), current_block_->GetLastInstruction());
2638 AppendInstruction(new (arena_) HClearException(dex_pc));
2639 break;
2640 }
2641
2642 case Instruction::THROW: {
2643 HInstruction* exception = LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot);
2644 AppendInstruction(new (arena_) HThrow(exception, dex_pc));
2645 // We finished building this block. Set the current block to null to avoid
2646 // adding dead instructions to it.
2647 current_block_ = nullptr;
2648 break;
2649 }
2650
2651 case Instruction::INSTANCE_OF: {
2652 uint8_t destination = instruction.VRegA_22c();
2653 uint8_t reference = instruction.VRegB_22c();
2654 uint16_t type_index = instruction.VRegC_22c();
2655 BuildTypeCheck(instruction, destination, reference, type_index, dex_pc);
2656 break;
2657 }
2658
2659 case Instruction::CHECK_CAST: {
2660 uint8_t reference = instruction.VRegA_21c();
2661 uint16_t type_index = instruction.VRegB_21c();
2662 BuildTypeCheck(instruction, -1, reference, type_index, dex_pc);
2663 break;
2664 }
2665
2666 case Instruction::MONITOR_ENTER: {
2667 AppendInstruction(new (arena_) HMonitorOperation(
2668 LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot),
2669 HMonitorOperation::OperationKind::kEnter,
2670 dex_pc));
2671 break;
2672 }
2673
2674 case Instruction::MONITOR_EXIT: {
2675 AppendInstruction(new (arena_) HMonitorOperation(
2676 LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot),
2677 HMonitorOperation::OperationKind::kExit,
2678 dex_pc));
2679 break;
2680 }
2681
2682 case Instruction::SPARSE_SWITCH:
2683 case Instruction::PACKED_SWITCH: {
2684 BuildSwitch(instruction, dex_pc);
2685 break;
2686 }
2687
2688 default:
2689 VLOG(compiler) << "Did not compile "
2690 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
2691 << " because of unhandled instruction "
2692 << instruction.Name();
2693 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnhandledInstruction);
2694 return false;
2695 }
2696 return true;
2697} // NOLINT(readability/fn_size)
2698
2699} // namespace art