common_compiler_test.cc revision 3c94f0945ed596ceee39783fa075f013b65e80a1
1/*
2 * Copyright (C) 2011 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 "common_compiler_test.h"
18
19#include "arch/instruction_set_features.h"
20#include "art_field-inl.h"
21#include "art_method.h"
22#include "class_linker.h"
23#include "compiled_method.h"
24#include "dex/quick_compiler_callbacks.h"
25#include "dex/quick/dex_file_to_method_inliner_map.h"
26#include "dex/verification_results.h"
27#include "driver/compiler_driver.h"
28#include "driver/compiler_options.h"
29#include "interpreter/interpreter.h"
30#include "mirror/class_loader.h"
31#include "mirror/class-inl.h"
32#include "mirror/dex_cache.h"
33#include "mirror/object-inl.h"
34#include "oat_quick_method_header.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "utils.h"
38
39namespace art {
40
41CommonCompilerTest::CommonCompilerTest() {}
42CommonCompilerTest::~CommonCompilerTest() {}
43
44void CommonCompilerTest::MakeExecutable(ArtMethod* method) {
45  CHECK(method != nullptr);
46
47  const CompiledMethod* compiled_method = nullptr;
48  if (!method->IsAbstract()) {
49    mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
50    const DexFile& dex_file = *dex_cache->GetDexFile();
51    compiled_method =
52        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
53                                                            method->GetDexMethodIndex()));
54  }
55  if (compiled_method != nullptr) {
56    ArrayRef<const uint8_t> code = compiled_method->GetQuickCode();
57    uint32_t code_size = code.size();
58    CHECK_NE(0u, code_size);
59    ArrayRef<const uint8_t> vmap_table = compiled_method->GetVmapTable();
60    uint32_t vmap_table_offset = vmap_table.empty() ? 0u
61        : sizeof(OatQuickMethodHeader) + vmap_table.size();
62    ArrayRef<const uint8_t> mapping_table = compiled_method->GetMappingTable();
63    bool mapping_table_used = !mapping_table.empty();
64    size_t mapping_table_size = mapping_table.size();
65    uint32_t mapping_table_offset = !mapping_table_used ? 0u
66        : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table_size;
67    ArrayRef<const uint8_t> gc_map = compiled_method->GetGcMap();
68    bool gc_map_used = !gc_map.empty();
69    size_t gc_map_size = gc_map.size();
70    uint32_t gc_map_offset = !gc_map_used ? 0u
71        : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table_size + gc_map_size;
72    OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset, gc_map_offset,
73                                       compiled_method->GetFrameSizeInBytes(),
74                                       compiled_method->GetCoreSpillMask(),
75                                       compiled_method->GetFpSpillMask(), code_size);
76
77    header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
78    std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
79    const size_t max_padding = GetInstructionSetAlignment(compiled_method->GetInstructionSet());
80    const size_t size =
81        gc_map_size + mapping_table_size + vmap_table.size() + sizeof(method_header) + code_size;
82    chunk->reserve(size + max_padding);
83    chunk->resize(sizeof(method_header));
84    memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
85    chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
86    if (mapping_table_used) {
87      chunk->insert(chunk->begin(), mapping_table.begin(), mapping_table.end());
88    }
89    if (gc_map_used) {
90      chunk->insert(chunk->begin(), gc_map.begin(), gc_map.end());
91    }
92    chunk->insert(chunk->end(), code.begin(), code.end());
93    CHECK_EQ(chunk->size(), size);
94    const void* unaligned_code_ptr = chunk->data() + (size - code_size);
95    size_t offset = dchecked_integral_cast<size_t>(reinterpret_cast<uintptr_t>(unaligned_code_ptr));
96    size_t padding = compiled_method->AlignCode(offset) - offset;
97    // Make sure no resizing takes place.
98    CHECK_GE(chunk->capacity(), chunk->size() + padding);
99    chunk->insert(chunk->begin(), padding, 0);
100    const void* code_ptr = reinterpret_cast<const uint8_t*>(unaligned_code_ptr) + padding;
101    CHECK_EQ(code_ptr, static_cast<const void*>(chunk->data() + (chunk->size() - code_size)));
102    MakeExecutable(code_ptr, code.size());
103    const void* method_code = CompiledMethod::CodePointer(code_ptr,
104                                                          compiled_method->GetInstructionSet());
105    LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
106    class_linker_->SetEntryPointsToCompiledCode(method, method_code);
107  } else {
108    // No code? You must mean to go into the interpreter.
109    // Or the generic JNI...
110    class_linker_->SetEntryPointsToInterpreter(method);
111  }
112}
113
114void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
115  CHECK(code_start != nullptr);
116  CHECK_NE(code_length, 0U);
117  uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
118  uintptr_t base = RoundDown(data, kPageSize);
119  uintptr_t limit = RoundUp(data + code_length, kPageSize);
120  uintptr_t len = limit - base;
121  int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
122  CHECK_EQ(result, 0);
123
124  FlushInstructionCache(reinterpret_cast<char*>(base), reinterpret_cast<char*>(base + len));
125}
126
127void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
128  std::string class_descriptor(DotToDescriptor(class_name));
129  Thread* self = Thread::Current();
130  StackHandleScope<1> hs(self);
131  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
132  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
133  CHECK(klass != nullptr) << "Class not found " << class_name;
134  size_t pointer_size = class_linker_->GetImagePointerSize();
135  for (auto& m : klass->GetMethods(pointer_size)) {
136    MakeExecutable(&m);
137  }
138}
139
140// Get the set of image classes given to the compiler-driver in SetUp. Note: the compiler
141// driver assumes ownership of the set, so the test should properly release the set.
142std::unordered_set<std::string>* CommonCompilerTest::GetImageClasses() {
143  // Empty set: by default no classes are retained in the image.
144  return new std::unordered_set<std::string>();
145}
146
147// Get the set of compiled classes given to the compiler-driver in SetUp. Note: the compiler
148// driver assumes ownership of the set, so the test should properly release the set.
149std::unordered_set<std::string>* CommonCompilerTest::GetCompiledClasses() {
150  // Null, no selection of compiled-classes.
151  return nullptr;
152}
153
154// Get the set of compiled methods given to the compiler-driver in SetUp. Note: the compiler
155// driver assumes ownership of the set, so the test should properly release the set.
156std::unordered_set<std::string>* CommonCompilerTest::GetCompiledMethods() {
157  // Null, no selection of compiled-methods.
158  return nullptr;
159}
160
161// Get ProfileCompilationInfo that should be passed to the driver.
162ProfileCompilationInfo* CommonCompilerTest::GetProfileCompilationInfo() {
163  // Null, profile information will not be taken into account.
164  return nullptr;
165}
166
167void CommonCompilerTest::SetUp() {
168  CommonRuntimeTest::SetUp();
169  {
170    ScopedObjectAccess soa(Thread::Current());
171
172    const InstructionSet instruction_set = kRuntimeISA;
173    // Take the default set of instruction features from the build.
174    instruction_set_features_.reset(InstructionSetFeatures::FromCppDefines());
175
176    runtime_->SetInstructionSet(instruction_set);
177    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
178      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
179      if (!runtime_->HasCalleeSaveMethod(type)) {
180        runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
181      }
182    }
183
184    timer_.reset(new CumulativeLogger("Compilation times"));
185    CreateCompilerDriver(compiler_kind_, instruction_set);
186  }
187}
188
189void CommonCompilerTest::CreateCompilerDriver(Compiler::Kind kind,
190                                              InstructionSet isa,
191                                              size_t number_of_threads) {
192  compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
193                                            verification_results_.get(),
194                                            method_inliner_map_.get(),
195                                            kind,
196                                            isa,
197                                            instruction_set_features_.get(),
198                                            /* boot_image */ true,
199                                            GetImageClasses(),
200                                            GetCompiledClasses(),
201                                            GetCompiledMethods(),
202                                            number_of_threads,
203                                            /* dump_stats */ true,
204                                            /* dump_passes */ true,
205                                            timer_.get(),
206                                            /* swap_fd */ -1,
207                                            GetProfileCompilationInfo()));
208  // We typically don't generate an image in unit tests, disable this optimization by default.
209  compiler_driver_->SetSupportBootImageFixup(false);
210}
211
212void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
213  CommonRuntimeTest::SetUpRuntimeOptions(options);
214
215  compiler_options_.reset(new CompilerOptions);
216  verification_results_.reset(new VerificationResults(compiler_options_.get()));
217  method_inliner_map_.reset(new DexFileToMethodInlinerMap);
218  callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
219                                              method_inliner_map_.get(),
220                                              CompilerCallbacks::CallbackMode::kCompileApp));
221}
222
223Compiler::Kind CommonCompilerTest::GetCompilerKind() const {
224  return compiler_kind_;
225}
226
227void CommonCompilerTest::SetCompilerKind(Compiler::Kind compiler_kind) {
228  compiler_kind_ = compiler_kind;
229}
230
231InstructionSet CommonCompilerTest::GetInstructionSet() const {
232  DCHECK(compiler_driver_.get() != nullptr);
233  return compiler_driver_->GetInstructionSet();
234}
235
236void CommonCompilerTest::TearDown() {
237  timer_.reset();
238  compiler_driver_.reset();
239  callbacks_.reset();
240  method_inliner_map_.reset();
241  verification_results_.reset();
242  compiler_options_.reset();
243
244  CommonRuntimeTest::TearDown();
245}
246
247void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) {
248  std::string class_descriptor(DotToDescriptor(class_name));
249  Thread* self = Thread::Current();
250  StackHandleScope<1> hs(self);
251  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
252  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
253  CHECK(klass != nullptr) << "Class not found " << class_name;
254  auto pointer_size = class_linker_->GetImagePointerSize();
255  for (auto& m : klass->GetMethods(pointer_size)) {
256    CompileMethod(&m);
257  }
258}
259
260void CommonCompilerTest::CompileMethod(ArtMethod* method) {
261  CHECK(method != nullptr);
262  TimingLogger timings("CommonTest::CompileMethod", false, false);
263  TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
264  compiler_driver_->CompileOne(Thread::Current(), method, &timings);
265  TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
266  MakeExecutable(method);
267}
268
269void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
270                                             const char* class_name, const char* method_name,
271                                             const char* signature) {
272  std::string class_descriptor(DotToDescriptor(class_name));
273  Thread* self = Thread::Current();
274  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
275  CHECK(klass != nullptr) << "Class not found " << class_name;
276  auto pointer_size = class_linker_->GetImagePointerSize();
277  ArtMethod* method = klass->FindDirectMethod(method_name, signature, pointer_size);
278  CHECK(method != nullptr) << "Direct method not found: "
279      << class_name << "." << method_name << signature;
280  CompileMethod(method);
281}
282
283void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader,
284                                              const char* class_name, const char* method_name,
285                                              const char* signature) {
286  std::string class_descriptor(DotToDescriptor(class_name));
287  Thread* self = Thread::Current();
288  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
289  CHECK(klass != nullptr) << "Class not found " << class_name;
290  auto pointer_size = class_linker_->GetImagePointerSize();
291  ArtMethod* method = klass->FindVirtualMethod(method_name, signature, pointer_size);
292  CHECK(method != nullptr) << "Virtual method not found: "
293      << class_name << "." << method_name << signature;
294  CompileMethod(method);
295}
296
297void CommonCompilerTest::ReserveImageSpace() {
298  // Reserve where the image will be loaded up front so that other parts of test set up don't
299  // accidentally end up colliding with the fixed memory address when we need to load the image.
300  std::string error_msg;
301  MemMap::Init();
302  image_reservation_.reset(MemMap::MapAnonymous("image reservation",
303                                                reinterpret_cast<uint8_t*>(ART_BASE_ADDRESS),
304                                                (size_t)100 * 1024 * 1024,  // 100MB
305                                                PROT_NONE,
306                                                false /* no need for 4gb flag with fixed mmap*/,
307                                                false /* not reusing existing reservation */,
308                                                &error_msg));
309  CHECK(image_reservation_.get() != nullptr) << error_msg;
310}
311
312void CommonCompilerTest::UnreserveImageSpace() {
313  image_reservation_.reset();
314}
315
316}  // namespace art
317