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