common_compiler_test.cc revision d4c4d953035d4418126d36517e402f411d6a87f3
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 "class_linker.h"
20#include "compiled_method.h"
21#include "dex/quick_compiler_callbacks.h"
22#include "dex/verification_results.h"
23#include "dex/quick/dex_file_to_method_inliner_map.h"
24#include "driver/compiler_driver.h"
25#include "interpreter/interpreter.h"
26#include "mirror/art_method.h"
27#include "mirror/dex_cache.h"
28#include "mirror/object-inl.h"
29#include "scoped_thread_state_change.h"
30#include "thread-inl.h"
31#include "utils.h"
32
33namespace art {
34
35CommonCompilerTest::CommonCompilerTest() {}
36CommonCompilerTest::~CommonCompilerTest() {}
37
38void CommonCompilerTest::MakeExecutable(mirror::ArtMethod* method) {
39  CHECK(method != nullptr);
40
41  const CompiledMethod* compiled_method = nullptr;
42  if (!method->IsAbstract()) {
43    mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
44    const DexFile& dex_file = *dex_cache->GetDexFile();
45    compiled_method =
46        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
47                                                            method->GetDexMethodIndex()));
48  }
49  if (compiled_method != nullptr) {
50    const std::vector<uint8_t>* code = compiled_method->GetQuickCode();
51    const void* code_ptr;
52    bool is_portable = (code == nullptr);
53    if (!is_portable) {
54      uint32_t code_size = code->size();
55      CHECK_NE(0u, code_size);
56      const std::vector<uint8_t>& vmap_table = compiled_method->GetVmapTable();
57      uint32_t vmap_table_offset = vmap_table.empty() ? 0u
58          : sizeof(OatQuickMethodHeader) + vmap_table.size();
59      const std::vector<uint8_t>& mapping_table = compiled_method->GetMappingTable();
60      uint32_t mapping_table_offset = mapping_table.empty() ? 0u
61          : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table.size();
62      OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset,
63                                         compiled_method->GetFrameSizeInBytes(),
64                                         compiled_method->GetCoreSpillMask(),
65                                         compiled_method->GetFpSpillMask(), code_size);
66
67      header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
68      std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
69      size_t size = sizeof(method_header) + code_size + vmap_table.size() + mapping_table.size();
70      size_t code_offset = compiled_method->AlignCode(size - code_size);
71      size_t padding = code_offset - (size - code_size);
72      chunk->reserve(padding + size);
73      chunk->resize(sizeof(method_header));
74      memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
75      chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
76      chunk->insert(chunk->begin(), mapping_table.begin(), mapping_table.end());
77      chunk->insert(chunk->begin(), padding, 0);
78      chunk->insert(chunk->end(), code->begin(), code->end());
79      CHECK_EQ(padding + size, chunk->size());
80      code_ptr = &(*chunk)[code_offset];
81    } else {
82      code = compiled_method->GetPortableCode();
83      code_ptr = &(*code)[0];
84    }
85    MakeExecutable(code_ptr, code->size());
86    const void* method_code = CompiledMethod::CodePointer(code_ptr,
87                                                          compiled_method->GetInstructionSet());
88    LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
89    class_linker_->SetEntryPointsToCompiledCode(method, method_code, is_portable);
90  } else {
91    // No code? You must mean to go into the interpreter.
92    // Or the generic JNI...
93    class_linker_->SetEntryPointsToInterpreter(method);
94  }
95}
96
97void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
98  CHECK(code_start != nullptr);
99  CHECK_NE(code_length, 0U);
100  uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
101  uintptr_t base = RoundDown(data, kPageSize);
102  uintptr_t limit = RoundUp(data + code_length, kPageSize);
103  uintptr_t len = limit - base;
104  int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
105  CHECK_EQ(result, 0);
106
107  // Flush instruction cache
108  // Only uses __builtin___clear_cache if GCC >= 4.3.3
109#if GCC_VERSION >= 40303
110  __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
111#else
112  // Only warn if not Intel as Intel doesn't have cache flush instructions.
113#if !defined(__i386__) && !defined(__x86_64__)
114  LOG(WARNING) << "UNIMPLEMENTED: cache flush";
115#endif
116#endif
117}
118
119void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
120  std::string class_descriptor(DotToDescriptor(class_name));
121  Thread* self = Thread::Current();
122  StackHandleScope<1> hs(self);
123  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
124  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
125  CHECK(klass != nullptr) << "Class not found " << class_name;
126  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
127    MakeExecutable(klass->GetDirectMethod(i));
128  }
129  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
130    MakeExecutable(klass->GetVirtualMethod(i));
131  }
132}
133
134void CommonCompilerTest::SetUp() {
135  CommonRuntimeTest::SetUp();
136  {
137    ScopedObjectAccess soa(Thread::Current());
138
139    const InstructionSet instruction_set = kRuntimeISA;
140    // Take the default set of instruction features from the build.
141    instruction_set_features_.reset(InstructionSetFeatures::FromCppDefines());
142
143    runtime_->SetInstructionSet(instruction_set);
144    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
145      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
146      if (!runtime_->HasCalleeSaveMethod(type)) {
147        runtime_->SetCalleeSaveMethod(
148            runtime_->CreateCalleeSaveMethod(type), 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>,
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