blob: 499514de97de5216904561ba632781d73e00e85c [file] [log] [blame]
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001/*
2 * Copyright (C) 2014 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
Andreas Gampe53c913b2014-08-12 23:19:23 -070017#include "optimizing_compiler.h"
18
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010019#include <fstream>
David Srbecky5cc349f2015-12-18 15:04:48 +000020#include <memory>
Andreas Gampea0d81af2016-10-27 12:04:57 -070021#include <sstream>
22
Nicolas Geoffray787c3072014-03-17 10:20:19 +000023#include <stdint.h>
24
Aart Bikd1c40452016-03-02 16:06:13 -080025#ifdef ART_ENABLE_CODEGEN_arm
Vladimir Markob4536b72015-11-24 13:45:23 +000026#include "dex_cache_array_fixups_arm.h"
27#endif
28
29#ifdef ART_ENABLE_CODEGEN_arm64
Alexandre Rames44b9cf92015-08-19 15:39:06 +010030#include "instruction_simplifier_arm64.h"
31#endif
32
Alexey Frunzee3fb2452016-05-10 16:08:05 -070033#ifdef ART_ENABLE_CODEGEN_mips
34#include "dex_cache_array_fixups_mips.h"
35#include "pc_relative_fixups_mips.h"
36#endif
37
Mark Mendell0616ae02015-04-17 12:49:27 -040038#ifdef ART_ENABLE_CODEGEN_x86
Vladimir Marko0f7dca42015-11-02 14:36:43 +000039#include "pc_relative_fixups_x86.h"
Mark Mendell0616ae02015-04-17 12:49:27 -040040#endif
41
Mark Mendellee8d9712016-07-12 11:13:15 -040042#if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
43#include "x86_memory_gen.h"
44#endif
45
Mathieu Chartiere401d142015-04-22 13:56:20 -070046#include "art_method-inl.h"
Mathieu Chartierb666f482015-02-18 14:33:14 -080047#include "base/arena_allocator.h"
Vladimir Markof9f64412015-09-02 14:05:49 +010048#include "base/arena_containers.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000049#include "base/dumpable.h"
Vladimir Markoc90d7c72015-10-06 17:30:45 +000050#include "base/macros.h"
Andreas Gampea0d81af2016-10-27 12:04:57 -070051#include "base/mutex.h"
David Brazdil5e8b1372015-01-23 14:39:08 +000052#include "base/timing_logger.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070053#include "bounds_check_elimination.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000054#include "builder.h"
55#include "code_generator.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000056#include "compiled_method.h"
Andreas Gampe53c913b2014-08-12 23:19:23 -070057#include "compiler.h"
Roland Levillain75be2832014-10-17 17:02:00 +010058#include "constant_folding.h"
59#include "dead_code_elimination.h"
David Srbeckyc5bfa972016-02-05 15:49:10 +000060#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000061#include "debug/method_debug_info.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010062#include "dex/verification_results.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000063#include "dex/verified_method.h"
Nicolas Geoffray9523a3e2015-07-17 11:51:28 +000064#include "driver/compiler_driver-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000065#include "driver/compiler_options.h"
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +000066#include "driver/dex_compilation_unit.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000067#include "elf_writer_quick.h"
David Brazdil69ba7b72015-06-23 18:27:30 +010068#include "graph_checker.h"
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010069#include "graph_visualizer.h"
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +010070#include "gvn.h"
Aart Bik22af3be2015-09-10 12:50:58 -070071#include "induction_var_analysis.h"
Nicolas Geoffraye53798a2014-12-01 10:31:54 +000072#include "inliner.h"
Nicolas Geoffray3c049742014-09-24 18:10:46 +010073#include "instruction_simplifier.h"
Artem Udovichenko4a0dad62016-01-26 12:28:31 +030074#include "instruction_simplifier_arm.h"
Andreas Gampe71fb52f2014-12-29 17:43:08 -080075#include "intrinsics.h"
David Srbecky5cc349f2015-12-18 15:04:48 +000076#include "jit/debugger_interface.h"
Nicolas Geoffraya4f81542016-03-08 16:57:48 +000077#include "jit/jit.h"
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +000078#include "jit/jit_code_cache.h"
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +000079#include "jni/quick/jni_compiler.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000080#include "licm.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070081#include "load_store_elimination.h"
Aart Bik281c6812016-08-26 11:31:48 -070082#include "loop_optimization.h"
Nicolas Geoffray787c3072014-03-17 10:20:19 +000083#include "nodes.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000084#include "oat_quick_method_header.h"
Nicolas Geoffray26a25ef2014-09-30 13:54:09 +010085#include "prepare_for_register_allocation.h"
Calin Juravlef1c6d9e2015-04-13 18:42:21 +010086#include "reference_type_propagation.h"
Matthew Gharritye9288852016-07-14 14:08:16 -070087#include "register_allocator_linear_scan.h"
David Brazdil74eb1b22015-12-14 11:44:01 +000088#include "select_generator.h"
Vladimir Markodc151b22015-10-15 18:02:30 +010089#include "sharpening.h"
Nicolas Geoffray827eedb2015-01-26 15:18:36 +000090#include "side_effects_analysis.h"
Nicolas Geoffray31596742014-11-24 15:28:45 +000091#include "ssa_builder.h"
Nicolas Geoffray804d0932014-05-02 08:46:00 +010092#include "ssa_liveness_analysis.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000093#include "ssa_phi_elimination.h"
David Srbeckyc6b4dd82015-04-07 20:32:43 +010094#include "utils/assembler.h"
Calin Juravle175dc732015-08-25 15:42:32 +010095#include "verifier/method_verifier.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000096
97namespace art {
98
Vladimir Marko3a40bf22016-03-22 16:26:33 +000099static constexpr size_t kArenaAllocatorMemoryReportThreshold = 8 * MB;
100
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700101static constexpr const char* kPassNameSeparator = "$";
102
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000103/**
104 * Used by the code generator, to allocate the code in a vector.
105 */
106class CodeVectorAllocator FINAL : public CodeAllocator {
107 public:
Vladimir Markof9f64412015-09-02 14:05:49 +0100108 explicit CodeVectorAllocator(ArenaAllocator* arena)
109 : memory_(arena->Adapter(kArenaAllocCodeBuffer)),
110 size_(0) {}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000111
112 virtual uint8_t* Allocate(size_t size) {
113 size_ = size;
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000114 memory_.resize(size);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000115 return &memory_[0];
116 }
117
118 size_t GetSize() const { return size_; }
Vladimir Markof9f64412015-09-02 14:05:49 +0100119 const ArenaVector<uint8_t>& GetMemory() const { return memory_; }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000120
121 private:
Vladimir Markof9f64412015-09-02 14:05:49 +0100122 ArenaVector<uint8_t> memory_;
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000123 size_t size_;
124
125 DISALLOW_COPY_AND_ASSIGN(CodeVectorAllocator);
126};
127
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100128/**
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100129 * Filter to apply to the visualizer. Methods whose name contain that filter will
David Brazdilee690a32014-12-01 17:04:16 +0000130 * be dumped.
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100131 */
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700132static constexpr const char kStringFilter[] = "";
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100133
David Brazdil69ba7b72015-06-23 18:27:30 +0100134class PassScope;
David Brazdil809658e2015-02-05 11:34:02 +0000135
David Brazdil69ba7b72015-06-23 18:27:30 +0100136class PassObserver : public ValueObject {
David Brazdil5e8b1372015-01-23 14:39:08 +0000137 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100138 PassObserver(HGraph* graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100139 CodeGenerator* codegen,
140 std::ostream* visualizer_output,
Andreas Gampea0d81af2016-10-27 12:04:57 -0700141 CompilerDriver* compiler_driver,
142 Mutex& dump_mutex)
David Brazdil69ba7b72015-06-23 18:27:30 +0100143 : graph_(graph),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000144 cached_method_name_(),
David Brazdil809658e2015-02-05 11:34:02 +0000145 timing_logger_enabled_(compiler_driver->GetDumpPasses()),
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000146 timing_logger_(timing_logger_enabled_ ? GetMethodName() : "", true, true),
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100147 disasm_info_(graph->GetArena()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700148 visualizer_oss_(),
149 visualizer_output_(visualizer_output),
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000150 visualizer_enabled_(!compiler_driver->GetCompilerOptions().GetDumpCfgFileName().empty()),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700151 visualizer_(&visualizer_oss_, graph, *codegen),
152 visualizer_dump_mutex_(dump_mutex),
David Brazdil69ba7b72015-06-23 18:27:30 +0100153 graph_in_bad_state_(false) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700154 if (timing_logger_enabled_ || visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000155 if (!IsVerboseMethod(compiler_driver, GetMethodName())) {
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700156 timing_logger_enabled_ = visualizer_enabled_ = false;
157 }
158 if (visualizer_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000159 visualizer_.PrintHeader(GetMethodName());
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700160 codegen->SetDisassemblyInformation(&disasm_info_);
161 }
David Brazdil62e074f2015-04-07 18:09:37 +0100162 }
David Brazdil5e8b1372015-01-23 14:39:08 +0000163 }
164
David Brazdil69ba7b72015-06-23 18:27:30 +0100165 ~PassObserver() {
David Brazdil5e8b1372015-01-23 14:39:08 +0000166 if (timing_logger_enabled_) {
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000167 LOG(INFO) << "TIMINGS " << GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000168 LOG(INFO) << Dumpable<TimingLogger>(timing_logger_);
169 }
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000170 DCHECK(visualizer_oss_.str().empty());
David Brazdil5e8b1372015-01-23 14:39:08 +0000171 }
172
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000173 void DumpDisassembly() REQUIRES(!visualizer_dump_mutex_) {
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100174 if (visualizer_enabled_) {
175 visualizer_.DumpGraphWithDisassembly();
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000176 FlushVisualizer();
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100177 }
178 }
179
David Brazdil69ba7b72015-06-23 18:27:30 +0100180 void SetGraphInBadState() { graph_in_bad_state_ = true; }
181
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000182 const char* GetMethodName() {
183 // PrettyMethod() is expensive, so we delay calling it until we actually have to.
184 if (cached_method_name_.empty()) {
David Sehr709b0702016-10-13 09:12:37 -0700185 cached_method_name_ = graph_->GetDexFile().PrettyMethod(graph_->GetMethodIdx());
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000186 }
187 return cached_method_name_.c_str();
188 }
189
David Brazdil5e8b1372015-01-23 14:39:08 +0000190 private:
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000191 void StartPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
Wojciech Staszkiewicze7060702016-08-16 17:31:19 -0700192 VLOG(compiler) << "Starting pass: " << pass_name;
David Brazdil809658e2015-02-05 11:34:02 +0000193 // Dump graph first, then start timer.
194 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100195 visualizer_.DumpGraph(pass_name, /* is_after_pass */ false, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000196 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000197 }
198 if (timing_logger_enabled_) {
199 timing_logger_.StartTiming(pass_name);
200 }
201 }
202
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000203 void FlushVisualizer() REQUIRES(!visualizer_dump_mutex_) {
204 MutexLock mu(Thread::Current(), visualizer_dump_mutex_);
205 *visualizer_output_ << visualizer_oss_.str();
206 visualizer_output_->flush();
207 visualizer_oss_.str("");
208 visualizer_oss_.clear();
209 }
210
211 void EndPass(const char* pass_name) REQUIRES(!visualizer_dump_mutex_) {
David Brazdil809658e2015-02-05 11:34:02 +0000212 // Pause timer first, then dump graph.
213 if (timing_logger_enabled_) {
214 timing_logger_.EndTiming();
215 }
216 if (visualizer_enabled_) {
David Brazdilffee3d32015-07-06 11:48:53 +0100217 visualizer_.DumpGraph(pass_name, /* is_after_pass */ true, graph_in_bad_state_);
Nicolas Geoffray00c141a2016-11-10 15:19:15 +0000218 FlushVisualizer();
David Brazdil809658e2015-02-05 11:34:02 +0000219 }
David Brazdil69ba7b72015-06-23 18:27:30 +0100220
221 // Validate the HGraph if running in debug mode.
222 if (kIsDebugBuild) {
223 if (!graph_in_bad_state_) {
David Brazdilbadd8262016-02-02 16:28:56 +0000224 GraphChecker checker(graph_);
225 checker.Run();
226 if (!checker.IsValid()) {
227 LOG(FATAL) << "Error after " << pass_name << ": " << Dumpable<GraphChecker>(checker);
David Brazdil69ba7b72015-06-23 18:27:30 +0100228 }
229 }
230 }
David Brazdil809658e2015-02-05 11:34:02 +0000231 }
232
Andreas Gampe53fcd0f2015-07-22 12:10:13 -0700233 static bool IsVerboseMethod(CompilerDriver* compiler_driver, const char* method_name) {
234 // Test an exact match to --verbose-methods. If verbose-methods is set, this overrides an
235 // empty kStringFilter matching all methods.
236 if (compiler_driver->GetCompilerOptions().HasVerboseMethods()) {
237 return compiler_driver->GetCompilerOptions().IsVerboseMethod(method_name);
238 }
239
240 // Test the kStringFilter sub-string. constexpr helper variable to silence unreachable-code
241 // warning when the string is empty.
242 constexpr bool kStringFilterEmpty = arraysize(kStringFilter) <= 1;
243 if (kStringFilterEmpty || strstr(method_name, kStringFilter) != nullptr) {
244 return true;
245 }
246
247 return false;
248 }
249
David Brazdil69ba7b72015-06-23 18:27:30 +0100250 HGraph* const graph_;
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000251
252 std::string cached_method_name_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000253
254 bool timing_logger_enabled_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000255 TimingLogger timing_logger_;
256
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100257 DisassemblyInformation disasm_info_;
258
Andreas Gampea0d81af2016-10-27 12:04:57 -0700259 std::ostringstream visualizer_oss_;
260 std::ostream* visualizer_output_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000261 bool visualizer_enabled_;
262 HGraphVisualizer visualizer_;
Andreas Gampea0d81af2016-10-27 12:04:57 -0700263 Mutex& visualizer_dump_mutex_;
David Brazdil5e8b1372015-01-23 14:39:08 +0000264
David Brazdil69ba7b72015-06-23 18:27:30 +0100265 // Flag to be set by the compiler if the pass failed and the graph is not
266 // expected to validate.
267 bool graph_in_bad_state_;
David Brazdil809658e2015-02-05 11:34:02 +0000268
David Brazdil69ba7b72015-06-23 18:27:30 +0100269 friend PassScope;
270
271 DISALLOW_COPY_AND_ASSIGN(PassObserver);
David Brazdil5e8b1372015-01-23 14:39:08 +0000272};
273
David Brazdil69ba7b72015-06-23 18:27:30 +0100274class PassScope : public ValueObject {
David Brazdil809658e2015-02-05 11:34:02 +0000275 public:
David Brazdil69ba7b72015-06-23 18:27:30 +0100276 PassScope(const char *pass_name, PassObserver* pass_observer)
David Brazdil809658e2015-02-05 11:34:02 +0000277 : pass_name_(pass_name),
David Brazdil69ba7b72015-06-23 18:27:30 +0100278 pass_observer_(pass_observer) {
279 pass_observer_->StartPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000280 }
281
David Brazdil69ba7b72015-06-23 18:27:30 +0100282 ~PassScope() {
283 pass_observer_->EndPass(pass_name_);
David Brazdil809658e2015-02-05 11:34:02 +0000284 }
285
286 private:
287 const char* const pass_name_;
David Brazdil69ba7b72015-06-23 18:27:30 +0100288 PassObserver* const pass_observer_;
David Brazdil809658e2015-02-05 11:34:02 +0000289};
290
Andreas Gampe53c913b2014-08-12 23:19:23 -0700291class OptimizingCompiler FINAL : public Compiler {
292 public:
293 explicit OptimizingCompiler(CompilerDriver* driver);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700294 ~OptimizingCompiler() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700295
Vladimir Markodf739842016-03-23 16:59:07 +0000296 bool CanCompileMethod(uint32_t method_idx, const DexFile& dex_file) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700297
298 CompiledMethod* Compile(const DexFile::CodeItem* code_item,
299 uint32_t access_flags,
300 InvokeType invoke_type,
301 uint16_t class_def_idx,
302 uint32_t method_idx,
303 jobject class_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -0700304 const DexFile& dex_file,
305 Handle<mirror::DexCache> dex_cache) const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700306
Andreas Gampe53c913b2014-08-12 23:19:23 -0700307 CompiledMethod* JniCompile(uint32_t access_flags,
308 uint32_t method_idx,
Igor Murashkin9d4b6da2016-07-29 09:51:58 -0700309 const DexFile& dex_file,
310 JniOptimizationFlags optimization_flags) const OVERRIDE {
311 return ArtQuickJniCompileMethod(GetCompilerDriver(),
312 access_flags,
313 method_idx,
314 dex_file,
315 optimization_flags);
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000316 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700317
Mathieu Chartiere401d142015-04-22 13:56:20 -0700318 uintptr_t GetEntryPointOf(ArtMethod* method) const OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700319 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000320 return reinterpret_cast<uintptr_t>(method->GetEntryPointFromQuickCompiledCodePtrSize(
321 InstructionSetPointerSize(GetCompilerDriver()->GetInstructionSet())));
322 }
Andreas Gampe53c913b2014-08-12 23:19:23 -0700323
David Brazdilee690a32014-12-01 17:04:16 +0000324 void Init() OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700325
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000326 void UnInit() const OVERRIDE;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700327
Calin Juravle2be39e02015-04-21 13:56:34 +0100328 void MaybeRecordStat(MethodCompilationStat compilation_stat) const {
329 if (compilation_stats_.get() != nullptr) {
330 compilation_stats_->RecordStat(compilation_stat);
331 }
332 }
333
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000334 bool JitCompile(Thread* self, jit::JitCodeCache* code_cache, ArtMethod* method, bool osr)
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000335 OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700336 REQUIRES_SHARED(Locks::mutator_lock_);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000337
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700338 private:
339 void RunOptimizations(HGraph* graph,
340 CodeGenerator* codegen,
341 CompilerDriver* driver,
342 const DexCompilationUnit& dex_compilation_unit,
343 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700344 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700345
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700346 void RunOptimizations(HOptimization* optimizations[],
347 size_t length,
348 PassObserver* pass_observer) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700349
Andreas Gampe53c913b2014-08-12 23:19:23 -0700350 private:
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000351 // Create a 'CompiledMethod' for an optimized graph.
David Brazdil58282f42016-01-14 12:45:10 +0000352 CompiledMethod* Emit(ArenaAllocator* arena,
353 CodeVectorAllocator* code_allocator,
354 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000355 CompilerDriver* driver,
356 const DexFile::CodeItem* item) const;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000357
358 // Try compiling a method and return the code generator used for
359 // compiling it.
360 // This method:
361 // 1) Builds the graph. Returns null if it failed to build it.
David Brazdil58282f42016-01-14 12:45:10 +0000362 // 2) Transforms the graph to SSA. Returns null if it failed.
363 // 3) Runs optimizations on the graph, including register allocator.
364 // 4) Generates code with the `code_allocator` provided.
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000365 CodeGenerator* TryCompile(ArenaAllocator* arena,
366 CodeVectorAllocator* code_allocator,
367 const DexFile::CodeItem* code_item,
368 uint32_t access_flags,
369 InvokeType invoke_type,
370 uint16_t class_def_idx,
371 uint32_t method_idx,
372 jobject class_loader,
373 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000374 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000375 ArtMethod* method,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000376 bool osr) const;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000377
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700378 void MaybeRunInliner(HGraph* graph,
379 CodeGenerator* codegen,
380 CompilerDriver* driver,
381 const DexCompilationUnit& dex_compilation_unit,
382 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700383 VariableSizedHandleScope* handles) const;
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700384
385 void RunArchOptimizations(InstructionSet instruction_set,
386 HGraph* graph,
387 CodeGenerator* codegen,
388 PassObserver* pass_observer) const;
389
Calin Juravle2be39e02015-04-21 13:56:34 +0100390 std::unique_ptr<OptimizingCompilerStats> compilation_stats_;
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100391
Andreas Gampe53c913b2014-08-12 23:19:23 -0700392 std::unique_ptr<std::ostream> visualizer_output_;
393
Andreas Gampea0d81af2016-10-27 12:04:57 -0700394 mutable Mutex dump_mutex_; // To synchronize visualizer writing.
395
Andreas Gampe53c913b2014-08-12 23:19:23 -0700396 DISALLOW_COPY_AND_ASSIGN(OptimizingCompiler);
397};
398
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100399static const int kMaximumCompilationTimeBeforeWarning = 100; /* ms */
400
401OptimizingCompiler::OptimizingCompiler(CompilerDriver* driver)
Andreas Gampea0d81af2016-10-27 12:04:57 -0700402 : Compiler(driver, kMaximumCompilationTimeBeforeWarning),
403 dump_mutex_("Visualizer dump lock") {}
David Brazdilee690a32014-12-01 17:04:16 +0000404
405void OptimizingCompiler::Init() {
406 // Enable C1visualizer output. Must be done in Init() because the compiler
407 // driver is not fully initialized when passed to the compiler's constructor.
408 CompilerDriver* driver = GetCompilerDriver();
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000409 const std::string cfg_file_name = driver->GetCompilerOptions().GetDumpCfgFileName();
David Brazdil866c0312015-01-13 21:21:31 +0000410 if (!cfg_file_name.empty()) {
Calin Juravle87000a92015-08-24 15:34:44 +0100411 std::ios_base::openmode cfg_file_mode =
Nicolas Geoffrayc903b6a2016-01-18 12:56:06 +0000412 driver->GetCompilerOptions().GetDumpCfgAppend() ? std::ofstream::app : std::ofstream::out;
Calin Juravle87000a92015-08-24 15:34:44 +0100413 visualizer_output_.reset(new std::ofstream(cfg_file_name, cfg_file_mode));
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100414 }
Calin Juravle2be39e02015-04-21 13:56:34 +0100415 if (driver->GetDumpStats()) {
416 compilation_stats_.reset(new OptimizingCompilerStats());
417 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100418}
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000419
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000420void OptimizingCompiler::UnInit() const {
Nicolas Geoffray216eaa22015-03-17 17:09:30 +0000421}
422
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100423OptimizingCompiler::~OptimizingCompiler() {
Calin Juravle2be39e02015-04-21 13:56:34 +0100424 if (compilation_stats_.get() != nullptr) {
425 compilation_stats_->Log();
426 }
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100427}
428
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000429bool OptimizingCompiler::CanCompileMethod(uint32_t method_idx ATTRIBUTE_UNUSED,
Vladimir Markodf739842016-03-23 16:59:07 +0000430 const DexFile& dex_file ATTRIBUTE_UNUSED) const {
Nicolas Geoffraye2dc6fa2014-11-17 12:55:12 +0000431 return true;
Andreas Gampe53c913b2014-08-12 23:19:23 -0700432}
433
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000434static bool IsInstructionSetSupported(InstructionSet instruction_set) {
Calin Juravlecff8cc72015-10-09 12:03:24 +0100435 return (instruction_set == kArm && !kArm32QuickCodeUseSoftFloat)
436 || instruction_set == kArm64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000437 || (instruction_set == kThumb2 && !kArm32QuickCodeUseSoftFloat)
Goran Jakovljevicf652cec2015-08-25 16:11:42 +0200438 || instruction_set == kMips
Alexey Frunze4dda3372015-06-01 18:31:49 -0700439 || instruction_set == kMips64
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000440 || instruction_set == kX86
441 || instruction_set == kX86_64;
442}
443
Roland Levillain22ccc3a2015-11-24 13:10:05 +0000444// Read barrier are supported on ARM, ARM64, x86 and x86-64 at the moment.
Roland Levillain0d5a2812015-11-13 10:07:31 +0000445// TODO: Add support for other architectures and remove this function
446static bool InstructionSetSupportsReadBarrier(InstructionSet instruction_set) {
Roland Levillain22ccc3a2015-11-24 13:10:05 +0000447 return instruction_set == kArm64
448 || instruction_set == kThumb2
Roland Levillain3b359c72015-11-17 19:35:12 +0000449 || instruction_set == kX86
Roland Levillain0d5a2812015-11-13 10:07:31 +0000450 || instruction_set == kX86_64;
451}
452
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700453// Strip pass name suffix to get optimization name.
454static std::string ConvertPassNameToOptimizationName(const std::string& pass_name) {
455 size_t pos = pass_name.find(kPassNameSeparator);
456 return pos == std::string::npos ? pass_name : pass_name.substr(0, pos);
457}
458
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700459static HOptimization* BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700460 const std::string& pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700461 ArenaAllocator* arena,
462 HGraph* graph,
463 OptimizingCompilerStats* stats,
464 CodeGenerator* codegen,
465 CompilerDriver* driver,
466 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700467 VariableSizedHandleScope* handles,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700468 SideEffectsAnalysis* most_recent_side_effects,
469 HInductionVarAnalysis* most_recent_induction) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700470 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700471 if (opt_name == BoundsCheckElimination::kBoundsCheckEliminationPassName) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700472 CHECK(most_recent_side_effects != nullptr && most_recent_induction != nullptr);
473 return new (arena) BoundsCheckElimination(graph,
474 *most_recent_side_effects,
475 most_recent_induction);
476 } else if (opt_name == GVNOptimization::kGlobalValueNumberingPassName) {
477 CHECK(most_recent_side_effects != nullptr);
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700478 return new (arena) GVNOptimization(graph, *most_recent_side_effects, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700479 } else if (opt_name == HConstantFolding::kConstantFoldingPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700480 return new (arena) HConstantFolding(graph, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700481 } else if (opt_name == HDeadCodeElimination::kDeadCodeEliminationPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700482 return new (arena) HDeadCodeElimination(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700483 } else if (opt_name == HInliner::kInlinerPassName) {
484 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
485 return new (arena) HInliner(graph, // outer_graph
486 graph, // outermost_graph
487 codegen,
488 dex_compilation_unit, // outer_compilation_unit
489 dex_compilation_unit, // outermost_compilation_unit
490 driver,
491 handles,
492 stats,
493 number_of_dex_registers,
494 /* depth */ 0);
495 } else if (opt_name == HSharpening::kSharpeningPassName) {
496 return new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver);
497 } else if (opt_name == HSelectGenerator::kSelectGeneratorPassName) {
498 return new (arena) HSelectGenerator(graph, stats);
499 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
500 return new (arena) HInductionVarAnalysis(graph);
501 } else if (opt_name == InstructionSimplifier::kInstructionSimplifierPassName) {
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700502 return new (arena) InstructionSimplifier(graph, stats, pass_name.c_str());
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700503 } else if (opt_name == IntrinsicsRecognizer::kIntrinsicsRecognizerPassName) {
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100504 return new (arena) IntrinsicsRecognizer(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700505 } else if (opt_name == LICM::kLoopInvariantCodeMotionPassName) {
506 CHECK(most_recent_side_effects != nullptr);
507 return new (arena) LICM(graph, *most_recent_side_effects, stats);
508 } else if (opt_name == LoadStoreElimination::kLoadStoreEliminationPassName) {
509 CHECK(most_recent_side_effects != nullptr);
510 return new (arena) LoadStoreElimination(graph, *most_recent_side_effects);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700511 } else if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
512 return new (arena) SideEffectsAnalysis(graph);
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100513 } else if (opt_name == HLoopOptimization::kLoopOptimizationPassName) {
514 return new (arena) HLoopOptimization(graph, most_recent_induction);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700515#ifdef ART_ENABLE_CODEGEN_arm
516 } else if (opt_name == arm::DexCacheArrayFixups::kDexCacheArrayFixupsArmPassName) {
Vladimir Marko68c981f2016-08-26 13:13:33 +0100517 return new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700518 } else if (opt_name == arm::InstructionSimplifierArm::kInstructionSimplifierArmPassName) {
519 return new (arena) arm::InstructionSimplifierArm(graph, stats);
520#endif
521#ifdef ART_ENABLE_CODEGEN_arm64
522 } else if (opt_name == arm64::InstructionSimplifierArm64::kInstructionSimplifierArm64PassName) {
523 return new (arena) arm64::InstructionSimplifierArm64(graph, stats);
524#endif
525#ifdef ART_ENABLE_CODEGEN_mips
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700526 } else if (opt_name == mips::DexCacheArrayFixups::kDexCacheArrayFixupsMipsPassName) {
527 return new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
528 } else if (opt_name == mips::PcRelativeFixups::kPcRelativeFixupsMipsPassName) {
529 return new (arena) mips::PcRelativeFixups(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700530#endif
531#ifdef ART_ENABLE_CODEGEN_x86
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700532 } else if (opt_name == x86::PcRelativeFixups::kPcRelativeFixupsX86PassName) {
533 return new (arena) x86::PcRelativeFixups(graph, codegen, stats);
534 } else if (opt_name == x86::X86MemoryOperandGeneration::kX86MemoryOperandGenerationPassName) {
535 return new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700536#endif
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700537 }
538 return nullptr;
539}
540
541static ArenaVector<HOptimization*> BuildOptimizations(
542 const std::vector<std::string>& pass_names,
543 ArenaAllocator* arena,
544 HGraph* graph,
545 OptimizingCompilerStats* stats,
546 CodeGenerator* codegen,
547 CompilerDriver* driver,
548 const DexCompilationUnit& dex_compilation_unit,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700549 VariableSizedHandleScope* handles) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700550 // Few HOptimizations constructors require SideEffectsAnalysis or HInductionVarAnalysis
551 // instances. This method assumes that each of them expects the nearest instance preceeding it
552 // in the pass name list.
553 SideEffectsAnalysis* most_recent_side_effects = nullptr;
554 HInductionVarAnalysis* most_recent_induction = nullptr;
555 ArenaVector<HOptimization*> ret(arena->Adapter());
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700556 for (const std::string& pass_name : pass_names) {
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700557 HOptimization* opt = BuildOptimization(
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700558 pass_name,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700559 arena,
560 graph,
561 stats,
562 codegen,
563 driver,
564 dex_compilation_unit,
565 handles,
566 most_recent_side_effects,
567 most_recent_induction);
568 CHECK(opt != nullptr) << "Couldn't build optimization: \"" << pass_name << "\"";
569 ret.push_back(opt);
570
Wojciech Staszkiewiczb6a128322016-08-16 16:33:00 -0700571 std::string opt_name = ConvertPassNameToOptimizationName(pass_name);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700572 if (opt_name == SideEffectsAnalysis::kSideEffectsAnalysisPassName) {
573 most_recent_side_effects = down_cast<SideEffectsAnalysis*>(opt);
574 } else if (opt_name == HInductionVarAnalysis::kInductionPassName) {
575 most_recent_induction = down_cast<HInductionVarAnalysis*>(opt);
576 }
577 }
578 return ret;
579}
580
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700581void OptimizingCompiler::RunOptimizations(HOptimization* optimizations[],
582 size_t length,
583 PassObserver* pass_observer) const {
Calin Juravle10e244f2015-01-26 18:54:32 +0000584 for (size_t i = 0; i < length; ++i) {
David Brazdil69ba7b72015-06-23 18:27:30 +0100585 PassScope scope(optimizations[i]->GetPassName(), pass_observer);
586 optimizations[i]->Run();
Calin Juravle10e244f2015-01-26 18:54:32 +0000587 }
588}
589
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700590void OptimizingCompiler::MaybeRunInliner(HGraph* graph,
591 CodeGenerator* codegen,
592 CompilerDriver* driver,
593 const DexCompilationUnit& dex_compilation_unit,
594 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700595 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700596 OptimizingCompilerStats* stats = compilation_stats_.get();
Calin Juravleec748352015-07-29 13:52:12 +0100597 const CompilerOptions& compiler_options = driver->GetCompilerOptions();
598 bool should_inline = (compiler_options.GetInlineDepthLimit() > 0)
599 && (compiler_options.GetInlineMaxCodeUnits() > 0);
600 if (!should_inline) {
601 return;
602 }
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000603 size_t number_of_dex_registers = dex_compilation_unit.GetCodeItem()->registers_size_;
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000604 HInliner* inliner = new (graph->GetArena()) HInliner(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700605 graph, // outer_graph
606 graph, // outermost_graph
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000607 codegen,
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700608 dex_compilation_unit, // outer_compilation_unit
609 dex_compilation_unit, // outermost_compilation_unit
Nicolas Geoffray5949fa02015-12-18 10:57:10 +0000610 driver,
611 handles,
612 stats,
613 number_of_dex_registers,
614 /* depth */ 0);
Calin Juravlecdfed3d2015-10-26 14:05:01 +0000615 HOptimization* optimizations[] = { inliner };
Calin Juravleec748352015-07-29 13:52:12 +0100616
617 RunOptimizations(optimizations, arraysize(optimizations), pass_observer);
618}
619
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700620void OptimizingCompiler::RunArchOptimizations(InstructionSet instruction_set,
621 HGraph* graph,
622 CodeGenerator* codegen,
623 PassObserver* pass_observer) const {
Wojciech Staszkiewicze28c7d02016-08-17 19:15:51 -0700624 UNUSED(codegen); // To avoid compilation error when compiling for svelte
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700625 OptimizingCompilerStats* stats = compilation_stats_.get();
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100626 ArenaAllocator* arena = graph->GetArena();
627 switch (instruction_set) {
Artem Serov2bbc9532016-10-21 11:51:50 +0100628#if defined(ART_ENABLE_CODEGEN_arm)
Vladimir Markob4536b72015-11-24 13:45:23 +0000629 case kThumb2:
630 case kArm: {
Artem Serov2bbc9532016-10-21 11:51:50 +0100631#ifndef ART_USE_VIXL_ARM_BACKEND
Vladimir Marko68c981f2016-08-26 13:13:33 +0100632 arm::DexCacheArrayFixups* fixups =
633 new (arena) arm::DexCacheArrayFixups(graph, codegen, stats);
Artem Serov2bbc9532016-10-21 11:51:50 +0100634#endif
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300635 arm::InstructionSimplifierArm* simplifier =
636 new (arena) arm::InstructionSimplifierArm(graph, stats);
Artem Serov328429f2016-07-06 16:23:04 +0100637 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700638 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Vladimir Markob4536b72015-11-24 13:45:23 +0000639 HOptimization* arm_optimizations[] = {
Artem Udovichenko4a0dad62016-01-26 12:28:31 +0300640 simplifier,
Artem Serov328429f2016-07-06 16:23:04 +0100641 side_effects,
642 gvn,
Artem Serov2bbc9532016-10-21 11:51:50 +0100643#ifndef ART_USE_VIXL_ARM_BACKEND
Nicolas Geoffray6b5afdd2016-01-22 09:31:52 +0000644 fixups
Artem Serov2bbc9532016-10-21 11:51:50 +0100645#endif
Vladimir Markob4536b72015-11-24 13:45:23 +0000646 };
647 RunOptimizations(arm_optimizations, arraysize(arm_optimizations), pass_observer);
648 break;
649 }
650#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100651#ifdef ART_ENABLE_CODEGEN_arm64
652 case kArm64: {
653 arm64::InstructionSimplifierArm64* simplifier =
654 new (arena) arm64::InstructionSimplifierArm64(graph, stats);
655 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700656 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects, "GVN$after_arch");
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100657 HOptimization* arm64_optimizations[] = {
658 simplifier,
659 side_effects,
660 gvn
661 };
662 RunOptimizations(arm64_optimizations, arraysize(arm64_optimizations), pass_observer);
663 break;
664 }
665#endif
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700666#ifdef ART_ENABLE_CODEGEN_mips
667 case kMips: {
668 mips::PcRelativeFixups* pc_relative_fixups =
669 new (arena) mips::PcRelativeFixups(graph, codegen, stats);
670 mips::DexCacheArrayFixups* dex_cache_array_fixups =
Alexey Frunze06a46c42016-07-19 15:00:40 -0700671 new (arena) mips::DexCacheArrayFixups(graph, codegen, stats);
Alexey Frunzee3fb2452016-05-10 16:08:05 -0700672 HOptimization* mips_optimizations[] = {
673 pc_relative_fixups,
674 dex_cache_array_fixups
675 };
676 RunOptimizations(mips_optimizations, arraysize(mips_optimizations), pass_observer);
677 break;
678 }
679#endif
Mark Mendell0616ae02015-04-17 12:49:27 -0400680#ifdef ART_ENABLE_CODEGEN_x86
681 case kX86: {
Aart Bikd1c40452016-03-02 16:06:13 -0800682 x86::PcRelativeFixups* pc_relative_fixups =
683 new (arena) x86::PcRelativeFixups(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400684 x86::X86MemoryOperandGeneration* memory_gen =
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700685 new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendell0616ae02015-04-17 12:49:27 -0400686 HOptimization* x86_optimizations[] = {
Mark Mendellee8d9712016-07-12 11:13:15 -0400687 pc_relative_fixups,
688 memory_gen
Mark Mendell0616ae02015-04-17 12:49:27 -0400689 };
690 RunOptimizations(x86_optimizations, arraysize(x86_optimizations), pass_observer);
691 break;
692 }
693#endif
Mark Mendellee8d9712016-07-12 11:13:15 -0400694#ifdef ART_ENABLE_CODEGEN_x86_64
695 case kX86_64: {
696 x86::X86MemoryOperandGeneration* memory_gen =
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700697 new (arena) x86::X86MemoryOperandGeneration(graph, codegen, stats);
Mark Mendellee8d9712016-07-12 11:13:15 -0400698 HOptimization* x86_64_optimizations[] = {
699 memory_gen
700 };
701 RunOptimizations(x86_64_optimizations, arraysize(x86_64_optimizations), pass_observer);
702 break;
703 }
704#endif
Alexandre Rames44b9cf92015-08-19 15:39:06 +0100705 default:
706 break;
707 }
708}
709
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000710NO_INLINE // Avoid increasing caller's frame size by large stack-allocated objects.
711static void AllocateRegisters(HGraph* graph,
712 CodeGenerator* codegen,
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700713 PassObserver* pass_observer,
714 RegisterAllocator::Strategy strategy) {
Mingyao Yang700347e2016-03-02 14:59:32 -0800715 {
716 PassScope scope(PrepareForRegisterAllocation::kPrepareForRegisterAllocationPassName,
717 pass_observer);
718 PrepareForRegisterAllocation(graph).Run();
719 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000720 SsaLivenessAnalysis liveness(graph, codegen);
721 {
722 PassScope scope(SsaLivenessAnalysis::kLivenessPassName, pass_observer);
723 liveness.Analyze();
724 }
725 {
726 PassScope scope(RegisterAllocator::kRegisterAllocatorPassName, pass_observer);
Matthew Gharrity2cd05b72016-08-03 16:57:37 -0700727 RegisterAllocator::Create(graph->GetArena(), codegen, liveness, strategy)->AllocateRegisters();
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000728 }
729}
730
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700731void OptimizingCompiler::RunOptimizations(HGraph* graph,
732 CodeGenerator* codegen,
733 CompilerDriver* driver,
734 const DexCompilationUnit& dex_compilation_unit,
735 PassObserver* pass_observer,
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700736 VariableSizedHandleScope* handles) const {
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700737 OptimizingCompilerStats* stats = compilation_stats_.get();
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100738 ArenaAllocator* arena = graph->GetArena();
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700739 if (driver->GetCompilerOptions().GetPassesToRun() != nullptr) {
740 ArenaVector<HOptimization*> optimizations = BuildOptimizations(
741 *driver->GetCompilerOptions().GetPassesToRun(),
742 arena,
743 graph,
744 stats,
745 codegen,
746 driver,
747 dex_compilation_unit,
748 handles);
749 RunOptimizations(&optimizations[0], optimizations.size(), pass_observer);
750 return;
751 }
752
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100753 HDeadCodeElimination* dce1 = new (arena) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700754 graph, stats, "dead_code_elimination$initial");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100755 HDeadCodeElimination* dce2 = new (arena) HDeadCodeElimination(
Aart Bik2767f4b2016-10-28 15:03:53 -0700756 graph, stats, "dead_code_elimination$after_inlining");
757 HDeadCodeElimination* dce3 = new (arena) HDeadCodeElimination(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700758 graph, stats, "dead_code_elimination$final");
Andreas Gampeca620d72016-11-08 08:09:33 -0800759 HConstantFolding* fold1 = new (arena) HConstantFolding(graph, "constant_folding");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100760 InstructionSimplifier* simplify1 = new (arena) InstructionSimplifier(graph, stats);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +0100761 HSelectGenerator* select_generator = new (arena) HSelectGenerator(graph, stats);
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700762 HConstantFolding* fold2 = new (arena) HConstantFolding(
763 graph, "constant_folding$after_inlining");
764 HConstantFolding* fold3 = new (arena) HConstantFolding(graph, "constant_folding$after_bce");
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100765 SideEffectsAnalysis* side_effects = new (arena) SideEffectsAnalysis(graph);
766 GVNOptimization* gvn = new (arena) GVNOptimization(graph, *side_effects);
Jean-Philippe Halimi38e9e802016-02-18 16:42:03 +0100767 LICM* licm = new (arena) LICM(graph, *side_effects, stats);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700768 LoadStoreElimination* lse = new (arena) LoadStoreElimination(graph, *side_effects);
Aart Bik22af3be2015-09-10 12:50:58 -0700769 HInductionVarAnalysis* induction = new (arena) HInductionVarAnalysis(graph);
Aart Bik4a342772015-11-30 10:17:46 -0800770 BoundsCheckElimination* bce = new (arena) BoundsCheckElimination(graph, *side_effects, induction);
Aart Bik281c6812016-08-26 11:31:48 -0700771 HLoopOptimization* loop = new (arena) HLoopOptimization(graph, induction);
Vladimir Markodc151b22015-10-15 18:02:30 +0100772 HSharpening* sharpening = new (arena) HSharpening(graph, codegen, dex_compilation_unit, driver);
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100773 InstructionSimplifier* simplify2 = new (arena) InstructionSimplifier(
Aart Bik639cc8c2016-10-18 13:03:31 -0700774 graph, stats, "instruction_simplifier$after_inlining");
David Brazdil4833f5a2015-12-16 10:37:39 +0000775 InstructionSimplifier* simplify3 = new (arena) InstructionSimplifier(
Aart Bik639cc8c2016-10-18 13:03:31 -0700776 graph, stats, "instruction_simplifier$after_bce");
777 InstructionSimplifier* simplify4 = new (arena) InstructionSimplifier(
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -0700778 graph, stats, "instruction_simplifier$before_codegen");
Nicolas Geoffray762869d2016-07-15 15:28:35 +0100779 IntrinsicsRecognizer* intrinsics = new (arena) IntrinsicsRecognizer(graph, stats);
Andreas Gampe71fb52f2014-12-29 17:43:08 -0800780
Calin Juravleec748352015-07-29 13:52:12 +0100781 HOptimization* optimizations1[] = {
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100782 intrinsics,
David Brazdil4833f5a2015-12-16 10:37:39 +0000783 sharpening,
Vladimir Markoa3a3c592015-06-12 14:30:53 +0100784 fold1,
785 simplify1,
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100786 dce1,
Calin Juravleec748352015-07-29 13:52:12 +0100787 };
Calin Juravleec748352015-07-29 13:52:12 +0100788 RunOptimizations(optimizations1, arraysize(optimizations1), pass_observer);
789
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700790 MaybeRunInliner(graph, codegen, driver, dex_compilation_unit, pass_observer, handles);
David Brazdil95177982015-10-30 12:56:58 -0500791
David Brazdil8993caf2015-12-07 10:04:40 +0000792 HOptimization* optimizations2[] = {
David Brazdil74eb1b22015-12-14 11:44:01 +0000793 // SelectGenerator depends on the InstructionSimplifier removing
David Brazdil8993caf2015-12-07 10:04:40 +0000794 // redundant suspend checks to recognize empty blocks.
David Brazdil74eb1b22015-12-14 11:44:01 +0000795 select_generator,
David Brazdil8993caf2015-12-07 10:04:40 +0000796 fold2, // TODO: if we don't inline we can also skip fold2.
Aart Bik639cc8c2016-10-18 13:03:31 -0700797 simplify2,
Aart Bik2767f4b2016-10-28 15:03:53 -0700798 dce2,
David Brazdil8993caf2015-12-07 10:04:40 +0000799 side_effects,
800 gvn,
801 licm,
802 induction,
803 bce,
Aart Bik281c6812016-08-26 11:31:48 -0700804 loop,
David Brazdil8993caf2015-12-07 10:04:40 +0000805 fold3, // evaluates code generated by dynamic bce
Aart Bik639cc8c2016-10-18 13:03:31 -0700806 simplify3,
David Brazdil8993caf2015-12-07 10:04:40 +0000807 lse,
Aart Bik2767f4b2016-10-28 15:03:53 -0700808 dce3,
David Brazdil8993caf2015-12-07 10:04:40 +0000809 // The codegen has a few assumptions that only the instruction simplifier
810 // can satisfy. For example, the code generator does not expect to see a
811 // HTypeConversion from a type to the same type.
Aart Bik639cc8c2016-10-18 13:03:31 -0700812 simplify4,
David Brazdil8993caf2015-12-07 10:04:40 +0000813 };
814 RunOptimizations(optimizations2, arraysize(optimizations2), pass_observer);
David Brazdilbbd733e2015-08-18 17:48:17 +0100815
Wojciech Staszkiewiczf5fb0902016-07-22 13:33:11 -0700816 RunArchOptimizations(driver->GetInstructionSet(), graph, codegen, pass_observer);
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000817}
818
Vladimir Marko58155012015-08-19 12:49:41 +0000819static ArenaVector<LinkerPatch> EmitAndSortLinkerPatches(CodeGenerator* codegen) {
820 ArenaVector<LinkerPatch> linker_patches(codegen->GetGraph()->GetArena()->Adapter());
821 codegen->EmitLinkerPatches(&linker_patches);
822
823 // Sort patches by literal offset. Required for .oat_patches encoding.
824 std::sort(linker_patches.begin(), linker_patches.end(),
825 [](const LinkerPatch& lhs, const LinkerPatch& rhs) {
826 return lhs.LiteralOffset() < rhs.LiteralOffset();
827 });
828
829 return linker_patches;
830}
831
David Brazdil58282f42016-01-14 12:45:10 +0000832CompiledMethod* OptimizingCompiler::Emit(ArenaAllocator* arena,
833 CodeVectorAllocator* code_allocator,
834 CodeGenerator* codegen,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000835 CompilerDriver* compiler_driver,
836 const DexFile::CodeItem* code_item) const {
Vladimir Marko58155012015-08-19 12:49:41 +0000837 ArenaVector<LinkerPatch> linker_patches = EmitAndSortLinkerPatches(codegen);
Vladimir Markof9f64412015-09-02 14:05:49 +0100838 ArenaVector<uint8_t> stack_map(arena->Adapter(kArenaAllocStackMaps));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000839 stack_map.resize(codegen->ComputeStackMapsSize());
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000840 codegen->BuildStackMaps(MemoryRegion(stack_map.data(), stack_map.size()), *code_item);
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000841
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100842 CompiledMethod* compiled_method = CompiledMethod::SwapAllocCompiledMethod(
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000843 compiler_driver,
844 codegen->GetInstructionSet(),
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000845 ArrayRef<const uint8_t>(code_allocator->GetMemory()),
Roland Levillainaa9b7c42015-02-17 15:40:09 +0000846 // Follow Quick's behavior and set the frame size to zero if it is
847 // considered "empty" (see the definition of
848 // art::CodeGenerator::HasEmptyFrame).
849 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000850 codegen->GetCoreSpillMask(),
Nicolas Geoffrayd97dc402015-01-22 13:50:01 +0000851 codegen->GetFpuSpillMask(),
David Srbeckyf71b3ad2015-12-08 15:05:08 +0000852 ArrayRef<const SrcMapElem>(),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100853 ArrayRef<const uint8_t>(stack_map),
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100854 ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data()),
Vladimir Marko58155012015-08-19 12:49:41 +0000855 ArrayRef<const LinkerPatch>(linker_patches));
Mathieu Chartiered150002015-08-28 11:16:54 -0700856
Alexandre Rameseb7b7392015-06-19 14:47:01 +0100857 return compiled_method;
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000858}
859
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000860CodeGenerator* OptimizingCompiler::TryCompile(ArenaAllocator* arena,
861 CodeVectorAllocator* code_allocator,
862 const DexFile::CodeItem* code_item,
863 uint32_t access_flags,
864 InvokeType invoke_type,
865 uint16_t class_def_idx,
866 uint32_t method_idx,
867 jobject class_loader,
868 const DexFile& dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000869 Handle<mirror::DexCache> dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000870 ArtMethod* method,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000871 bool osr) const {
Calin Juravle2be39e02015-04-21 13:56:34 +0100872 MaybeRecordStat(MethodCompilationStat::kAttemptCompilation);
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000873 CompilerDriver* compiler_driver = GetCompilerDriver();
874 InstructionSet instruction_set = compiler_driver->GetInstructionSet();
Calin Juravlecff8cc72015-10-09 12:03:24 +0100875
Roland Levillain3b359c72015-11-17 19:35:12 +0000876 // Always use the Thumb-2 assembler: some runtime functionality
877 // (like implicit stack overflow checks) assume Thumb-2.
Artem Serovba6b6792016-08-15 14:22:07 +0100878 DCHECK_NE(instruction_set, kArm);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100879
880 // Do not attempt to compile on architectures we do not support.
Nicolas Geoffray1ba0f592014-10-27 15:14:55 +0000881 if (!IsInstructionSetSupported(instruction_set)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100882 MaybeRecordStat(MethodCompilationStat::kNotCompiledUnsupportedIsa);
Nicolas Geoffray8fb5ce32014-07-04 09:43:26 +0100883 return nullptr;
884 }
885
Roland Levillain0d5a2812015-11-13 10:07:31 +0000886 // When read barriers are enabled, do not attempt to compile for
887 // instruction sets that have no read barrier support.
888 if (kEmitCompilerReadBarrier && !InstructionSetSupportsReadBarrier(instruction_set)) {
889 return nullptr;
890 }
891
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000892 if (Compiler::IsPathologicalCase(*code_item, method_idx, dex_file)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100893 MaybeRecordStat(MethodCompilationStat::kNotCompiledPathological);
Nicolas Geoffrayb5f62b32014-10-30 10:58:41 +0000894 return nullptr;
895 }
896
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000897 // Implementation of the space filter: do not compile a code item whose size in
Nicolas Geoffray432bf3d2015-07-17 11:11:09 +0100898 // code units is bigger than 128.
899 static constexpr size_t kSpaceFilterOptimizingThreshold = 128;
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000900 const CompilerOptions& compiler_options = compiler_driver->GetCompilerOptions();
Andreas Gampe29d38e72016-03-23 15:31:51 +0000901 if ((compiler_options.GetCompilerFilter() == CompilerFilter::kSpace)
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000902 && (code_item->insns_size_in_code_units_ > kSpaceFilterOptimizingThreshold)) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100903 MaybeRecordStat(MethodCompilationStat::kNotCompiledSpaceFilter);
Nicolas Geoffray36540cb2015-03-23 14:45:53 +0000904 return nullptr;
905 }
906
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100907 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000908 DexCompilationUnit dex_compilation_unit(
Vladimir Markodf739842016-03-23 16:59:07 +0000909 class_loader,
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100910 class_linker,
Vladimir Markodf739842016-03-23 16:59:07 +0000911 dex_file,
912 code_item,
913 class_def_idx,
914 method_idx,
915 access_flags,
916 /* verified_method */ nullptr,
917 dex_cache);
Nicolas Geoffray92cf83e2014-03-18 17:59:20 +0000918
Calin Juravle3cd4fc82015-05-14 15:15:42 +0100919 bool requires_barrier = dex_compilation_unit.IsConstructor()
920 && compiler_driver->RequiresConstructorBarrier(Thread::Current(),
921 dex_compilation_unit.GetDexFile(),
922 dex_compilation_unit.GetClassDefIndex());
David Brazdilbadd8262016-02-02 16:28:56 +0000923
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +0000924 HGraph* graph = new (arena) HGraph(
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000925 arena,
926 dex_file,
927 method_idx,
928 requires_barrier,
929 compiler_driver->GetInstructionSet(),
930 kInvalidInvokeType,
931 compiler_driver->GetCompilerOptions().GetDebuggable(),
932 osr);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000933
David Brazdilbadd8262016-02-02 16:28:56 +0000934 const uint8_t* interpreter_metadata = nullptr;
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000935 if (method == nullptr) {
David Brazdilbadd8262016-02-02 16:28:56 +0000936 ScopedObjectAccess soa(Thread::Current());
937 StackHandleScope<1> hs(soa.Self());
938 Handle<mirror::ClassLoader> loader(hs.NewHandle(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700939 soa.Decode<mirror::ClassLoader>(class_loader)));
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000940 method = compiler_driver->ResolveMethod(
David Brazdilbadd8262016-02-02 16:28:56 +0000941 soa, dex_cache, loader, &dex_compilation_unit, method_idx, invoke_type);
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000942 }
943 // For AOT compilation, we may not get a method, for example if its class is erroneous.
944 // JIT should always have a method.
945 DCHECK(Runtime::Current()->IsAotCompiler() || method != nullptr);
946 if (method != nullptr) {
947 graph->SetArtMethod(method);
948 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +0100949 interpreter_metadata = method->GetQuickenedInfo(class_linker->GetImagePointerSize());
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +0000950 uint16_t type_index = method->GetDeclaringClass()->GetDexTypeIndex();
951
952 // Update the dex cache if the type is not in it yet. Note that under AOT,
953 // the verifier must have set it, but under JIT, there's no guarantee, as we
954 // don't necessarily run the verifier.
955 // The compiler and the compiler driver assume the compiling class is
956 // in the dex cache.
957 if (dex_cache->GetResolvedType(type_index) == nullptr) {
958 dex_cache->SetResolvedType(type_index, method->GetDeclaringClass());
Nicolas Geoffray12abcbd2016-06-06 15:51:58 +0000959 }
David Brazdilbadd8262016-02-02 16:28:56 +0000960 }
961
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000962 std::unique_ptr<CodeGenerator> codegen(
Calin Juravlecd6dffe2015-01-08 17:35:35 +0000963 CodeGenerator::Create(graph,
964 instruction_set,
965 *compiler_driver->GetInstructionSetFeatures(),
Calin Juravle2ae48182016-03-16 14:05:09 +0000966 compiler_driver->GetCompilerOptions(),
967 compilation_stats_.get()));
Nicolas Geoffray12df9eb2015-01-09 14:53:50 +0000968 if (codegen.get() == nullptr) {
Calin Juravle2be39e02015-04-21 13:56:34 +0100969 MaybeRecordStat(MethodCompilationStat::kNotCompiledNoCodegen);
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000970 return nullptr;
971 }
David Srbeckyc6b4dd82015-04-07 20:32:43 +0100972 codegen->GetAssembler()->cfi().SetEnabled(
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000973 compiler_driver->GetCompilerOptions().GenerateAnyDebugInfo());
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000974
David Brazdil69ba7b72015-06-23 18:27:30 +0100975 PassObserver pass_observer(graph,
David Brazdil69ba7b72015-06-23 18:27:30 +0100976 codegen.get(),
977 visualizer_output_.get(),
Andreas Gampea0d81af2016-10-27 12:04:57 -0700978 compiler_driver,
979 dump_mutex_);
David Brazdil5e8b1372015-01-23 14:39:08 +0000980
Vladimir Marko0d1caa52015-11-20 13:02:22 +0000981 VLOG(compiler) << "Building " << pass_observer.GetMethodName();
David Brazdil5e8b1372015-01-23 14:39:08 +0000982
David Brazdil809658e2015-02-05 11:34:02 +0000983 {
David Brazdilbadd8262016-02-02 16:28:56 +0000984 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartiere8a3c572016-10-11 16:52:17 -0700985 VariableSizedHandleScope handles(soa.Self());
David Brazdilbadd8262016-02-02 16:28:56 +0000986 // Do not hold `mutator_lock_` between optimizations.
987 ScopedThreadSuspension sts(soa.Self(), kNative);
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100988
David Brazdilbadd8262016-02-02 16:28:56 +0000989 {
990 PassScope scope(HGraphBuilder::kBuilderPassName, &pass_observer);
991 HGraphBuilder builder(graph,
992 &dex_compilation_unit,
993 &dex_compilation_unit,
994 &dex_file,
David Brazdil86ea7ee2016-02-16 09:26:07 +0000995 *code_item,
David Brazdilbadd8262016-02-02 16:28:56 +0000996 compiler_driver,
997 compilation_stats_.get(),
998 interpreter_metadata,
David Brazdildee58d62016-04-07 09:54:26 +0000999 dex_cache,
1000 &handles);
1001 GraphAnalysisResult result = builder.BuildGraph();
David Brazdilbadd8262016-02-02 16:28:56 +00001002 if (result != kAnalysisSuccess) {
1003 switch (result) {
David Brazdil86ea7ee2016-02-16 09:26:07 +00001004 case kAnalysisSkipped:
1005 MaybeRecordStat(MethodCompilationStat::kNotCompiledSkipped);
1006 break;
David Brazdilbadd8262016-02-02 16:28:56 +00001007 case kAnalysisInvalidBytecode:
David Brazdil86ea7ee2016-02-16 09:26:07 +00001008 MaybeRecordStat(MethodCompilationStat::kNotCompiledInvalidBytecode);
David Brazdilbadd8262016-02-02 16:28:56 +00001009 break;
1010 case kAnalysisFailThrowCatchLoop:
1011 MaybeRecordStat(MethodCompilationStat::kNotCompiledThrowCatchLoop);
1012 break;
1013 case kAnalysisFailAmbiguousArrayOp:
1014 MaybeRecordStat(MethodCompilationStat::kNotCompiledAmbiguousArrayOp);
1015 break;
1016 case kAnalysisSuccess:
1017 UNREACHABLE();
1018 }
1019 pass_observer.SetGraphInBadState();
1020 return nullptr;
David Brazdil809658e2015-02-05 11:34:02 +00001021 }
Nicolas Geoffrayf5370122014-12-02 11:51:19 +00001022 }
David Brazdil58282f42016-01-14 12:45:10 +00001023
David Brazdilbadd8262016-02-02 16:28:56 +00001024 RunOptimizations(graph,
1025 codegen.get(),
1026 compiler_driver,
David Brazdilbadd8262016-02-02 16:28:56 +00001027 dex_compilation_unit,
1028 &pass_observer,
1029 &handles);
1030
Wojciech Staszkiewicz5319d3c2016-08-01 17:48:59 -07001031 RegisterAllocator::Strategy regalloc_strategy =
1032 compiler_options.GetRegisterAllocationStrategy();
1033 AllocateRegisters(graph, codegen.get(), &pass_observer, regalloc_strategy);
1034
David Brazdilbadd8262016-02-02 16:28:56 +00001035 codegen->Compile(code_allocator);
1036 pass_observer.DumpDisassembly();
1037 }
Vladimir Markof9f64412015-09-02 14:05:49 +01001038
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001039 return codegen.release();
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001040}
1041
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001042CompiledMethod* OptimizingCompiler::Compile(const DexFile::CodeItem* code_item,
1043 uint32_t access_flags,
1044 InvokeType invoke_type,
1045 uint16_t class_def_idx,
1046 uint32_t method_idx,
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001047 jobject jclass_loader,
Mathieu Chartier736b5602015-09-02 14:54:11 -07001048 const DexFile& dex_file,
1049 Handle<mirror::DexCache> dex_cache) const {
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001050 CompilerDriver* compiler_driver = GetCompilerDriver();
1051 CompiledMethod* method = nullptr;
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001052 DCHECK(Runtime::Current()->IsAotCompiler());
1053 const VerifiedMethod* verified_method = compiler_driver->GetVerifiedMethod(&dex_file, method_idx);
1054 DCHECK(!verified_method->HasRuntimeThrow());
1055 if (compiler_driver->IsMethodVerifiedWithoutFailures(method_idx, class_def_idx, dex_file)
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001056 || verifier::MethodVerifier::CanCompilerHandleVerificationFailure(
1057 verified_method->GetEncounteredVerificationFailures())) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001058 ArenaAllocator arena(Runtime::Current()->GetArenaPool());
1059 CodeVectorAllocator code_allocator(&arena);
1060 std::unique_ptr<CodeGenerator> codegen(
1061 TryCompile(&arena,
1062 &code_allocator,
1063 code_item,
1064 access_flags,
1065 invoke_type,
1066 class_def_idx,
1067 method_idx,
1068 jclass_loader,
1069 dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001070 dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001071 nullptr,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001072 /* osr */ false));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001073 if (codegen.get() != nullptr) {
Calin Juravlead543382015-11-19 17:26:29 +00001074 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001075 method = Emit(&arena, &code_allocator, codegen.get(), compiler_driver, code_item);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001076
1077 if (kArenaAllocatorCountAllocations) {
1078 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1079 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001080 LOG(INFO) << dex_file.PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001081 }
1082 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001083 }
Nicolas Geoffray0c3c2662015-10-15 13:53:04 +01001084 } else {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001085 if (compiler_driver->GetCompilerOptions().VerifyAtRuntime()) {
1086 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerifyAtRuntime);
1087 } else {
Calin Juravlead543382015-11-19 17:26:29 +00001088 MaybeRecordStat(MethodCompilationStat::kNotCompiledVerificationError);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001089 }
Calin Juravlef1c6d9e2015-04-13 18:42:21 +01001090 }
1091
Calin Juravlecff8cc72015-10-09 12:03:24 +01001092 if (kIsDebugBuild &&
1093 IsCompilingWithCoreImage() &&
Roland Levillain0d5a2812015-11-13 10:07:31 +00001094 IsInstructionSetSupported(compiler_driver->GetInstructionSet()) &&
1095 (!kEmitCompilerReadBarrier ||
1096 InstructionSetSupportsReadBarrier(compiler_driver->GetInstructionSet()))) {
1097 // For testing purposes, we put a special marker on method names
1098 // that should be compiled with this compiler (when the the
1099 // instruction set is supported -- and has support for read
1100 // barriers, if they are enabled). This makes sure we're not
1101 // regressing.
David Sehr709b0702016-10-13 09:12:37 -07001102 std::string method_name = dex_file.PrettyMethod(method_idx);
Calin Juravle09b1d6f2015-10-07 12:08:54 +01001103 bool shouldCompile = method_name.find("$opt$") != std::string::npos;
1104 DCHECK((method != nullptr) || !shouldCompile) << "Didn't compile " << method_name;
1105 }
1106
Nicolas Geoffray12be74e2015-03-30 13:29:08 +01001107 return method;
Nicolas Geoffray216eaa22015-03-17 17:09:30 +00001108}
1109
Andreas Gampe53c913b2014-08-12 23:19:23 -07001110Compiler* CreateOptimizingCompiler(CompilerDriver* driver) {
1111 return new OptimizingCompiler(driver);
1112}
1113
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001114bool IsCompilingWithCoreImage() {
1115 const std::string& image = Runtime::Current()->GetImageLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001116 // TODO: This is under-approximating...
1117 if (EndsWith(image, "core.art") || EndsWith(image, "core-optimizing.art")) {
1118 return true;
1119 }
1120 return false;
Nicolas Geoffray335005e2015-06-25 10:01:47 +01001121}
1122
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001123bool OptimizingCompiler::JitCompile(Thread* self,
1124 jit::JitCodeCache* code_cache,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001125 ArtMethod* method,
1126 bool osr) {
Nicolas Geoffray3395fbc2016-11-14 12:40:52 +00001127 StackHandleScope<2> hs(self);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001128 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(
1129 method->GetDeclaringClass()->GetClassLoader()));
1130 Handle<mirror::DexCache> dex_cache(hs.NewHandle(method->GetDexCache()));
Nicolas Geoffray250a3782016-04-20 16:27:53 +01001131 DCHECK(method->IsCompilable());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001132
1133 jobject jclass_loader = class_loader.ToJObject();
1134 const DexFile* dex_file = method->GetDexFile();
1135 const uint16_t class_def_idx = method->GetClassDefIndex();
1136 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1137 const uint32_t method_idx = method->GetDexMethodIndex();
1138 const uint32_t access_flags = method->GetAccessFlags();
1139 const InvokeType invoke_type = method->GetInvokeType();
1140
Nicolas Geoffray25e04562016-03-01 13:17:58 +00001141 ArenaAllocator arena(Runtime::Current()->GetJitArenaPool());
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001142 CodeVectorAllocator code_allocator(&arena);
1143 std::unique_ptr<CodeGenerator> codegen;
1144 {
1145 // Go to native so that we don't block GC during compilation.
1146 ScopedThreadSuspension sts(self, kNative);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001147 codegen.reset(
1148 TryCompile(&arena,
1149 &code_allocator,
1150 code_item,
1151 access_flags,
1152 invoke_type,
1153 class_def_idx,
1154 method_idx,
1155 jclass_loader,
1156 *dex_file,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001157 dex_cache,
Nicolas Geoffray3aaf9642016-06-07 14:14:37 +00001158 method,
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001159 osr));
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001160 if (codegen.get() == nullptr) {
1161 return false;
1162 }
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001163
1164 if (kArenaAllocatorCountAllocations) {
1165 if (arena.BytesAllocated() > kArenaAllocatorMemoryReportThreshold) {
1166 MemStats mem_stats(arena.GetMemStats());
David Sehr709b0702016-10-13 09:12:37 -07001167 LOG(INFO) << dex_file->PrettyMethod(method_idx) << " " << Dumpable<MemStats>(mem_stats);
Vladimir Marko3a40bf22016-03-22 16:26:33 +00001168 }
1169 }
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001170 }
1171
1172 size_t stack_map_size = codegen->ComputeStackMapsSize();
Nicolas Geoffray3395fbc2016-11-14 12:40:52 +00001173 uint8_t* stack_map_data = code_cache->ReserveData(self, stack_map_size, method);
1174 if (stack_map_data == nullptr) {
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001175 return false;
1176 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01001177 MaybeRecordStat(MethodCompilationStat::kCompiled);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001178 codegen->BuildStackMaps(MemoryRegion(stack_map_data, stack_map_size), *code_item);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001179 const void* code = code_cache->CommitCode(
1180 self,
1181 method,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001182 stack_map_data,
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001183 codegen->HasEmptyFrame() ? 0 : codegen->GetFrameSize(),
1184 codegen->GetCoreSpillMask(),
1185 codegen->GetFpuSpillMask(),
1186 code_allocator.GetMemory().data(),
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00001187 code_allocator.GetSize(),
Nicolas Geoffray3395fbc2016-11-14 12:40:52 +00001188 osr);
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001189
1190 if (code == nullptr) {
1191 code_cache->ClearData(self, stack_map_data);
1192 return false;
1193 }
1194
David Srbecky91cc06c2016-03-07 16:13:58 +00001195 const CompilerOptions& compiler_options = GetCompilerDriver()->GetCompilerOptions();
1196 if (compiler_options.GetGenerateDebugInfo()) {
David Srbecky5cc349f2015-12-18 15:04:48 +00001197 const auto* method_header = reinterpret_cast<const OatQuickMethodHeader*>(code);
1198 const uintptr_t code_address = reinterpret_cast<uintptr_t>(method_header->GetCode());
David Srbecky09c2a6b2016-03-11 17:11:44 +00001199 debug::MethodDebugInfo info = debug::MethodDebugInfo();
1200 info.trampoline_name = nullptr;
David Srbecky197160d2016-03-07 17:33:57 +00001201 info.dex_file = dex_file;
1202 info.class_def_index = class_def_idx;
1203 info.dex_method_index = method_idx;
1204 info.access_flags = access_flags;
1205 info.code_item = code_item;
1206 info.isa = codegen->GetInstructionSet();
1207 info.deduped = false;
1208 info.is_native_debuggable = compiler_options.GetNativeDebuggable();
1209 info.is_optimized = true;
1210 info.is_code_address_text_relative = false;
1211 info.code_address = code_address;
1212 info.code_size = code_allocator.GetSize();
1213 info.frame_size_in_bytes = method_header->GetFrameSizeInBytes();
1214 info.code_info = stack_map_size == 0 ? nullptr : stack_map_data;
1215 info.cfi = ArrayRef<const uint8_t>(*codegen->GetAssembler()->cfi().data());
Vladimir Marko93205e32016-04-13 11:59:46 +01001216 std::vector<uint8_t> elf_file = debug::WriteDebugElfFileForMethods(
David Srbecky5d811202016-03-08 13:21:22 +00001217 GetCompilerDriver()->GetInstructionSet(),
1218 GetCompilerDriver()->GetInstructionSetFeatures(),
David Srbeckyfe736b72016-03-09 11:44:44 +00001219 ArrayRef<const debug::MethodDebugInfo>(&info, 1));
Vladimir Marko93205e32016-04-13 11:59:46 +01001220 CreateJITCodeEntryForAddress(code_address, std::move(elf_file));
David Srbecky5cc349f2015-12-18 15:04:48 +00001221 }
1222
Nicolas Geoffraya4f81542016-03-08 16:57:48 +00001223 Runtime::Current()->GetJit()->AddMemoryUsage(method, arena.BytesUsed());
1224
Nicolas Geoffrayd28b9692015-11-04 14:36:55 +00001225 return true;
1226}
1227
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +00001228} // namespace art