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