1 /*
2  * Copyright (C) 2015 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 "compiler_options.h"
18 
19 #include <fstream>
20 #include <string_view>
21 
22 #include "android-base/stringprintf.h"
23 
24 #include "arch/instruction_set.h"
25 #include "arch/instruction_set_features.h"
26 #include "base/runtime_debug.h"
27 #include "base/string_view_cpp20.h"
28 #include "base/variant_map.h"
29 #include "class_linker.h"
30 #include "cmdline_parser.h"
31 #include "compiler_options_map-inl.h"
32 #include "dex/dex_file-inl.h"
33 #include "dex/verification_results.h"
34 #include "dex/verified_method.h"
35 #include "runtime.h"
36 #include "scoped_thread_state_change-inl.h"
37 #include "simple_compiler_options_map.h"
38 
39 namespace art {
40 
CompilerOptions()41 CompilerOptions::CompilerOptions()
42     : compiler_filter_(CompilerFilter::kDefaultCompilerFilter),
43       huge_method_threshold_(kDefaultHugeMethodThreshold),
44       large_method_threshold_(kDefaultLargeMethodThreshold),
45       num_dex_methods_threshold_(kDefaultNumDexMethodsThreshold),
46       inline_max_code_units_(kUnsetInlineMaxCodeUnits),
47       instruction_set_(kRuntimeISA == InstructionSet::kArm ? InstructionSet::kThumb2 : kRuntimeISA),
48       instruction_set_features_(nullptr),
49       no_inline_from_(),
50       dex_files_for_oat_file_(),
51       image_classes_(),
52       verification_results_(nullptr),
53       image_type_(ImageType::kNone),
54       compiling_with_core_image_(false),
55       baseline_(false),
56       debuggable_(false),
57       generate_debug_info_(kDefaultGenerateDebugInfo),
58       generate_mini_debug_info_(kDefaultGenerateMiniDebugInfo),
59       generate_build_id_(false),
60       implicit_null_checks_(true),
61       implicit_so_checks_(true),
62       implicit_suspend_checks_(false),
63       compile_pic_(false),
64       dump_timings_(false),
65       dump_pass_timings_(false),
66       dump_stats_(false),
67       top_k_profile_threshold_(kDefaultTopKProfileThreshold),
68       profile_compilation_info_(nullptr),
69       verbose_methods_(),
70       abort_on_hard_verifier_failure_(false),
71       abort_on_soft_verifier_failure_(false),
72       init_failure_output_(nullptr),
73       dump_cfg_file_name_(""),
74       dump_cfg_append_(false),
75       force_determinism_(false),
76       deduplicate_code_(true),
77       count_hotness_in_compiled_code_(false),
78       resolve_startup_const_strings_(false),
79       initialize_app_image_classes_(false),
80       check_profiled_methods_(ProfileMethodsCheck::kNone),
81       max_image_block_size_(std::numeric_limits<uint32_t>::max()),
82       register_allocation_strategy_(RegisterAllocator::kRegisterAllocatorDefault),
83       passes_to_run_(nullptr) {
84 }
85 
~CompilerOptions()86 CompilerOptions::~CompilerOptions() {
87   // Everything done by member destructors.
88   // The definitions of classes forward-declared in the header have now been #included.
89 }
90 
91 namespace {
92 
93 bool kEmitRuntimeReadBarrierChecks = kIsDebugBuild &&
94     RegisterRuntimeDebugFlag(&kEmitRuntimeReadBarrierChecks);
95 
96 }  // namespace
97 
EmitRunTimeChecksInDebugMode() const98 bool CompilerOptions::EmitRunTimeChecksInDebugMode() const {
99   // Run-time checks (e.g. Marking Register checks) are only emitted in slow-debug mode.
100   return kEmitRuntimeReadBarrierChecks;
101 }
102 
ParseDumpInitFailures(const std::string & option,std::string * error_msg)103 bool CompilerOptions::ParseDumpInitFailures(const std::string& option, std::string* error_msg) {
104   init_failure_output_.reset(new std::ofstream(option));
105   if (init_failure_output_.get() == nullptr) {
106     *error_msg = "Failed to construct std::ofstream";
107     return false;
108   } else if (init_failure_output_->fail()) {
109     *error_msg = android::base::StringPrintf(
110         "Failed to open %s for writing the initialization failures.", option.c_str());
111     init_failure_output_.reset();
112     return false;
113   }
114   return true;
115 }
116 
ParseRegisterAllocationStrategy(const std::string & option,std::string * error_msg)117 bool CompilerOptions::ParseRegisterAllocationStrategy(const std::string& option,
118                                                       std::string* error_msg) {
119   if (option == "linear-scan") {
120     register_allocation_strategy_ = RegisterAllocator::Strategy::kRegisterAllocatorLinearScan;
121   } else if (option == "graph-color") {
122     register_allocation_strategy_ = RegisterAllocator::Strategy::kRegisterAllocatorGraphColor;
123   } else {
124     *error_msg = "Unrecognized register allocation strategy. Try linear-scan, or graph-color.";
125     return false;
126   }
127   return true;
128 }
129 
ParseCompilerOptions(const std::vector<std::string> & options,bool ignore_unrecognized,std::string * error_msg)130 bool CompilerOptions::ParseCompilerOptions(const std::vector<std::string>& options,
131                                            bool ignore_unrecognized,
132                                            std::string* error_msg) {
133   auto parser = CreateSimpleParser(ignore_unrecognized);
134   CmdlineResult parse_result = parser.Parse(options);
135   if (!parse_result.IsSuccess()) {
136     *error_msg = parse_result.GetMessage();
137     return false;
138   }
139 
140   SimpleParseArgumentMap args = parser.ReleaseArgumentsMap();
141   return ReadCompilerOptions(args, this, error_msg);
142 }
143 
IsImageClass(const char * descriptor) const144 bool CompilerOptions::IsImageClass(const char* descriptor) const {
145   // Historical note: We used to hold the set indirectly and there was a distinction between an
146   // empty set and a null, null meaning to include all classes. However, the distiction has been
147   // removed; if we don't have a profile, we treat it as an empty set of classes. b/77340429
148   return image_classes_.find(std::string_view(descriptor)) != image_classes_.end();
149 }
150 
GetVerificationResults() const151 const VerificationResults* CompilerOptions::GetVerificationResults() const {
152   DCHECK(Runtime::Current()->IsAotCompiler());
153   return verification_results_;
154 }
155 
GetVerifiedMethod(const DexFile * dex_file,uint32_t method_idx) const156 const VerifiedMethod* CompilerOptions::GetVerifiedMethod(const DexFile* dex_file,
157                                                          uint32_t method_idx) const {
158   MethodReference ref(dex_file, method_idx);
159   return verification_results_->GetVerifiedMethod(ref);
160 }
161 
IsMethodVerifiedWithoutFailures(uint32_t method_idx,uint16_t class_def_idx,const DexFile & dex_file) const162 bool CompilerOptions::IsMethodVerifiedWithoutFailures(uint32_t method_idx,
163                                                       uint16_t class_def_idx,
164                                                       const DexFile& dex_file) const {
165   const VerifiedMethod* verified_method = GetVerifiedMethod(&dex_file, method_idx);
166   if (verified_method != nullptr) {
167     return !verified_method->HasVerificationFailures();
168   }
169 
170   // If we can't find verification metadata, check if this is a system class (we trust that system
171   // classes have their methods verified). If it's not, be conservative and assume the method
172   // has not been verified successfully.
173 
174   // TODO: When compiling the boot image it should be safe to assume that everything is verified,
175   // even if methods are not found in the verification cache.
176   const char* descriptor = dex_file.GetClassDescriptor(dex_file.GetClassDef(class_def_idx));
177   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
178   Thread* self = Thread::Current();
179   ScopedObjectAccess soa(self);
180   bool is_system_class = class_linker->FindSystemClass(self, descriptor) != nullptr;
181   if (!is_system_class) {
182     self->ClearException();
183   }
184   return is_system_class;
185 }
186 
IsCoreImageFilename(const std::string & boot_image_filename)187 bool CompilerOptions::IsCoreImageFilename(const std::string& boot_image_filename) {
188   std::string_view filename(boot_image_filename);
189   size_t colon_pos = filename.find(':');
190   if (colon_pos != std::string_view::npos) {
191     filename = filename.substr(0u, colon_pos);
192   }
193   // Look for "core.art" or "core-*.art".
194   if (EndsWith(filename, "core.art")) {
195     return true;
196   }
197   if (!EndsWith(filename, ".art")) {
198     return false;
199   }
200   size_t slash_pos = filename.rfind('/');
201   if (slash_pos == std::string::npos) {
202     return StartsWith(filename, "core-");
203   }
204   return filename.compare(slash_pos + 1, 5u, "core-") == 0;
205 }
206 
207 }  // namespace art
208