common_compiler_test.cc revision d582fa4ea62083a7598dded5b82dc2198b3daac7
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 "class_linker.h"
21#include "compiled_method.h"
22#include "dex/quick_compiler_callbacks.h"
23#include "dex/verification_results.h"
24#include "dex/quick/dex_file_to_method_inliner_map.h"
25#include "driver/compiler_driver.h"
26#include "interpreter/interpreter.h"
27#include "mirror/art_method.h"
28#include "mirror/dex_cache.h"
29#include "mirror/object-inl.h"
30#include "scoped_thread_state_change.h"
31#include "thread-inl.h"
32#include "utils.h"
33
34namespace art {
35
36CommonCompilerTest::CommonCompilerTest() {}
37CommonCompilerTest::~CommonCompilerTest() {}
38
39void CommonCompilerTest::MakeExecutable(mirror::ArtMethod* method) {
40  CHECK(method != nullptr);
41
42  const CompiledMethod* compiled_method = nullptr;
43  if (!method->IsAbstract()) {
44    mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
45    const DexFile& dex_file = *dex_cache->GetDexFile();
46    compiled_method =
47        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
48                                                            method->GetDexMethodIndex()));
49  }
50  if (compiled_method != nullptr) {
51    const std::vector<uint8_t>* code = compiled_method->GetQuickCode();
52    const void* code_ptr;
53    bool is_portable = (code == nullptr);
54    if (!is_portable) {
55      uint32_t code_size = code->size();
56      CHECK_NE(0u, code_size);
57      const std::vector<uint8_t>& vmap_table = compiled_method->GetVmapTable();
58      uint32_t vmap_table_offset = vmap_table.empty() ? 0u
59          : sizeof(OatQuickMethodHeader) + vmap_table.size();
60      const std::vector<uint8_t>& mapping_table = compiled_method->GetMappingTable();
61      uint32_t mapping_table_offset = mapping_table.empty() ? 0u
62          : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table.size();
63      OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset,
64                                         compiled_method->GetFrameSizeInBytes(),
65                                         compiled_method->GetCoreSpillMask(),
66                                         compiled_method->GetFpSpillMask(), code_size);
67
68      header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
69      std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
70      size_t size = sizeof(method_header) + code_size + vmap_table.size() + mapping_table.size();
71      size_t code_offset = compiled_method->AlignCode(size - code_size);
72      size_t padding = code_offset - (size - code_size);
73      chunk->reserve(padding + size);
74      chunk->resize(sizeof(method_header));
75      memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
76      chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
77      chunk->insert(chunk->begin(), mapping_table.begin(), mapping_table.end());
78      chunk->insert(chunk->begin(), padding, 0);
79      chunk->insert(chunk->end(), code->begin(), code->end());
80      CHECK_EQ(padding + size, chunk->size());
81      code_ptr = &(*chunk)[code_offset];
82    } else {
83      code = compiled_method->GetPortableCode();
84      code_ptr = &(*code)[0];
85    }
86    MakeExecutable(code_ptr, code->size());
87    const void* method_code = CompiledMethod::CodePointer(code_ptr,
88                                                          compiled_method->GetInstructionSet());
89    LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
90    class_linker_->SetEntryPointsToCompiledCode(method, method_code, is_portable);
91  } else {
92    // No code? You must mean to go into the interpreter.
93    // Or the generic JNI...
94    class_linker_->SetEntryPointsToInterpreter(method);
95  }
96}
97
98void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
99  CHECK(code_start != nullptr);
100  CHECK_NE(code_length, 0U);
101  uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
102  uintptr_t base = RoundDown(data, kPageSize);
103  uintptr_t limit = RoundUp(data + code_length, kPageSize);
104  uintptr_t len = limit - base;
105  int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
106  CHECK_EQ(result, 0);
107
108  // Flush instruction cache
109  // Only uses __builtin___clear_cache if GCC >= 4.3.3
110#if GCC_VERSION >= 40303
111  __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
112#else
113  // Only warn if not Intel as Intel doesn't have cache flush instructions.
114#if !defined(__i386__) && !defined(__x86_64__)
115  UNIMPLEMENTED(WARNING) << "cache flush";
116#endif
117#endif
118}
119
120void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
121  std::string class_descriptor(DotToDescriptor(class_name));
122  Thread* self = Thread::Current();
123  StackHandleScope<1> hs(self);
124  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
125  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
126  CHECK(klass != nullptr) << "Class not found " << class_name;
127  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
128    MakeExecutable(klass->GetDirectMethod(i));
129  }
130  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
131    MakeExecutable(klass->GetVirtualMethod(i));
132  }
133}
134
135void CommonCompilerTest::SetUp() {
136  CommonRuntimeTest::SetUp();
137  {
138    ScopedObjectAccess soa(Thread::Current());
139
140    const InstructionSet instruction_set = kRuntimeISA;
141    // Take the default set of instruction features from the build.
142    instruction_set_features_.reset(InstructionSetFeatures::FromCppDefines());
143
144    runtime_->SetInstructionSet(instruction_set);
145    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
146      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
147      if (!runtime_->HasCalleeSaveMethod(type)) {
148        runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
149      }
150    }
151
152    // TODO: make selectable
153    Compiler::Kind compiler_kind = kUsePortableCompiler ? Compiler::kPortable : Compiler::kQuick;
154    timer_.reset(new CumulativeLogger("Compilation times"));
155    compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
156                                              verification_results_.get(),
157                                              method_inliner_map_.get(),
158                                              compiler_kind, instruction_set,
159                                              instruction_set_features_.get(),
160                                              true, new std::set<std::string>, nullptr,
161                                              2, true, true, timer_.get(), ""));
162  }
163  // We typically don't generate an image in unit tests, disable this optimization by default.
164  compiler_driver_->SetSupportBootImageFixup(false);
165}
166
167void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
168  CommonRuntimeTest::SetUpRuntimeOptions(options);
169
170  compiler_options_.reset(new CompilerOptions);
171  verification_results_.reset(new VerificationResults(compiler_options_.get()));
172  method_inliner_map_.reset(new DexFileToMethodInlinerMap);
173  callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
174                                              method_inliner_map_.get()));
175  options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
176}
177
178void CommonCompilerTest::TearDown() {
179  timer_.reset();
180  compiler_driver_.reset();
181  callbacks_.reset();
182  method_inliner_map_.reset();
183  verification_results_.reset();
184  compiler_options_.reset();
185
186  CommonRuntimeTest::TearDown();
187}
188
189void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) {
190  std::string class_descriptor(DotToDescriptor(class_name));
191  Thread* self = Thread::Current();
192  StackHandleScope<1> hs(self);
193  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
194  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
195  CHECK(klass != nullptr) << "Class not found " << class_name;
196  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
197    CompileMethod(klass->GetDirectMethod(i));
198  }
199  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
200    CompileMethod(klass->GetVirtualMethod(i));
201  }
202}
203
204void CommonCompilerTest::CompileMethod(mirror::ArtMethod* method) {
205  CHECK(method != nullptr);
206  TimingLogger timings("CommonTest::CompileMethod", false, false);
207  TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
208  compiler_driver_->CompileOne(method, &timings);
209  TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
210  MakeExecutable(method);
211}
212
213void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
214                                             const char* class_name, const char* method_name,
215                                             const char* signature) {
216  std::string class_descriptor(DotToDescriptor(class_name));
217  Thread* self = Thread::Current();
218  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
219  CHECK(klass != nullptr) << "Class not found " << class_name;
220  mirror::ArtMethod* method = klass->FindDirectMethod(method_name, signature);
221  CHECK(method != nullptr) << "Direct method not found: "
222      << class_name << "." << method_name << signature;
223  CompileMethod(method);
224}
225
226void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader,
227                                              const char* class_name, const char* method_name,
228                                              const char* signature) {
229  std::string class_descriptor(DotToDescriptor(class_name));
230  Thread* self = Thread::Current();
231  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
232  CHECK(klass != nullptr) << "Class not found " << class_name;
233  mirror::ArtMethod* method = klass->FindVirtualMethod(method_name, signature);
234  CHECK(method != NULL) << "Virtual method not found: "
235      << class_name << "." << method_name << signature;
236  CompileMethod(method);
237}
238
239void CommonCompilerTest::ReserveImageSpace() {
240  // Reserve where the image will be loaded up front so that other parts of test set up don't
241  // accidentally end up colliding with the fixed memory address when we need to load the image.
242  std::string error_msg;
243  MemMap::Init();
244  image_reservation_.reset(MemMap::MapAnonymous("image reservation",
245                                                reinterpret_cast<uint8_t*>(ART_BASE_ADDRESS),
246                                                (size_t)100 * 1024 * 1024,  // 100MB
247                                                PROT_NONE,
248                                                false /* no need for 4gb flag with fixed mmap*/,
249                                                &error_msg));
250  CHECK(image_reservation_.get() != nullptr) << error_msg;
251}
252
253void CommonCompilerTest::UnreserveImageSpace() {
254  image_reservation_.reset();
255}
256
257}  // namespace art
258