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