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