blob: b4125299ea75343bf41dc605d11a06f8c0ae2a28 [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,
Aart Bik296fbb42016-06-07 13:49:12 -0700836 nullptr, /* clinit_check */
837 true /* is_unresolved */);
David Brazdildee58d62016-04-07 09:54:26 +0000838 }
839
840 // Potential class initialization check, in the case of a static method call.
841 HClinitCheck* clinit_check = nullptr;
842 HInvoke* invoke = nullptr;
843 if (invoke_type == kDirect || invoke_type == kStatic || invoke_type == kSuper) {
844 // By default, consider that the called method implicitly requires
845 // an initialization check of its declaring method.
846 HInvokeStaticOrDirect::ClinitCheckRequirement clinit_check_requirement
847 = HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit;
848 ScopedObjectAccess soa(Thread::Current());
849 if (invoke_type == kStatic) {
850 clinit_check = ProcessClinitCheckForInvoke(
851 dex_pc, resolved_method, method_idx, &clinit_check_requirement);
852 } else if (invoke_type == kSuper) {
853 if (IsSameDexFile(*resolved_method->GetDexFile(), *dex_compilation_unit_->GetDexFile())) {
854 // Update the target method to the one resolved. Note that this may be a no-op if
855 // we resolved to the method referenced by the instruction.
856 method_idx = resolved_method->GetDexMethodIndex();
857 target_method = MethodReference(dex_file_, method_idx);
858 }
859 }
860
861 HInvokeStaticOrDirect::DispatchInfo dispatch_info = {
862 HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod,
863 HInvokeStaticOrDirect::CodePtrLocation::kCallArtMethod,
864 0u,
865 0U
866 };
867 invoke = new (arena_) HInvokeStaticOrDirect(arena_,
868 number_of_arguments,
869 return_type,
870 dex_pc,
871 method_idx,
872 target_method,
873 dispatch_info,
874 invoke_type,
875 invoke_type,
876 clinit_check_requirement);
877 } else if (invoke_type == kVirtual) {
878 ScopedObjectAccess soa(Thread::Current()); // Needed for the method index
879 invoke = new (arena_) HInvokeVirtual(arena_,
880 number_of_arguments,
881 return_type,
882 dex_pc,
883 method_idx,
884 resolved_method->GetMethodIndex());
885 } else {
886 DCHECK_EQ(invoke_type, kInterface);
887 ScopedObjectAccess soa(Thread::Current()); // Needed for the method index
888 invoke = new (arena_) HInvokeInterface(arena_,
889 number_of_arguments,
890 return_type,
891 dex_pc,
892 method_idx,
Nicolas Geoffrayd4ceecc2016-06-29 08:39:47 +0000893 resolved_method->GetDexMethodIndex());
David Brazdildee58d62016-04-07 09:54:26 +0000894 }
895
896 return HandleInvoke(invoke,
897 number_of_vreg_arguments,
898 args,
899 register_index,
900 is_range,
901 descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -0700902 clinit_check,
903 false /* is_unresolved */);
David Brazdildee58d62016-04-07 09:54:26 +0000904}
905
906bool HInstructionBuilder::BuildNewInstance(uint16_t type_index, uint32_t dex_pc) {
Vladimir Marko3cd50df2016-04-13 19:29:26 +0100907 ScopedObjectAccess soa(Thread::Current());
908 StackHandleScope<1> hs(soa.Self());
909 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
910 Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
911 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
912 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
913
David Brazdildee58d62016-04-07 09:54:26 +0000914 bool finalizable;
Mingyao Yang062157f2016-03-02 10:15:36 -0800915 bool needs_access_check = NeedsAccessCheck(type_index, dex_cache, &finalizable);
David Brazdildee58d62016-04-07 09:54:26 +0000916
917 // Only the non-resolved entrypoint handles the finalizable class case. If we
918 // need access checks, then we haven't resolved the method and the class may
919 // again be finalizable.
Mingyao Yang062157f2016-03-02 10:15:36 -0800920 QuickEntrypointEnum entrypoint = (finalizable || needs_access_check)
David Brazdildee58d62016-04-07 09:54:26 +0000921 ? kQuickAllocObject
922 : kQuickAllocObjectInitialized;
923
David Brazdildee58d62016-04-07 09:54:26 +0000924 if (outer_dex_cache.Get() != dex_cache.Get()) {
925 // We currently do not support inlining allocations across dex files.
926 return false;
927 }
928
929 HLoadClass* load_class = new (arena_) HLoadClass(
930 graph_->GetCurrentMethod(),
931 type_index,
932 outer_dex_file,
933 IsOutermostCompilingClass(type_index),
934 dex_pc,
Mingyao Yang062157f2016-03-02 10:15:36 -0800935 needs_access_check,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +0100936 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +0000937
938 AppendInstruction(load_class);
939 HInstruction* cls = load_class;
940 if (!IsInitialized(resolved_class)) {
941 cls = new (arena_) HClinitCheck(load_class, dex_pc);
942 AppendInstruction(cls);
943 }
944
945 AppendInstruction(new (arena_) HNewInstance(
946 cls,
947 graph_->GetCurrentMethod(),
948 dex_pc,
949 type_index,
950 *dex_compilation_unit_->GetDexFile(),
Mingyao Yang062157f2016-03-02 10:15:36 -0800951 needs_access_check,
David Brazdildee58d62016-04-07 09:54:26 +0000952 finalizable,
953 entrypoint));
954 return true;
955}
956
957static bool IsSubClass(mirror::Class* to_test, mirror::Class* super_class)
958 SHARED_REQUIRES(Locks::mutator_lock_) {
959 return to_test != nullptr && !to_test->IsInterface() && to_test->IsSubClass(super_class);
960}
961
962bool HInstructionBuilder::IsInitialized(Handle<mirror::Class> cls) const {
963 if (cls.Get() == nullptr) {
964 return false;
965 }
966
967 // `CanAssumeClassIsLoaded` will return true if we're JITting, or will
968 // check whether the class is in an image for the AOT compilation.
969 if (cls->IsInitialized() &&
970 compiler_driver_->CanAssumeClassIsLoaded(cls.Get())) {
971 return true;
972 }
973
974 if (IsSubClass(GetOutermostCompilingClass(), cls.Get())) {
975 return true;
976 }
977
978 // TODO: We should walk over the inlined methods, but we don't pass
979 // that information to the builder.
980 if (IsSubClass(GetCompilingClass(), cls.Get())) {
981 return true;
982 }
983
984 return false;
985}
986
987HClinitCheck* HInstructionBuilder::ProcessClinitCheckForInvoke(
988 uint32_t dex_pc,
989 ArtMethod* resolved_method,
990 uint32_t method_idx,
991 HInvokeStaticOrDirect::ClinitCheckRequirement* clinit_check_requirement) {
992 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
993 Thread* self = Thread::Current();
Vladimir Marko3cd50df2016-04-13 19:29:26 +0100994 StackHandleScope<2> hs(self);
995 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
996 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +0000997 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
998 Handle<mirror::Class> resolved_method_class(hs.NewHandle(resolved_method->GetDeclaringClass()));
999
1000 // The index at which the method's class is stored in the DexCache's type array.
1001 uint32_t storage_index = DexFile::kDexNoIndex;
1002 bool is_outer_class = (resolved_method->GetDeclaringClass() == outer_class.Get());
1003 if (is_outer_class) {
1004 storage_index = outer_class->GetDexTypeIndex();
1005 } else if (outer_dex_cache.Get() == dex_cache.Get()) {
1006 // Get `storage_index` from IsClassOfStaticMethodAvailableToReferrer.
1007 compiler_driver_->IsClassOfStaticMethodAvailableToReferrer(outer_dex_cache.Get(),
1008 GetCompilingClass(),
1009 resolved_method,
1010 method_idx,
1011 &storage_index);
1012 }
1013
1014 HClinitCheck* clinit_check = nullptr;
1015
1016 if (IsInitialized(resolved_method_class)) {
1017 *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kNone;
1018 } else if (storage_index != DexFile::kDexNoIndex) {
1019 *clinit_check_requirement = HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit;
1020 HLoadClass* load_class = new (arena_) HLoadClass(
1021 graph_->GetCurrentMethod(),
1022 storage_index,
1023 outer_dex_file,
1024 is_outer_class,
1025 dex_pc,
1026 /*needs_access_check*/ false,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001027 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001028 AppendInstruction(load_class);
1029 clinit_check = new (arena_) HClinitCheck(load_class, dex_pc);
1030 AppendInstruction(clinit_check);
1031 }
1032 return clinit_check;
1033}
1034
1035bool HInstructionBuilder::SetupInvokeArguments(HInvoke* invoke,
1036 uint32_t number_of_vreg_arguments,
1037 uint32_t* args,
1038 uint32_t register_index,
1039 bool is_range,
1040 const char* descriptor,
1041 size_t start_index,
1042 size_t* argument_index) {
1043 uint32_t descriptor_index = 1; // Skip the return type.
1044
1045 for (size_t i = start_index;
1046 // Make sure we don't go over the expected arguments or over the number of
1047 // dex registers given. If the instruction was seen as dead by the verifier,
1048 // it hasn't been properly checked.
1049 (i < number_of_vreg_arguments) && (*argument_index < invoke->GetNumberOfArguments());
1050 i++, (*argument_index)++) {
1051 Primitive::Type type = Primitive::GetType(descriptor[descriptor_index++]);
1052 bool is_wide = (type == Primitive::kPrimLong) || (type == Primitive::kPrimDouble);
1053 if (!is_range
1054 && is_wide
1055 && ((i + 1 == number_of_vreg_arguments) || (args[i] + 1 != args[i + 1]))) {
1056 // Longs and doubles should be in pairs, that is, sequential registers. The verifier should
1057 // reject any class where this is violated. However, the verifier only does these checks
1058 // on non trivially dead instructions, so we just bailout the compilation.
1059 VLOG(compiler) << "Did not compile "
1060 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1061 << " because of non-sequential dex register pair in wide argument";
1062 MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1063 return false;
1064 }
1065 HInstruction* arg = LoadLocal(is_range ? register_index + i : args[i], type);
1066 invoke->SetArgumentAt(*argument_index, arg);
1067 if (is_wide) {
1068 i++;
1069 }
1070 }
1071
1072 if (*argument_index != invoke->GetNumberOfArguments()) {
1073 VLOG(compiler) << "Did not compile "
1074 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
1075 << " because of wrong number of arguments in invoke instruction";
1076 MaybeRecordStat(MethodCompilationStat::kNotCompiledMalformedOpcode);
1077 return false;
1078 }
1079
1080 if (invoke->IsInvokeStaticOrDirect() &&
1081 HInvokeStaticOrDirect::NeedsCurrentMethodInput(
1082 invoke->AsInvokeStaticOrDirect()->GetMethodLoadKind())) {
1083 invoke->SetArgumentAt(*argument_index, graph_->GetCurrentMethod());
1084 (*argument_index)++;
1085 }
1086
1087 return true;
1088}
1089
1090bool HInstructionBuilder::HandleInvoke(HInvoke* invoke,
1091 uint32_t number_of_vreg_arguments,
1092 uint32_t* args,
1093 uint32_t register_index,
1094 bool is_range,
1095 const char* descriptor,
Aart Bik296fbb42016-06-07 13:49:12 -07001096 HClinitCheck* clinit_check,
1097 bool is_unresolved) {
David Brazdildee58d62016-04-07 09:54:26 +00001098 DCHECK(!invoke->IsInvokeStaticOrDirect() || !invoke->AsInvokeStaticOrDirect()->IsStringInit());
1099
1100 size_t start_index = 0;
1101 size_t argument_index = 0;
1102 if (invoke->GetOriginalInvokeType() != InvokeType::kStatic) { // Instance call.
Aart Bik296fbb42016-06-07 13:49:12 -07001103 uint32_t obj_reg = is_range ? register_index : args[0];
1104 HInstruction* arg = is_unresolved
1105 ? LoadLocal(obj_reg, Primitive::kPrimNot)
1106 : LoadNullCheckedLocal(obj_reg, invoke->GetDexPc());
David Brazdilc120bbe2016-04-22 16:57:00 +01001107 invoke->SetArgumentAt(0, arg);
David Brazdildee58d62016-04-07 09:54:26 +00001108 start_index = 1;
1109 argument_index = 1;
1110 }
1111
1112 if (!SetupInvokeArguments(invoke,
1113 number_of_vreg_arguments,
1114 args,
1115 register_index,
1116 is_range,
1117 descriptor,
1118 start_index,
1119 &argument_index)) {
1120 return false;
1121 }
1122
1123 if (clinit_check != nullptr) {
1124 // Add the class initialization check as last input of `invoke`.
1125 DCHECK(invoke->IsInvokeStaticOrDirect());
1126 DCHECK(invoke->AsInvokeStaticOrDirect()->GetClinitCheckRequirement()
1127 == HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit);
1128 invoke->SetArgumentAt(argument_index, clinit_check);
1129 argument_index++;
1130 }
1131
1132 AppendInstruction(invoke);
1133 latest_result_ = invoke;
1134
1135 return true;
1136}
1137
1138bool HInstructionBuilder::HandleStringInit(HInvoke* invoke,
1139 uint32_t number_of_vreg_arguments,
1140 uint32_t* args,
1141 uint32_t register_index,
1142 bool is_range,
1143 const char* descriptor) {
1144 DCHECK(invoke->IsInvokeStaticOrDirect());
1145 DCHECK(invoke->AsInvokeStaticOrDirect()->IsStringInit());
1146
1147 size_t start_index = 1;
1148 size_t argument_index = 0;
1149 if (!SetupInvokeArguments(invoke,
1150 number_of_vreg_arguments,
1151 args,
1152 register_index,
1153 is_range,
1154 descriptor,
1155 start_index,
1156 &argument_index)) {
1157 return false;
1158 }
1159
1160 AppendInstruction(invoke);
1161
1162 // This is a StringFactory call, not an actual String constructor. Its result
1163 // replaces the empty String pre-allocated by NewInstance.
1164 uint32_t orig_this_reg = is_range ? register_index : args[0];
1165 HInstruction* arg_this = LoadLocal(orig_this_reg, Primitive::kPrimNot);
1166
1167 // Replacing the NewInstance might render it redundant. Keep a list of these
1168 // to be visited once it is clear whether it is has remaining uses.
1169 if (arg_this->IsNewInstance()) {
1170 ssa_builder_->AddUninitializedString(arg_this->AsNewInstance());
1171 } else {
1172 DCHECK(arg_this->IsPhi());
1173 // NewInstance is not the direct input of the StringFactory call. It might
1174 // be redundant but optimizing this case is not worth the effort.
1175 }
1176
1177 // Walk over all vregs and replace any occurrence of `arg_this` with `invoke`.
1178 for (size_t vreg = 0, e = current_locals_->size(); vreg < e; ++vreg) {
1179 if ((*current_locals_)[vreg] == arg_this) {
1180 (*current_locals_)[vreg] = invoke;
1181 }
1182 }
1183
1184 return true;
1185}
1186
1187static Primitive::Type GetFieldAccessType(const DexFile& dex_file, uint16_t field_index) {
1188 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_index);
1189 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
1190 return Primitive::GetType(type[0]);
1191}
1192
1193bool HInstructionBuilder::BuildInstanceFieldAccess(const Instruction& instruction,
1194 uint32_t dex_pc,
1195 bool is_put) {
1196 uint32_t source_or_dest_reg = instruction.VRegA_22c();
1197 uint32_t obj_reg = instruction.VRegB_22c();
1198 uint16_t field_index;
1199 if (instruction.IsQuickened()) {
1200 if (!CanDecodeQuickenedInfo()) {
1201 return false;
1202 }
1203 field_index = LookupQuickenedInfo(dex_pc);
1204 } else {
1205 field_index = instruction.VRegC_22c();
1206 }
1207
1208 ScopedObjectAccess soa(Thread::Current());
1209 ArtField* resolved_field =
1210 compiler_driver_->ComputeInstanceFieldInfo(field_index, dex_compilation_unit_, is_put, soa);
1211
1212
Aart Bik14154132016-06-02 17:53:58 -07001213 // Generate an explicit null check on the reference, unless the field access
1214 // is unresolved. In that case, we rely on the runtime to perform various
1215 // checks first, followed by a null check.
1216 HInstruction* object = (resolved_field == nullptr)
1217 ? LoadLocal(obj_reg, Primitive::kPrimNot)
1218 : LoadNullCheckedLocal(obj_reg, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001219
1220 Primitive::Type field_type = (resolved_field == nullptr)
1221 ? GetFieldAccessType(*dex_file_, field_index)
1222 : resolved_field->GetTypeAsPrimitiveType();
1223 if (is_put) {
1224 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1225 HInstruction* field_set = nullptr;
1226 if (resolved_field == nullptr) {
1227 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
David Brazdilc120bbe2016-04-22 16:57:00 +01001228 field_set = new (arena_) HUnresolvedInstanceFieldSet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001229 value,
1230 field_type,
1231 field_index,
1232 dex_pc);
1233 } else {
1234 uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
David Brazdilc120bbe2016-04-22 16:57:00 +01001235 field_set = new (arena_) HInstanceFieldSet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001236 value,
1237 field_type,
1238 resolved_field->GetOffset(),
1239 resolved_field->IsVolatile(),
1240 field_index,
1241 class_def_index,
1242 *dex_file_,
1243 dex_compilation_unit_->GetDexCache(),
1244 dex_pc);
1245 }
1246 AppendInstruction(field_set);
1247 } else {
1248 HInstruction* field_get = nullptr;
1249 if (resolved_field == nullptr) {
1250 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
David Brazdilc120bbe2016-04-22 16:57:00 +01001251 field_get = new (arena_) HUnresolvedInstanceFieldGet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001252 field_type,
1253 field_index,
1254 dex_pc);
1255 } else {
1256 uint16_t class_def_index = resolved_field->GetDeclaringClass()->GetDexClassDefIndex();
David Brazdilc120bbe2016-04-22 16:57:00 +01001257 field_get = new (arena_) HInstanceFieldGet(object,
David Brazdildee58d62016-04-07 09:54:26 +00001258 field_type,
1259 resolved_field->GetOffset(),
1260 resolved_field->IsVolatile(),
1261 field_index,
1262 class_def_index,
1263 *dex_file_,
1264 dex_compilation_unit_->GetDexCache(),
1265 dex_pc);
1266 }
1267 AppendInstruction(field_get);
1268 UpdateLocal(source_or_dest_reg, field_get);
1269 }
1270
1271 return true;
1272}
1273
1274static mirror::Class* GetClassFrom(CompilerDriver* driver,
1275 const DexCompilationUnit& compilation_unit) {
1276 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001277 StackHandleScope<1> hs(soa.Self());
David Brazdildee58d62016-04-07 09:54:26 +00001278 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1279 soa.Decode<mirror::ClassLoader*>(compilation_unit.GetClassLoader())));
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001280 Handle<mirror::DexCache> dex_cache = compilation_unit.GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001281
1282 return driver->ResolveCompilingMethodsClass(soa, dex_cache, class_loader, &compilation_unit);
1283}
1284
1285mirror::Class* HInstructionBuilder::GetOutermostCompilingClass() const {
1286 return GetClassFrom(compiler_driver_, *outer_compilation_unit_);
1287}
1288
1289mirror::Class* HInstructionBuilder::GetCompilingClass() const {
1290 return GetClassFrom(compiler_driver_, *dex_compilation_unit_);
1291}
1292
1293bool HInstructionBuilder::IsOutermostCompilingClass(uint16_t type_index) const {
1294 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001295 StackHandleScope<3> hs(soa.Self());
1296 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001297 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1298 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1299 Handle<mirror::Class> cls(hs.NewHandle(compiler_driver_->ResolveClass(
1300 soa, dex_cache, class_loader, type_index, dex_compilation_unit_)));
1301 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1302
1303 // GetOutermostCompilingClass returns null when the class is unresolved
1304 // (e.g. if it derives from an unresolved class). This is bogus knowing that
1305 // we are compiling it.
1306 // When this happens we cannot establish a direct relation between the current
1307 // class and the outer class, so we return false.
1308 // (Note that this is only used for optimizing invokes and field accesses)
1309 return (cls.Get() != nullptr) && (outer_class.Get() == cls.Get());
1310}
1311
1312void HInstructionBuilder::BuildUnresolvedStaticFieldAccess(const Instruction& instruction,
1313 uint32_t dex_pc,
1314 bool is_put,
1315 Primitive::Type field_type) {
1316 uint32_t source_or_dest_reg = instruction.VRegA_21c();
1317 uint16_t field_index = instruction.VRegB_21c();
1318
1319 if (is_put) {
1320 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1321 AppendInstruction(
1322 new (arena_) HUnresolvedStaticFieldSet(value, field_type, field_index, dex_pc));
1323 } else {
1324 AppendInstruction(new (arena_) HUnresolvedStaticFieldGet(field_type, field_index, dex_pc));
1325 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1326 }
1327}
1328
1329bool HInstructionBuilder::BuildStaticFieldAccess(const Instruction& instruction,
1330 uint32_t dex_pc,
1331 bool is_put) {
1332 uint32_t source_or_dest_reg = instruction.VRegA_21c();
1333 uint16_t field_index = instruction.VRegB_21c();
1334
1335 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001336 StackHandleScope<3> hs(soa.Self());
1337 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001338 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1339 soa.Decode<mirror::ClassLoader*>(dex_compilation_unit_->GetClassLoader())));
1340 ArtField* resolved_field = compiler_driver_->ResolveField(
1341 soa, dex_cache, class_loader, dex_compilation_unit_, field_index, true);
1342
1343 if (resolved_field == nullptr) {
1344 MaybeRecordStat(MethodCompilationStat::kUnresolvedField);
1345 Primitive::Type field_type = GetFieldAccessType(*dex_file_, field_index);
1346 BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1347 return true;
1348 }
1349
1350 Primitive::Type field_type = resolved_field->GetTypeAsPrimitiveType();
1351 const DexFile& outer_dex_file = *outer_compilation_unit_->GetDexFile();
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001352 Handle<mirror::DexCache> outer_dex_cache = outer_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00001353 Handle<mirror::Class> outer_class(hs.NewHandle(GetOutermostCompilingClass()));
1354
1355 // The index at which the field's class is stored in the DexCache's type array.
1356 uint32_t storage_index;
1357 bool is_outer_class = (outer_class.Get() == resolved_field->GetDeclaringClass());
1358 if (is_outer_class) {
1359 storage_index = outer_class->GetDexTypeIndex();
1360 } else if (outer_dex_cache.Get() != dex_cache.Get()) {
1361 // The compiler driver cannot currently understand multiple dex caches involved. Just bailout.
1362 return false;
1363 } else {
1364 // TODO: This is rather expensive. Perf it and cache the results if needed.
1365 std::pair<bool, bool> pair = compiler_driver_->IsFastStaticField(
1366 outer_dex_cache.Get(),
1367 GetCompilingClass(),
1368 resolved_field,
1369 field_index,
1370 &storage_index);
1371 bool can_easily_access = is_put ? pair.second : pair.first;
1372 if (!can_easily_access) {
1373 MaybeRecordStat(MethodCompilationStat::kUnresolvedFieldNotAFastAccess);
1374 BuildUnresolvedStaticFieldAccess(instruction, dex_pc, is_put, field_type);
1375 return true;
1376 }
1377 }
1378
David Brazdildee58d62016-04-07 09:54:26 +00001379 HLoadClass* constant = new (arena_) HLoadClass(graph_->GetCurrentMethod(),
1380 storage_index,
1381 outer_dex_file,
1382 is_outer_class,
1383 dex_pc,
1384 /*needs_access_check*/ false,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001385 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001386 AppendInstruction(constant);
1387
1388 HInstruction* cls = constant;
1389
1390 Handle<mirror::Class> klass(hs.NewHandle(resolved_field->GetDeclaringClass()));
1391 if (!IsInitialized(klass)) {
1392 cls = new (arena_) HClinitCheck(constant, dex_pc);
1393 AppendInstruction(cls);
1394 }
1395
1396 uint16_t class_def_index = klass->GetDexClassDefIndex();
1397 if (is_put) {
1398 // We need to keep the class alive before loading the value.
1399 HInstruction* value = LoadLocal(source_or_dest_reg, field_type);
1400 DCHECK_EQ(HPhi::ToPhiType(value->GetType()), HPhi::ToPhiType(field_type));
1401 AppendInstruction(new (arena_) HStaticFieldSet(cls,
1402 value,
1403 field_type,
1404 resolved_field->GetOffset(),
1405 resolved_field->IsVolatile(),
1406 field_index,
1407 class_def_index,
1408 *dex_file_,
1409 dex_cache_,
1410 dex_pc));
1411 } else {
1412 AppendInstruction(new (arena_) HStaticFieldGet(cls,
1413 field_type,
1414 resolved_field->GetOffset(),
1415 resolved_field->IsVolatile(),
1416 field_index,
1417 class_def_index,
1418 *dex_file_,
1419 dex_cache_,
1420 dex_pc));
1421 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1422 }
1423 return true;
1424}
1425
1426void HInstructionBuilder::BuildCheckedDivRem(uint16_t out_vreg,
1427 uint16_t first_vreg,
1428 int64_t second_vreg_or_constant,
1429 uint32_t dex_pc,
1430 Primitive::Type type,
1431 bool second_is_constant,
1432 bool isDiv) {
1433 DCHECK(type == Primitive::kPrimInt || type == Primitive::kPrimLong);
1434
1435 HInstruction* first = LoadLocal(first_vreg, type);
1436 HInstruction* second = nullptr;
1437 if (second_is_constant) {
1438 if (type == Primitive::kPrimInt) {
1439 second = graph_->GetIntConstant(second_vreg_or_constant, dex_pc);
1440 } else {
1441 second = graph_->GetLongConstant(second_vreg_or_constant, dex_pc);
1442 }
1443 } else {
1444 second = LoadLocal(second_vreg_or_constant, type);
1445 }
1446
1447 if (!second_is_constant
1448 || (type == Primitive::kPrimInt && second->AsIntConstant()->GetValue() == 0)
1449 || (type == Primitive::kPrimLong && second->AsLongConstant()->GetValue() == 0)) {
1450 second = new (arena_) HDivZeroCheck(second, dex_pc);
1451 AppendInstruction(second);
1452 }
1453
1454 if (isDiv) {
1455 AppendInstruction(new (arena_) HDiv(type, first, second, dex_pc));
1456 } else {
1457 AppendInstruction(new (arena_) HRem(type, first, second, dex_pc));
1458 }
1459 UpdateLocal(out_vreg, current_block_->GetLastInstruction());
1460}
1461
1462void HInstructionBuilder::BuildArrayAccess(const Instruction& instruction,
1463 uint32_t dex_pc,
1464 bool is_put,
1465 Primitive::Type anticipated_type) {
1466 uint8_t source_or_dest_reg = instruction.VRegA_23x();
1467 uint8_t array_reg = instruction.VRegB_23x();
1468 uint8_t index_reg = instruction.VRegC_23x();
1469
David Brazdilc120bbe2016-04-22 16:57:00 +01001470 HInstruction* object = LoadNullCheckedLocal(array_reg, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001471 HInstruction* length = new (arena_) HArrayLength(object, dex_pc);
1472 AppendInstruction(length);
1473 HInstruction* index = LoadLocal(index_reg, Primitive::kPrimInt);
1474 index = new (arena_) HBoundsCheck(index, length, dex_pc);
1475 AppendInstruction(index);
1476 if (is_put) {
1477 HInstruction* value = LoadLocal(source_or_dest_reg, anticipated_type);
1478 // TODO: Insert a type check node if the type is Object.
1479 HArraySet* aset = new (arena_) HArraySet(object, index, value, anticipated_type, dex_pc);
1480 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1481 AppendInstruction(aset);
1482 } else {
1483 HArrayGet* aget = new (arena_) HArrayGet(object, index, anticipated_type, dex_pc);
1484 ssa_builder_->MaybeAddAmbiguousArrayGet(aget);
1485 AppendInstruction(aget);
1486 UpdateLocal(source_or_dest_reg, current_block_->GetLastInstruction());
1487 }
1488 graph_->SetHasBoundsChecks(true);
1489}
1490
1491void HInstructionBuilder::BuildFilledNewArray(uint32_t dex_pc,
1492 uint32_t type_index,
1493 uint32_t number_of_vreg_arguments,
1494 bool is_range,
1495 uint32_t* args,
1496 uint32_t register_index) {
1497 HInstruction* length = graph_->GetIntConstant(number_of_vreg_arguments, dex_pc);
1498 bool finalizable;
1499 QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
1500 ? kQuickAllocArrayWithAccessCheck
1501 : kQuickAllocArray;
1502 HInstruction* object = new (arena_) HNewArray(length,
1503 graph_->GetCurrentMethod(),
1504 dex_pc,
1505 type_index,
1506 *dex_compilation_unit_->GetDexFile(),
1507 entrypoint);
1508 AppendInstruction(object);
1509
1510 const char* descriptor = dex_file_->StringByTypeIdx(type_index);
1511 DCHECK_EQ(descriptor[0], '[') << descriptor;
1512 char primitive = descriptor[1];
1513 DCHECK(primitive == 'I'
1514 || primitive == 'L'
1515 || primitive == '[') << descriptor;
1516 bool is_reference_array = (primitive == 'L') || (primitive == '[');
1517 Primitive::Type type = is_reference_array ? Primitive::kPrimNot : Primitive::kPrimInt;
1518
1519 for (size_t i = 0; i < number_of_vreg_arguments; ++i) {
1520 HInstruction* value = LoadLocal(is_range ? register_index + i : args[i], type);
1521 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1522 HArraySet* aset = new (arena_) HArraySet(object, index, value, type, dex_pc);
1523 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1524 AppendInstruction(aset);
1525 }
1526 latest_result_ = object;
1527}
1528
1529template <typename T>
1530void HInstructionBuilder::BuildFillArrayData(HInstruction* object,
1531 const T* data,
1532 uint32_t element_count,
1533 Primitive::Type anticipated_type,
1534 uint32_t dex_pc) {
1535 for (uint32_t i = 0; i < element_count; ++i) {
1536 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1537 HInstruction* value = graph_->GetIntConstant(data[i], dex_pc);
1538 HArraySet* aset = new (arena_) HArraySet(object, index, value, anticipated_type, dex_pc);
1539 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1540 AppendInstruction(aset);
1541 }
1542}
1543
1544void HInstructionBuilder::BuildFillArrayData(const Instruction& instruction, uint32_t dex_pc) {
David Brazdilc120bbe2016-04-22 16:57:00 +01001545 HInstruction* array = LoadNullCheckedLocal(instruction.VRegA_31t(), dex_pc);
1546 HInstruction* length = new (arena_) HArrayLength(array, dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00001547 AppendInstruction(length);
1548
1549 int32_t payload_offset = instruction.VRegB_31t() + dex_pc;
1550 const Instruction::ArrayDataPayload* payload =
1551 reinterpret_cast<const Instruction::ArrayDataPayload*>(code_item_.insns_ + payload_offset);
1552 const uint8_t* data = payload->data;
1553 uint32_t element_count = payload->element_count;
1554
1555 // Implementation of this DEX instruction seems to be that the bounds check is
1556 // done before doing any stores.
1557 HInstruction* last_index = graph_->GetIntConstant(payload->element_count - 1, dex_pc);
1558 AppendInstruction(new (arena_) HBoundsCheck(last_index, length, dex_pc));
1559
1560 switch (payload->element_width) {
1561 case 1:
David Brazdilc120bbe2016-04-22 16:57:00 +01001562 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001563 reinterpret_cast<const int8_t*>(data),
1564 element_count,
1565 Primitive::kPrimByte,
1566 dex_pc);
1567 break;
1568 case 2:
David Brazdilc120bbe2016-04-22 16:57:00 +01001569 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001570 reinterpret_cast<const int16_t*>(data),
1571 element_count,
1572 Primitive::kPrimShort,
1573 dex_pc);
1574 break;
1575 case 4:
David Brazdilc120bbe2016-04-22 16:57:00 +01001576 BuildFillArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001577 reinterpret_cast<const int32_t*>(data),
1578 element_count,
1579 Primitive::kPrimInt,
1580 dex_pc);
1581 break;
1582 case 8:
David Brazdilc120bbe2016-04-22 16:57:00 +01001583 BuildFillWideArrayData(array,
David Brazdildee58d62016-04-07 09:54:26 +00001584 reinterpret_cast<const int64_t*>(data),
1585 element_count,
1586 dex_pc);
1587 break;
1588 default:
1589 LOG(FATAL) << "Unknown element width for " << payload->element_width;
1590 }
1591 graph_->SetHasBoundsChecks(true);
1592}
1593
1594void HInstructionBuilder::BuildFillWideArrayData(HInstruction* object,
1595 const int64_t* data,
1596 uint32_t element_count,
1597 uint32_t dex_pc) {
1598 for (uint32_t i = 0; i < element_count; ++i) {
1599 HInstruction* index = graph_->GetIntConstant(i, dex_pc);
1600 HInstruction* value = graph_->GetLongConstant(data[i], dex_pc);
1601 HArraySet* aset = new (arena_) HArraySet(object, index, value, Primitive::kPrimLong, dex_pc);
1602 ssa_builder_->MaybeAddAmbiguousArraySet(aset);
1603 AppendInstruction(aset);
1604 }
1605}
1606
1607static TypeCheckKind ComputeTypeCheckKind(Handle<mirror::Class> cls)
1608 SHARED_REQUIRES(Locks::mutator_lock_) {
1609 if (cls.Get() == nullptr) {
1610 return TypeCheckKind::kUnresolvedCheck;
1611 } else if (cls->IsInterface()) {
1612 return TypeCheckKind::kInterfaceCheck;
1613 } else if (cls->IsArrayClass()) {
1614 if (cls->GetComponentType()->IsObjectClass()) {
1615 return TypeCheckKind::kArrayObjectCheck;
1616 } else if (cls->CannotBeAssignedFromOtherTypes()) {
1617 return TypeCheckKind::kExactCheck;
1618 } else {
1619 return TypeCheckKind::kArrayCheck;
1620 }
1621 } else if (cls->IsFinal()) {
1622 return TypeCheckKind::kExactCheck;
1623 } else if (cls->IsAbstract()) {
1624 return TypeCheckKind::kAbstractClassCheck;
1625 } else {
1626 return TypeCheckKind::kClassHierarchyCheck;
1627 }
1628}
1629
1630void HInstructionBuilder::BuildTypeCheck(const Instruction& instruction,
1631 uint8_t destination,
1632 uint8_t reference,
1633 uint16_t type_index,
1634 uint32_t dex_pc) {
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001635 ScopedObjectAccess soa(Thread::Current());
1636 StackHandleScope<1> hs(soa.Self());
1637 const DexFile& dex_file = *dex_compilation_unit_->GetDexFile();
1638 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
1639 Handle<mirror::Class> resolved_class(hs.NewHandle(dex_cache->GetResolvedType(type_index)));
1640
David Brazdildee58d62016-04-07 09:54:26 +00001641 bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
1642 dex_compilation_unit_->GetDexMethodIndex(),
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001643 dex_cache,
1644 type_index);
David Brazdildee58d62016-04-07 09:54:26 +00001645
1646 HInstruction* object = LoadLocal(reference, Primitive::kPrimNot);
1647 HLoadClass* cls = new (arena_) HLoadClass(
1648 graph_->GetCurrentMethod(),
1649 type_index,
1650 dex_file,
1651 IsOutermostCompilingClass(type_index),
1652 dex_pc,
1653 !can_access,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01001654 /* is_in_dex_cache */ false);
David Brazdildee58d62016-04-07 09:54:26 +00001655 AppendInstruction(cls);
1656
1657 TypeCheckKind check_kind = ComputeTypeCheckKind(resolved_class);
1658 if (instruction.Opcode() == Instruction::INSTANCE_OF) {
1659 AppendInstruction(new (arena_) HInstanceOf(object, cls, check_kind, dex_pc));
1660 UpdateLocal(destination, current_block_->GetLastInstruction());
1661 } else {
1662 DCHECK_EQ(instruction.Opcode(), Instruction::CHECK_CAST);
1663 // We emit a CheckCast followed by a BoundType. CheckCast is a statement
1664 // which may throw. If it succeeds BoundType sets the new type of `object`
1665 // for all subsequent uses.
1666 AppendInstruction(new (arena_) HCheckCast(object, cls, check_kind, dex_pc));
1667 AppendInstruction(new (arena_) HBoundType(object, dex_pc));
1668 UpdateLocal(reference, current_block_->GetLastInstruction());
1669 }
1670}
1671
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001672bool HInstructionBuilder::NeedsAccessCheck(uint32_t type_index,
1673 Handle<mirror::DexCache> dex_cache,
1674 bool* finalizable) const {
David Brazdildee58d62016-04-07 09:54:26 +00001675 return !compiler_driver_->CanAccessInstantiableTypeWithoutChecks(
Vladimir Marko3cd50df2016-04-13 19:29:26 +01001676 dex_compilation_unit_->GetDexMethodIndex(), dex_cache, type_index, finalizable);
1677}
1678
1679bool HInstructionBuilder::NeedsAccessCheck(uint32_t type_index, bool* finalizable) const {
1680 ScopedObjectAccess soa(Thread::Current());
1681 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
1682 return NeedsAccessCheck(type_index, dex_cache, finalizable);
David Brazdildee58d62016-04-07 09:54:26 +00001683}
1684
1685bool HInstructionBuilder::CanDecodeQuickenedInfo() const {
1686 return interpreter_metadata_ != nullptr;
1687}
1688
1689uint16_t HInstructionBuilder::LookupQuickenedInfo(uint32_t dex_pc) {
1690 DCHECK(interpreter_metadata_ != nullptr);
1691
1692 // First check if the info has already been decoded from `interpreter_metadata_`.
1693 auto it = skipped_interpreter_metadata_.find(dex_pc);
1694 if (it != skipped_interpreter_metadata_.end()) {
1695 // Remove the entry from the map and return the parsed info.
1696 uint16_t value_in_map = it->second;
1697 skipped_interpreter_metadata_.erase(it);
1698 return value_in_map;
1699 }
1700
1701 // Otherwise start parsing `interpreter_metadata_` until the slot for `dex_pc`
1702 // is found. Store skipped values in the `skipped_interpreter_metadata_` map.
1703 while (true) {
1704 uint32_t dex_pc_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1705 uint16_t value_in_map = DecodeUnsignedLeb128(&interpreter_metadata_);
1706 DCHECK_LE(dex_pc_in_map, dex_pc);
1707
1708 if (dex_pc_in_map == dex_pc) {
1709 return value_in_map;
1710 } else {
1711 skipped_interpreter_metadata_.Put(dex_pc_in_map, value_in_map);
1712 }
1713 }
1714}
1715
1716bool HInstructionBuilder::ProcessDexInstruction(const Instruction& instruction, uint32_t dex_pc) {
1717 switch (instruction.Opcode()) {
1718 case Instruction::CONST_4: {
1719 int32_t register_index = instruction.VRegA();
1720 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_11n(), dex_pc);
1721 UpdateLocal(register_index, constant);
1722 break;
1723 }
1724
1725 case Instruction::CONST_16: {
1726 int32_t register_index = instruction.VRegA();
1727 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21s(), dex_pc);
1728 UpdateLocal(register_index, constant);
1729 break;
1730 }
1731
1732 case Instruction::CONST: {
1733 int32_t register_index = instruction.VRegA();
1734 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_31i(), dex_pc);
1735 UpdateLocal(register_index, constant);
1736 break;
1737 }
1738
1739 case Instruction::CONST_HIGH16: {
1740 int32_t register_index = instruction.VRegA();
1741 HIntConstant* constant = graph_->GetIntConstant(instruction.VRegB_21h() << 16, dex_pc);
1742 UpdateLocal(register_index, constant);
1743 break;
1744 }
1745
1746 case Instruction::CONST_WIDE_16: {
1747 int32_t register_index = instruction.VRegA();
1748 // Get 16 bits of constant value, sign extended to 64 bits.
1749 int64_t value = instruction.VRegB_21s();
1750 value <<= 48;
1751 value >>= 48;
1752 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1753 UpdateLocal(register_index, constant);
1754 break;
1755 }
1756
1757 case Instruction::CONST_WIDE_32: {
1758 int32_t register_index = instruction.VRegA();
1759 // Get 32 bits of constant value, sign extended to 64 bits.
1760 int64_t value = instruction.VRegB_31i();
1761 value <<= 32;
1762 value >>= 32;
1763 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1764 UpdateLocal(register_index, constant);
1765 break;
1766 }
1767
1768 case Instruction::CONST_WIDE: {
1769 int32_t register_index = instruction.VRegA();
1770 HLongConstant* constant = graph_->GetLongConstant(instruction.VRegB_51l(), dex_pc);
1771 UpdateLocal(register_index, constant);
1772 break;
1773 }
1774
1775 case Instruction::CONST_WIDE_HIGH16: {
1776 int32_t register_index = instruction.VRegA();
1777 int64_t value = static_cast<int64_t>(instruction.VRegB_21h()) << 48;
1778 HLongConstant* constant = graph_->GetLongConstant(value, dex_pc);
1779 UpdateLocal(register_index, constant);
1780 break;
1781 }
1782
1783 // Note that the SSA building will refine the types.
1784 case Instruction::MOVE:
1785 case Instruction::MOVE_FROM16:
1786 case Instruction::MOVE_16: {
1787 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimInt);
1788 UpdateLocal(instruction.VRegA(), value);
1789 break;
1790 }
1791
1792 // Note that the SSA building will refine the types.
1793 case Instruction::MOVE_WIDE:
1794 case Instruction::MOVE_WIDE_FROM16:
1795 case Instruction::MOVE_WIDE_16: {
1796 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimLong);
1797 UpdateLocal(instruction.VRegA(), value);
1798 break;
1799 }
1800
1801 case Instruction::MOVE_OBJECT:
1802 case Instruction::MOVE_OBJECT_16:
1803 case Instruction::MOVE_OBJECT_FROM16: {
1804 HInstruction* value = LoadLocal(instruction.VRegB(), Primitive::kPrimNot);
1805 UpdateLocal(instruction.VRegA(), value);
1806 break;
1807 }
1808
1809 case Instruction::RETURN_VOID_NO_BARRIER:
1810 case Instruction::RETURN_VOID: {
1811 BuildReturn(instruction, Primitive::kPrimVoid, dex_pc);
1812 break;
1813 }
1814
1815#define IF_XX(comparison, cond) \
1816 case Instruction::IF_##cond: If_22t<comparison>(instruction, dex_pc); break; \
1817 case Instruction::IF_##cond##Z: If_21t<comparison>(instruction, dex_pc); break
1818
1819 IF_XX(HEqual, EQ);
1820 IF_XX(HNotEqual, NE);
1821 IF_XX(HLessThan, LT);
1822 IF_XX(HLessThanOrEqual, LE);
1823 IF_XX(HGreaterThan, GT);
1824 IF_XX(HGreaterThanOrEqual, GE);
1825
1826 case Instruction::GOTO:
1827 case Instruction::GOTO_16:
1828 case Instruction::GOTO_32: {
1829 AppendInstruction(new (arena_) HGoto(dex_pc));
1830 current_block_ = nullptr;
1831 break;
1832 }
1833
1834 case Instruction::RETURN: {
1835 BuildReturn(instruction, return_type_, dex_pc);
1836 break;
1837 }
1838
1839 case Instruction::RETURN_OBJECT: {
1840 BuildReturn(instruction, return_type_, dex_pc);
1841 break;
1842 }
1843
1844 case Instruction::RETURN_WIDE: {
1845 BuildReturn(instruction, return_type_, dex_pc);
1846 break;
1847 }
1848
1849 case Instruction::INVOKE_DIRECT:
1850 case Instruction::INVOKE_INTERFACE:
1851 case Instruction::INVOKE_STATIC:
1852 case Instruction::INVOKE_SUPER:
1853 case Instruction::INVOKE_VIRTUAL:
1854 case Instruction::INVOKE_VIRTUAL_QUICK: {
1855 uint16_t method_idx;
1856 if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_QUICK) {
1857 if (!CanDecodeQuickenedInfo()) {
1858 return false;
1859 }
1860 method_idx = LookupQuickenedInfo(dex_pc);
1861 } else {
1862 method_idx = instruction.VRegB_35c();
1863 }
1864 uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
1865 uint32_t args[5];
1866 instruction.GetVarArgs(args);
1867 if (!BuildInvoke(instruction, dex_pc, method_idx,
1868 number_of_vreg_arguments, false, args, -1)) {
1869 return false;
1870 }
1871 break;
1872 }
1873
1874 case Instruction::INVOKE_DIRECT_RANGE:
1875 case Instruction::INVOKE_INTERFACE_RANGE:
1876 case Instruction::INVOKE_STATIC_RANGE:
1877 case Instruction::INVOKE_SUPER_RANGE:
1878 case Instruction::INVOKE_VIRTUAL_RANGE:
1879 case Instruction::INVOKE_VIRTUAL_RANGE_QUICK: {
1880 uint16_t method_idx;
1881 if (instruction.Opcode() == Instruction::INVOKE_VIRTUAL_RANGE_QUICK) {
1882 if (!CanDecodeQuickenedInfo()) {
1883 return false;
1884 }
1885 method_idx = LookupQuickenedInfo(dex_pc);
1886 } else {
1887 method_idx = instruction.VRegB_3rc();
1888 }
1889 uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
1890 uint32_t register_index = instruction.VRegC();
1891 if (!BuildInvoke(instruction, dex_pc, method_idx,
1892 number_of_vreg_arguments, true, nullptr, register_index)) {
1893 return false;
1894 }
1895 break;
1896 }
1897
1898 case Instruction::NEG_INT: {
1899 Unop_12x<HNeg>(instruction, Primitive::kPrimInt, dex_pc);
1900 break;
1901 }
1902
1903 case Instruction::NEG_LONG: {
1904 Unop_12x<HNeg>(instruction, Primitive::kPrimLong, dex_pc);
1905 break;
1906 }
1907
1908 case Instruction::NEG_FLOAT: {
1909 Unop_12x<HNeg>(instruction, Primitive::kPrimFloat, dex_pc);
1910 break;
1911 }
1912
1913 case Instruction::NEG_DOUBLE: {
1914 Unop_12x<HNeg>(instruction, Primitive::kPrimDouble, dex_pc);
1915 break;
1916 }
1917
1918 case Instruction::NOT_INT: {
1919 Unop_12x<HNot>(instruction, Primitive::kPrimInt, dex_pc);
1920 break;
1921 }
1922
1923 case Instruction::NOT_LONG: {
1924 Unop_12x<HNot>(instruction, Primitive::kPrimLong, dex_pc);
1925 break;
1926 }
1927
1928 case Instruction::INT_TO_LONG: {
1929 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimLong, dex_pc);
1930 break;
1931 }
1932
1933 case Instruction::INT_TO_FLOAT: {
1934 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimFloat, dex_pc);
1935 break;
1936 }
1937
1938 case Instruction::INT_TO_DOUBLE: {
1939 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimDouble, dex_pc);
1940 break;
1941 }
1942
1943 case Instruction::LONG_TO_INT: {
1944 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimInt, dex_pc);
1945 break;
1946 }
1947
1948 case Instruction::LONG_TO_FLOAT: {
1949 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimFloat, dex_pc);
1950 break;
1951 }
1952
1953 case Instruction::LONG_TO_DOUBLE: {
1954 Conversion_12x(instruction, Primitive::kPrimLong, Primitive::kPrimDouble, dex_pc);
1955 break;
1956 }
1957
1958 case Instruction::FLOAT_TO_INT: {
1959 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimInt, dex_pc);
1960 break;
1961 }
1962
1963 case Instruction::FLOAT_TO_LONG: {
1964 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimLong, dex_pc);
1965 break;
1966 }
1967
1968 case Instruction::FLOAT_TO_DOUBLE: {
1969 Conversion_12x(instruction, Primitive::kPrimFloat, Primitive::kPrimDouble, dex_pc);
1970 break;
1971 }
1972
1973 case Instruction::DOUBLE_TO_INT: {
1974 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimInt, dex_pc);
1975 break;
1976 }
1977
1978 case Instruction::DOUBLE_TO_LONG: {
1979 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimLong, dex_pc);
1980 break;
1981 }
1982
1983 case Instruction::DOUBLE_TO_FLOAT: {
1984 Conversion_12x(instruction, Primitive::kPrimDouble, Primitive::kPrimFloat, dex_pc);
1985 break;
1986 }
1987
1988 case Instruction::INT_TO_BYTE: {
1989 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimByte, dex_pc);
1990 break;
1991 }
1992
1993 case Instruction::INT_TO_SHORT: {
1994 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimShort, dex_pc);
1995 break;
1996 }
1997
1998 case Instruction::INT_TO_CHAR: {
1999 Conversion_12x(instruction, Primitive::kPrimInt, Primitive::kPrimChar, dex_pc);
2000 break;
2001 }
2002
2003 case Instruction::ADD_INT: {
2004 Binop_23x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2005 break;
2006 }
2007
2008 case Instruction::ADD_LONG: {
2009 Binop_23x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2010 break;
2011 }
2012
2013 case Instruction::ADD_DOUBLE: {
2014 Binop_23x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2015 break;
2016 }
2017
2018 case Instruction::ADD_FLOAT: {
2019 Binop_23x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2020 break;
2021 }
2022
2023 case Instruction::SUB_INT: {
2024 Binop_23x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2025 break;
2026 }
2027
2028 case Instruction::SUB_LONG: {
2029 Binop_23x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2030 break;
2031 }
2032
2033 case Instruction::SUB_FLOAT: {
2034 Binop_23x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2035 break;
2036 }
2037
2038 case Instruction::SUB_DOUBLE: {
2039 Binop_23x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2040 break;
2041 }
2042
2043 case Instruction::ADD_INT_2ADDR: {
2044 Binop_12x<HAdd>(instruction, Primitive::kPrimInt, dex_pc);
2045 break;
2046 }
2047
2048 case Instruction::MUL_INT: {
2049 Binop_23x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2050 break;
2051 }
2052
2053 case Instruction::MUL_LONG: {
2054 Binop_23x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2055 break;
2056 }
2057
2058 case Instruction::MUL_FLOAT: {
2059 Binop_23x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2060 break;
2061 }
2062
2063 case Instruction::MUL_DOUBLE: {
2064 Binop_23x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2065 break;
2066 }
2067
2068 case Instruction::DIV_INT: {
2069 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2070 dex_pc, Primitive::kPrimInt, false, true);
2071 break;
2072 }
2073
2074 case Instruction::DIV_LONG: {
2075 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2076 dex_pc, Primitive::kPrimLong, false, true);
2077 break;
2078 }
2079
2080 case Instruction::DIV_FLOAT: {
2081 Binop_23x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2082 break;
2083 }
2084
2085 case Instruction::DIV_DOUBLE: {
2086 Binop_23x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2087 break;
2088 }
2089
2090 case Instruction::REM_INT: {
2091 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2092 dex_pc, Primitive::kPrimInt, false, false);
2093 break;
2094 }
2095
2096 case Instruction::REM_LONG: {
2097 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2098 dex_pc, Primitive::kPrimLong, false, false);
2099 break;
2100 }
2101
2102 case Instruction::REM_FLOAT: {
2103 Binop_23x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2104 break;
2105 }
2106
2107 case Instruction::REM_DOUBLE: {
2108 Binop_23x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2109 break;
2110 }
2111
2112 case Instruction::AND_INT: {
2113 Binop_23x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2114 break;
2115 }
2116
2117 case Instruction::AND_LONG: {
2118 Binop_23x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2119 break;
2120 }
2121
2122 case Instruction::SHL_INT: {
2123 Binop_23x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2124 break;
2125 }
2126
2127 case Instruction::SHL_LONG: {
2128 Binop_23x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2129 break;
2130 }
2131
2132 case Instruction::SHR_INT: {
2133 Binop_23x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2134 break;
2135 }
2136
2137 case Instruction::SHR_LONG: {
2138 Binop_23x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2139 break;
2140 }
2141
2142 case Instruction::USHR_INT: {
2143 Binop_23x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2144 break;
2145 }
2146
2147 case Instruction::USHR_LONG: {
2148 Binop_23x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2149 break;
2150 }
2151
2152 case Instruction::OR_INT: {
2153 Binop_23x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2154 break;
2155 }
2156
2157 case Instruction::OR_LONG: {
2158 Binop_23x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2159 break;
2160 }
2161
2162 case Instruction::XOR_INT: {
2163 Binop_23x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2164 break;
2165 }
2166
2167 case Instruction::XOR_LONG: {
2168 Binop_23x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2169 break;
2170 }
2171
2172 case Instruction::ADD_LONG_2ADDR: {
2173 Binop_12x<HAdd>(instruction, Primitive::kPrimLong, dex_pc);
2174 break;
2175 }
2176
2177 case Instruction::ADD_DOUBLE_2ADDR: {
2178 Binop_12x<HAdd>(instruction, Primitive::kPrimDouble, dex_pc);
2179 break;
2180 }
2181
2182 case Instruction::ADD_FLOAT_2ADDR: {
2183 Binop_12x<HAdd>(instruction, Primitive::kPrimFloat, dex_pc);
2184 break;
2185 }
2186
2187 case Instruction::SUB_INT_2ADDR: {
2188 Binop_12x<HSub>(instruction, Primitive::kPrimInt, dex_pc);
2189 break;
2190 }
2191
2192 case Instruction::SUB_LONG_2ADDR: {
2193 Binop_12x<HSub>(instruction, Primitive::kPrimLong, dex_pc);
2194 break;
2195 }
2196
2197 case Instruction::SUB_FLOAT_2ADDR: {
2198 Binop_12x<HSub>(instruction, Primitive::kPrimFloat, dex_pc);
2199 break;
2200 }
2201
2202 case Instruction::SUB_DOUBLE_2ADDR: {
2203 Binop_12x<HSub>(instruction, Primitive::kPrimDouble, dex_pc);
2204 break;
2205 }
2206
2207 case Instruction::MUL_INT_2ADDR: {
2208 Binop_12x<HMul>(instruction, Primitive::kPrimInt, dex_pc);
2209 break;
2210 }
2211
2212 case Instruction::MUL_LONG_2ADDR: {
2213 Binop_12x<HMul>(instruction, Primitive::kPrimLong, dex_pc);
2214 break;
2215 }
2216
2217 case Instruction::MUL_FLOAT_2ADDR: {
2218 Binop_12x<HMul>(instruction, Primitive::kPrimFloat, dex_pc);
2219 break;
2220 }
2221
2222 case Instruction::MUL_DOUBLE_2ADDR: {
2223 Binop_12x<HMul>(instruction, Primitive::kPrimDouble, dex_pc);
2224 break;
2225 }
2226
2227 case Instruction::DIV_INT_2ADDR: {
2228 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2229 dex_pc, Primitive::kPrimInt, false, true);
2230 break;
2231 }
2232
2233 case Instruction::DIV_LONG_2ADDR: {
2234 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2235 dex_pc, Primitive::kPrimLong, false, true);
2236 break;
2237 }
2238
2239 case Instruction::REM_INT_2ADDR: {
2240 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2241 dex_pc, Primitive::kPrimInt, false, false);
2242 break;
2243 }
2244
2245 case Instruction::REM_LONG_2ADDR: {
2246 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegA(), instruction.VRegB(),
2247 dex_pc, Primitive::kPrimLong, false, false);
2248 break;
2249 }
2250
2251 case Instruction::REM_FLOAT_2ADDR: {
2252 Binop_12x<HRem>(instruction, Primitive::kPrimFloat, dex_pc);
2253 break;
2254 }
2255
2256 case Instruction::REM_DOUBLE_2ADDR: {
2257 Binop_12x<HRem>(instruction, Primitive::kPrimDouble, dex_pc);
2258 break;
2259 }
2260
2261 case Instruction::SHL_INT_2ADDR: {
2262 Binop_12x_shift<HShl>(instruction, Primitive::kPrimInt, dex_pc);
2263 break;
2264 }
2265
2266 case Instruction::SHL_LONG_2ADDR: {
2267 Binop_12x_shift<HShl>(instruction, Primitive::kPrimLong, dex_pc);
2268 break;
2269 }
2270
2271 case Instruction::SHR_INT_2ADDR: {
2272 Binop_12x_shift<HShr>(instruction, Primitive::kPrimInt, dex_pc);
2273 break;
2274 }
2275
2276 case Instruction::SHR_LONG_2ADDR: {
2277 Binop_12x_shift<HShr>(instruction, Primitive::kPrimLong, dex_pc);
2278 break;
2279 }
2280
2281 case Instruction::USHR_INT_2ADDR: {
2282 Binop_12x_shift<HUShr>(instruction, Primitive::kPrimInt, dex_pc);
2283 break;
2284 }
2285
2286 case Instruction::USHR_LONG_2ADDR: {
2287 Binop_12x_shift<HUShr>(instruction, Primitive::kPrimLong, dex_pc);
2288 break;
2289 }
2290
2291 case Instruction::DIV_FLOAT_2ADDR: {
2292 Binop_12x<HDiv>(instruction, Primitive::kPrimFloat, dex_pc);
2293 break;
2294 }
2295
2296 case Instruction::DIV_DOUBLE_2ADDR: {
2297 Binop_12x<HDiv>(instruction, Primitive::kPrimDouble, dex_pc);
2298 break;
2299 }
2300
2301 case Instruction::AND_INT_2ADDR: {
2302 Binop_12x<HAnd>(instruction, Primitive::kPrimInt, dex_pc);
2303 break;
2304 }
2305
2306 case Instruction::AND_LONG_2ADDR: {
2307 Binop_12x<HAnd>(instruction, Primitive::kPrimLong, dex_pc);
2308 break;
2309 }
2310
2311 case Instruction::OR_INT_2ADDR: {
2312 Binop_12x<HOr>(instruction, Primitive::kPrimInt, dex_pc);
2313 break;
2314 }
2315
2316 case Instruction::OR_LONG_2ADDR: {
2317 Binop_12x<HOr>(instruction, Primitive::kPrimLong, dex_pc);
2318 break;
2319 }
2320
2321 case Instruction::XOR_INT_2ADDR: {
2322 Binop_12x<HXor>(instruction, Primitive::kPrimInt, dex_pc);
2323 break;
2324 }
2325
2326 case Instruction::XOR_LONG_2ADDR: {
2327 Binop_12x<HXor>(instruction, Primitive::kPrimLong, dex_pc);
2328 break;
2329 }
2330
2331 case Instruction::ADD_INT_LIT16: {
2332 Binop_22s<HAdd>(instruction, false, dex_pc);
2333 break;
2334 }
2335
2336 case Instruction::AND_INT_LIT16: {
2337 Binop_22s<HAnd>(instruction, false, dex_pc);
2338 break;
2339 }
2340
2341 case Instruction::OR_INT_LIT16: {
2342 Binop_22s<HOr>(instruction, false, dex_pc);
2343 break;
2344 }
2345
2346 case Instruction::XOR_INT_LIT16: {
2347 Binop_22s<HXor>(instruction, false, dex_pc);
2348 break;
2349 }
2350
2351 case Instruction::RSUB_INT: {
2352 Binop_22s<HSub>(instruction, true, dex_pc);
2353 break;
2354 }
2355
2356 case Instruction::MUL_INT_LIT16: {
2357 Binop_22s<HMul>(instruction, false, dex_pc);
2358 break;
2359 }
2360
2361 case Instruction::ADD_INT_LIT8: {
2362 Binop_22b<HAdd>(instruction, false, dex_pc);
2363 break;
2364 }
2365
2366 case Instruction::AND_INT_LIT8: {
2367 Binop_22b<HAnd>(instruction, false, dex_pc);
2368 break;
2369 }
2370
2371 case Instruction::OR_INT_LIT8: {
2372 Binop_22b<HOr>(instruction, false, dex_pc);
2373 break;
2374 }
2375
2376 case Instruction::XOR_INT_LIT8: {
2377 Binop_22b<HXor>(instruction, false, dex_pc);
2378 break;
2379 }
2380
2381 case Instruction::RSUB_INT_LIT8: {
2382 Binop_22b<HSub>(instruction, true, dex_pc);
2383 break;
2384 }
2385
2386 case Instruction::MUL_INT_LIT8: {
2387 Binop_22b<HMul>(instruction, false, dex_pc);
2388 break;
2389 }
2390
2391 case Instruction::DIV_INT_LIT16:
2392 case Instruction::DIV_INT_LIT8: {
2393 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2394 dex_pc, Primitive::kPrimInt, true, true);
2395 break;
2396 }
2397
2398 case Instruction::REM_INT_LIT16:
2399 case Instruction::REM_INT_LIT8: {
2400 BuildCheckedDivRem(instruction.VRegA(), instruction.VRegB(), instruction.VRegC(),
2401 dex_pc, Primitive::kPrimInt, true, false);
2402 break;
2403 }
2404
2405 case Instruction::SHL_INT_LIT8: {
2406 Binop_22b<HShl>(instruction, false, dex_pc);
2407 break;
2408 }
2409
2410 case Instruction::SHR_INT_LIT8: {
2411 Binop_22b<HShr>(instruction, false, dex_pc);
2412 break;
2413 }
2414
2415 case Instruction::USHR_INT_LIT8: {
2416 Binop_22b<HUShr>(instruction, false, dex_pc);
2417 break;
2418 }
2419
2420 case Instruction::NEW_INSTANCE: {
2421 if (!BuildNewInstance(instruction.VRegB_21c(), dex_pc)) {
2422 return false;
2423 }
2424 UpdateLocal(instruction.VRegA(), current_block_->GetLastInstruction());
2425 break;
2426 }
2427
2428 case Instruction::NEW_ARRAY: {
2429 uint16_t type_index = instruction.VRegC_22c();
2430 HInstruction* length = LoadLocal(instruction.VRegB_22c(), Primitive::kPrimInt);
2431 bool finalizable;
2432 QuickEntrypointEnum entrypoint = NeedsAccessCheck(type_index, &finalizable)
2433 ? kQuickAllocArrayWithAccessCheck
2434 : kQuickAllocArray;
2435 AppendInstruction(new (arena_) HNewArray(length,
2436 graph_->GetCurrentMethod(),
2437 dex_pc,
2438 type_index,
2439 *dex_compilation_unit_->GetDexFile(),
2440 entrypoint));
2441 UpdateLocal(instruction.VRegA_22c(), current_block_->GetLastInstruction());
2442 break;
2443 }
2444
2445 case Instruction::FILLED_NEW_ARRAY: {
2446 uint32_t number_of_vreg_arguments = instruction.VRegA_35c();
2447 uint32_t type_index = instruction.VRegB_35c();
2448 uint32_t args[5];
2449 instruction.GetVarArgs(args);
2450 BuildFilledNewArray(dex_pc, type_index, number_of_vreg_arguments, false, args, 0);
2451 break;
2452 }
2453
2454 case Instruction::FILLED_NEW_ARRAY_RANGE: {
2455 uint32_t number_of_vreg_arguments = instruction.VRegA_3rc();
2456 uint32_t type_index = instruction.VRegB_3rc();
2457 uint32_t register_index = instruction.VRegC_3rc();
2458 BuildFilledNewArray(
2459 dex_pc, type_index, number_of_vreg_arguments, true, nullptr, register_index);
2460 break;
2461 }
2462
2463 case Instruction::FILL_ARRAY_DATA: {
2464 BuildFillArrayData(instruction, dex_pc);
2465 break;
2466 }
2467
2468 case Instruction::MOVE_RESULT:
2469 case Instruction::MOVE_RESULT_WIDE:
2470 case Instruction::MOVE_RESULT_OBJECT: {
2471 DCHECK(latest_result_ != nullptr);
2472 UpdateLocal(instruction.VRegA(), latest_result_);
2473 latest_result_ = nullptr;
2474 break;
2475 }
2476
2477 case Instruction::CMP_LONG: {
2478 Binop_23x_cmp(instruction, Primitive::kPrimLong, ComparisonBias::kNoBias, dex_pc);
2479 break;
2480 }
2481
2482 case Instruction::CMPG_FLOAT: {
2483 Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kGtBias, dex_pc);
2484 break;
2485 }
2486
2487 case Instruction::CMPG_DOUBLE: {
2488 Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kGtBias, dex_pc);
2489 break;
2490 }
2491
2492 case Instruction::CMPL_FLOAT: {
2493 Binop_23x_cmp(instruction, Primitive::kPrimFloat, ComparisonBias::kLtBias, dex_pc);
2494 break;
2495 }
2496
2497 case Instruction::CMPL_DOUBLE: {
2498 Binop_23x_cmp(instruction, Primitive::kPrimDouble, ComparisonBias::kLtBias, dex_pc);
2499 break;
2500 }
2501
2502 case Instruction::NOP:
2503 break;
2504
2505 case Instruction::IGET:
2506 case Instruction::IGET_QUICK:
2507 case Instruction::IGET_WIDE:
2508 case Instruction::IGET_WIDE_QUICK:
2509 case Instruction::IGET_OBJECT:
2510 case Instruction::IGET_OBJECT_QUICK:
2511 case Instruction::IGET_BOOLEAN:
2512 case Instruction::IGET_BOOLEAN_QUICK:
2513 case Instruction::IGET_BYTE:
2514 case Instruction::IGET_BYTE_QUICK:
2515 case Instruction::IGET_CHAR:
2516 case Instruction::IGET_CHAR_QUICK:
2517 case Instruction::IGET_SHORT:
2518 case Instruction::IGET_SHORT_QUICK: {
2519 if (!BuildInstanceFieldAccess(instruction, dex_pc, false)) {
2520 return false;
2521 }
2522 break;
2523 }
2524
2525 case Instruction::IPUT:
2526 case Instruction::IPUT_QUICK:
2527 case Instruction::IPUT_WIDE:
2528 case Instruction::IPUT_WIDE_QUICK:
2529 case Instruction::IPUT_OBJECT:
2530 case Instruction::IPUT_OBJECT_QUICK:
2531 case Instruction::IPUT_BOOLEAN:
2532 case Instruction::IPUT_BOOLEAN_QUICK:
2533 case Instruction::IPUT_BYTE:
2534 case Instruction::IPUT_BYTE_QUICK:
2535 case Instruction::IPUT_CHAR:
2536 case Instruction::IPUT_CHAR_QUICK:
2537 case Instruction::IPUT_SHORT:
2538 case Instruction::IPUT_SHORT_QUICK: {
2539 if (!BuildInstanceFieldAccess(instruction, dex_pc, true)) {
2540 return false;
2541 }
2542 break;
2543 }
2544
2545 case Instruction::SGET:
2546 case Instruction::SGET_WIDE:
2547 case Instruction::SGET_OBJECT:
2548 case Instruction::SGET_BOOLEAN:
2549 case Instruction::SGET_BYTE:
2550 case Instruction::SGET_CHAR:
2551 case Instruction::SGET_SHORT: {
2552 if (!BuildStaticFieldAccess(instruction, dex_pc, false)) {
2553 return false;
2554 }
2555 break;
2556 }
2557
2558 case Instruction::SPUT:
2559 case Instruction::SPUT_WIDE:
2560 case Instruction::SPUT_OBJECT:
2561 case Instruction::SPUT_BOOLEAN:
2562 case Instruction::SPUT_BYTE:
2563 case Instruction::SPUT_CHAR:
2564 case Instruction::SPUT_SHORT: {
2565 if (!BuildStaticFieldAccess(instruction, dex_pc, true)) {
2566 return false;
2567 }
2568 break;
2569 }
2570
2571#define ARRAY_XX(kind, anticipated_type) \
2572 case Instruction::AGET##kind: { \
2573 BuildArrayAccess(instruction, dex_pc, false, anticipated_type); \
2574 break; \
2575 } \
2576 case Instruction::APUT##kind: { \
2577 BuildArrayAccess(instruction, dex_pc, true, anticipated_type); \
2578 break; \
2579 }
2580
2581 ARRAY_XX(, Primitive::kPrimInt);
2582 ARRAY_XX(_WIDE, Primitive::kPrimLong);
2583 ARRAY_XX(_OBJECT, Primitive::kPrimNot);
2584 ARRAY_XX(_BOOLEAN, Primitive::kPrimBoolean);
2585 ARRAY_XX(_BYTE, Primitive::kPrimByte);
2586 ARRAY_XX(_CHAR, Primitive::kPrimChar);
2587 ARRAY_XX(_SHORT, Primitive::kPrimShort);
2588
2589 case Instruction::ARRAY_LENGTH: {
David Brazdilc120bbe2016-04-22 16:57:00 +01002590 HInstruction* object = LoadNullCheckedLocal(instruction.VRegB_12x(), dex_pc);
David Brazdildee58d62016-04-07 09:54:26 +00002591 AppendInstruction(new (arena_) HArrayLength(object, dex_pc));
2592 UpdateLocal(instruction.VRegA_12x(), current_block_->GetLastInstruction());
2593 break;
2594 }
2595
2596 case Instruction::CONST_STRING: {
2597 uint32_t string_index = instruction.VRegB_21c();
2598 AppendInstruction(
2599 new (arena_) HLoadString(graph_->GetCurrentMethod(), string_index, *dex_file_, dex_pc));
2600 UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction());
2601 break;
2602 }
2603
2604 case Instruction::CONST_STRING_JUMBO: {
2605 uint32_t string_index = instruction.VRegB_31c();
2606 AppendInstruction(
2607 new (arena_) HLoadString(graph_->GetCurrentMethod(), string_index, *dex_file_, dex_pc));
2608 UpdateLocal(instruction.VRegA_31c(), current_block_->GetLastInstruction());
2609 break;
2610 }
2611
2612 case Instruction::CONST_CLASS: {
2613 uint16_t type_index = instruction.VRegB_21c();
David Brazdildee58d62016-04-07 09:54:26 +00002614 // `CanAccessTypeWithoutChecks` will tell whether the method being
2615 // built is trying to access its own class, so that the generated
2616 // code can optimize for this case. However, the optimization does not
2617 // work for inlining, so we use `IsOutermostCompilingClass` instead.
Vladimir Marko3cd50df2016-04-13 19:29:26 +01002618 ScopedObjectAccess soa(Thread::Current());
2619 Handle<mirror::DexCache> dex_cache = dex_compilation_unit_->GetDexCache();
David Brazdildee58d62016-04-07 09:54:26 +00002620 bool can_access = compiler_driver_->CanAccessTypeWithoutChecks(
Vladimir Marko3cd50df2016-04-13 19:29:26 +01002621 dex_compilation_unit_->GetDexMethodIndex(), dex_cache, type_index);
David Brazdildee58d62016-04-07 09:54:26 +00002622 AppendInstruction(new (arena_) HLoadClass(
2623 graph_->GetCurrentMethod(),
2624 type_index,
2625 *dex_file_,
2626 IsOutermostCompilingClass(type_index),
2627 dex_pc,
2628 !can_access,
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002629 /* is_in_dex_cache */ false));
David Brazdildee58d62016-04-07 09:54:26 +00002630 UpdateLocal(instruction.VRegA_21c(), current_block_->GetLastInstruction());
2631 break;
2632 }
2633
2634 case Instruction::MOVE_EXCEPTION: {
2635 AppendInstruction(new (arena_) HLoadException(dex_pc));
2636 UpdateLocal(instruction.VRegA_11x(), current_block_->GetLastInstruction());
2637 AppendInstruction(new (arena_) HClearException(dex_pc));
2638 break;
2639 }
2640
2641 case Instruction::THROW: {
2642 HInstruction* exception = LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot);
2643 AppendInstruction(new (arena_) HThrow(exception, dex_pc));
2644 // We finished building this block. Set the current block to null to avoid
2645 // adding dead instructions to it.
2646 current_block_ = nullptr;
2647 break;
2648 }
2649
2650 case Instruction::INSTANCE_OF: {
2651 uint8_t destination = instruction.VRegA_22c();
2652 uint8_t reference = instruction.VRegB_22c();
2653 uint16_t type_index = instruction.VRegC_22c();
2654 BuildTypeCheck(instruction, destination, reference, type_index, dex_pc);
2655 break;
2656 }
2657
2658 case Instruction::CHECK_CAST: {
2659 uint8_t reference = instruction.VRegA_21c();
2660 uint16_t type_index = instruction.VRegB_21c();
2661 BuildTypeCheck(instruction, -1, reference, type_index, dex_pc);
2662 break;
2663 }
2664
2665 case Instruction::MONITOR_ENTER: {
2666 AppendInstruction(new (arena_) HMonitorOperation(
2667 LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot),
2668 HMonitorOperation::OperationKind::kEnter,
2669 dex_pc));
2670 break;
2671 }
2672
2673 case Instruction::MONITOR_EXIT: {
2674 AppendInstruction(new (arena_) HMonitorOperation(
2675 LoadLocal(instruction.VRegA_11x(), Primitive::kPrimNot),
2676 HMonitorOperation::OperationKind::kExit,
2677 dex_pc));
2678 break;
2679 }
2680
2681 case Instruction::SPARSE_SWITCH:
2682 case Instruction::PACKED_SWITCH: {
2683 BuildSwitch(instruction, dex_pc);
2684 break;
2685 }
2686
2687 default:
2688 VLOG(compiler) << "Did not compile "
2689 << PrettyMethod(dex_compilation_unit_->GetDexMethodIndex(), *dex_file_)
2690 << " because of unhandled instruction "
2691 << instruction.Name();
2692 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnhandledInstruction);
2693 return false;
2694 }
2695 return true;
2696} // NOLINT(readability/fn_size)
2697
2698} // namespace art