common_compiler_test.cc revision 63bc11efaac0c041e849ab401f9fc368631a00f5
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#if defined(__arm__)
20#include <sys/ucontext.h>
21#endif
22#include <fstream>
23
24#include "class_linker.h"
25#include "compiled_method.h"
26#include "dex/quick_compiler_callbacks.h"
27#include "dex/verification_results.h"
28#include "dex/quick/dex_file_to_method_inliner_map.h"
29#include "driver/compiler_driver.h"
30#include "entrypoints/entrypoint_utils.h"
31#include "interpreter/interpreter.h"
32#include "mirror/art_method.h"
33#include "mirror/dex_cache.h"
34#include "mirror/object-inl.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "utils.h"
38
39namespace art {
40
41// Normally the ClassLinker supplies this.
42extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
43
44#if defined(__arm__)
45// A signal handler called when have an illegal instruction.  We record the fact in
46// a global boolean and then increment the PC in the signal context to return to
47// the next instruction.  We know the instruction is an sdiv (4 bytes long).
48static void baddivideinst(int signo, siginfo *si, void *data) {
49  UNUSED(signo);
50  UNUSED(si);
51  struct ucontext *uc = (struct ucontext *)data;
52  struct sigcontext *sc = &uc->uc_mcontext;
53  sc->arm_r0 = 0;     // set R0 to #0 to signal error
54  sc->arm_pc += 4;    // skip offending instruction
55}
56
57// This is in arch/arm/arm_sdiv.S.  It does the following:
58// mov r1,#1
59// sdiv r0,r1,r1
60// bx lr
61//
62// the result will be the value 1 if sdiv is supported.  If it is not supported
63// a SIGILL signal will be raised and the signal handler (baddivideinst) called.
64// The signal handler sets r0 to #0 and then increments pc beyond the failed instruction.
65// Thus if the instruction is not supported, the result of this function will be #0
66
67extern "C" bool CheckForARMSDIVInstruction();
68
69static InstructionSetFeatures GuessInstructionFeatures() {
70  InstructionSetFeatures f;
71
72  // Uncomment this for processing of /proc/cpuinfo.
73  if (false) {
74    // Look in /proc/cpuinfo for features we need.  Only use this when we can guarantee that
75    // the kernel puts the appropriate feature flags in here.  Sometimes it doesn't.
76    std::ifstream in("/proc/cpuinfo");
77    if (in) {
78      while (!in.eof()) {
79        std::string line;
80        std::getline(in, line);
81        if (!in.eof()) {
82          if (line.find("Features") != std::string::npos) {
83            if (line.find("idivt") != std::string::npos) {
84              f.SetHasDivideInstruction(true);
85            }
86          }
87        }
88        in.close();
89      }
90    } else {
91      LOG(INFO) << "Failed to open /proc/cpuinfo";
92    }
93  }
94
95  // See if have a sdiv instruction.  Register a signal handler and try to execute
96  // an sdiv instruction.  If we get a SIGILL then it's not supported.  We can't use
97  // the /proc/cpuinfo method for this because Krait devices don't always put the idivt
98  // feature in the list.
99  struct sigaction sa, osa;
100  sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
101  sa.sa_sigaction = baddivideinst;
102  sigaction(SIGILL, &sa, &osa);
103
104  if (CheckForARMSDIVInstruction()) {
105    f.SetHasDivideInstruction(true);
106  }
107
108  // Restore the signal handler.
109  sigaction(SIGILL, &osa, nullptr);
110
111  // Other feature guesses in here.
112  return f;
113}
114#endif
115
116// Given a set of instruction features from the build, parse it.  The
117// input 'str' is a comma separated list of feature names.  Parse it and
118// return the InstructionSetFeatures object.
119static InstructionSetFeatures ParseFeatureList(std::string str) {
120  InstructionSetFeatures result;
121  typedef std::vector<std::string> FeatureList;
122  FeatureList features;
123  Split(str, ',', features);
124  for (FeatureList::iterator i = features.begin(); i != features.end(); i++) {
125    std::string feature = Trim(*i);
126    if (feature == "default") {
127      // Nothing to do.
128    } else if (feature == "div") {
129      // Supports divide instruction.
130      result.SetHasDivideInstruction(true);
131    } else if (feature == "nodiv") {
132      // Turn off support for divide instruction.
133      result.SetHasDivideInstruction(false);
134    } else {
135      LOG(FATAL) << "Unknown instruction set feature: '" << feature << "'";
136    }
137  }
138  // Others...
139  return result;
140}
141
142CommonCompilerTest::CommonCompilerTest() {}
143CommonCompilerTest::~CommonCompilerTest() {}
144
145OatFile::OatMethod CommonCompilerTest::CreateOatMethod(const void* code, const uint8_t* gc_map) {
146  CHECK(code != nullptr);
147  const byte* base;
148  uint32_t code_offset, gc_map_offset;
149  if (gc_map == nullptr) {
150    base = reinterpret_cast<const byte*>(code);  // Base of data points at code.
151    base -= kPointerSize;  // Move backward so that code_offset != 0.
152    code_offset = kPointerSize;
153    gc_map_offset = 0;
154  } else {
155    // TODO: 64bit support.
156    base = nullptr;  // Base of data in oat file, ie 0.
157    code_offset = PointerToLowMemUInt32(code);
158    gc_map_offset = PointerToLowMemUInt32(gc_map);
159  }
160  return OatFile::OatMethod(base, code_offset, gc_map_offset);
161}
162
163void CommonCompilerTest::MakeExecutable(mirror::ArtMethod* method) {
164  CHECK(method != nullptr);
165
166  const CompiledMethod* compiled_method = nullptr;
167  if (!method->IsAbstract()) {
168    mirror::DexCache* dex_cache = method->GetDeclaringClass()->GetDexCache();
169    const DexFile& dex_file = *dex_cache->GetDexFile();
170    compiled_method =
171        compiler_driver_->GetCompiledMethod(MethodReference(&dex_file,
172                                                            method->GetDexMethodIndex()));
173  }
174  if (compiled_method != nullptr) {
175    const std::vector<uint8_t>* code = compiled_method->GetQuickCode();
176    const void* code_ptr;
177    if (code != nullptr) {
178      uint32_t code_size = code->size();
179      CHECK_NE(0u, code_size);
180      const std::vector<uint8_t>& vmap_table = compiled_method->GetVmapTable();
181      uint32_t vmap_table_offset = vmap_table.empty() ? 0u
182          : sizeof(OatQuickMethodHeader) + vmap_table.size();
183      const std::vector<uint8_t>& mapping_table = compiled_method->GetMappingTable();
184      uint32_t mapping_table_offset = mapping_table.empty() ? 0u
185          : sizeof(OatQuickMethodHeader) + vmap_table.size() + mapping_table.size();
186      OatQuickMethodHeader method_header(mapping_table_offset, vmap_table_offset,
187                                         compiled_method->GetFrameSizeInBytes(),
188                                         compiled_method->GetCoreSpillMask(),
189                                         compiled_method->GetFpSpillMask(), code_size);
190
191      header_code_and_maps_chunks_.push_back(std::vector<uint8_t>());
192      std::vector<uint8_t>* chunk = &header_code_and_maps_chunks_.back();
193      size_t size = sizeof(method_header) + code_size + vmap_table.size() + mapping_table.size();
194      size_t code_offset = compiled_method->AlignCode(size - code_size);
195      size_t padding = code_offset - (size - code_size);
196      chunk->reserve(padding + size);
197      chunk->resize(sizeof(method_header));
198      memcpy(&(*chunk)[0], &method_header, sizeof(method_header));
199      chunk->insert(chunk->begin(), vmap_table.begin(), vmap_table.end());
200      chunk->insert(chunk->begin(), mapping_table.begin(), mapping_table.end());
201      chunk->insert(chunk->begin(), padding, 0);
202      chunk->insert(chunk->end(), code->begin(), code->end());
203      CHECK_EQ(padding + size, chunk->size());
204      code_ptr = &(*chunk)[code_offset];
205    } else {
206      code = compiled_method->GetPortableCode();
207      code_ptr = &(*code)[0];
208    }
209    MakeExecutable(code_ptr, code->size());
210    const void* method_code = CompiledMethod::CodePointer(code_ptr,
211                                                          compiled_method->GetInstructionSet());
212    LOG(INFO) << "MakeExecutable " << PrettyMethod(method) << " code=" << method_code;
213    OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr);
214    oat_method.LinkMethod(method);
215    method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
216  } else {
217    // No code? You must mean to go into the interpreter.
218    // Or the generic JNI...
219    if (!method->IsNative()) {
220#if defined(ART_USE_PORTABLE_COMPILER)
221      const void* method_code = GetPortableToInterpreterBridge();
222#else
223      const void* method_code = GetQuickToInterpreterBridge();
224#endif
225      OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr);
226      oat_method.LinkMethod(method);
227      method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
228    } else {
229      const void* method_code = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
230
231      OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr);
232      oat_method.LinkMethod(method);
233      method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
234    }
235  }
236  // Create bridges to transition between different kinds of compiled bridge.
237#if defined(ART_USE_PORTABLE_COMPILER)
238  if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
239    method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
240  } else {
241    CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
242    method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
243    method->SetIsPortableCompiled();
244  }
245#else
246  CHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
247#endif
248}
249
250void CommonCompilerTest::MakeExecutable(const void* code_start, size_t code_length) {
251  CHECK(code_start != nullptr);
252  CHECK_NE(code_length, 0U);
253  uintptr_t data = reinterpret_cast<uintptr_t>(code_start);
254  uintptr_t base = RoundDown(data, kPageSize);
255  uintptr_t limit = RoundUp(data + code_length, kPageSize);
256  uintptr_t len = limit - base;
257  int result = mprotect(reinterpret_cast<void*>(base), len, PROT_READ | PROT_WRITE | PROT_EXEC);
258  CHECK_EQ(result, 0);
259
260  // Flush instruction cache
261  // Only uses __builtin___clear_cache if GCC >= 4.3.3
262#if GCC_VERSION >= 40303
263  __builtin___clear_cache(reinterpret_cast<void*>(base), reinterpret_cast<void*>(base + len));
264#else
265  // Only warn if not Intel as Intel doesn't have cache flush instructions.
266#if !defined(__i386__) && !defined(__x86_64__)
267  LOG(WARNING) << "UNIMPLEMENTED: cache flush";
268#endif
269#endif
270}
271
272void CommonCompilerTest::MakeExecutable(mirror::ClassLoader* class_loader, const char* class_name) {
273  std::string class_descriptor(DotToDescriptor(class_name));
274  Thread* self = Thread::Current();
275  StackHandleScope<1> hs(self);
276  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
277  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
278  CHECK(klass != nullptr) << "Class not found " << class_name;
279  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
280    MakeExecutable(klass->GetDirectMethod(i));
281  }
282  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
283    MakeExecutable(klass->GetVirtualMethod(i));
284  }
285}
286
287void CommonCompilerTest::SetUp() {
288  CommonRuntimeTest::SetUp();
289  {
290    ScopedObjectAccess soa(Thread::Current());
291
292    InstructionSet instruction_set = kRuntimeISA;
293
294    // Take the default set of instruction features from the build.
295    InstructionSetFeatures instruction_set_features =
296        ParseFeatureList(Runtime::GetDefaultInstructionSetFeatures());
297
298#if defined(__arm__)
299    InstructionSetFeatures runtime_features = GuessInstructionFeatures();
300
301    // for ARM, do a runtime check to make sure that the features we are passed from
302    // the build match the features we actually determine at runtime.
303    ASSERT_LE(instruction_set_features, runtime_features);
304#endif
305
306    runtime_->SetInstructionSet(instruction_set);
307    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
308      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
309      if (!runtime_->HasCalleeSaveMethod(type)) {
310        runtime_->SetCalleeSaveMethod(
311            runtime_->CreateCalleeSaveMethod(type), type);
312      }
313    }
314
315    // TODO: make selectable
316    Compiler::Kind compiler_kind
317    = (kUsePortableCompiler) ? Compiler::kPortable : Compiler::kQuick;
318    timer_.reset(new CumulativeLogger("Compilation times"));
319    compiler_driver_.reset(new CompilerDriver(compiler_options_.get(),
320                                              verification_results_.get(),
321                                              method_inliner_map_.get(),
322                                              compiler_kind, instruction_set,
323                                              instruction_set_features,
324                                              true, new std::set<std::string>,
325                                              2, true, true, timer_.get()));
326  }
327  // We typically don't generate an image in unit tests, disable this optimization by default.
328  compiler_driver_->SetSupportBootImageFixup(false);
329}
330
331void CommonCompilerTest::SetUpRuntimeOptions(RuntimeOptions* options) {
332  CommonRuntimeTest::SetUpRuntimeOptions(options);
333
334  compiler_options_.reset(new CompilerOptions);
335  verification_results_.reset(new VerificationResults(compiler_options_.get()));
336  method_inliner_map_.reset(new DexFileToMethodInlinerMap);
337  callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(),
338                                              method_inliner_map_.get()));
339  options->push_back(std::make_pair("compilercallbacks", callbacks_.get()));
340}
341
342void CommonCompilerTest::TearDown() {
343  timer_.reset();
344  compiler_driver_.reset();
345  callbacks_.reset();
346  method_inliner_map_.reset();
347  verification_results_.reset();
348  compiler_options_.reset();
349
350  CommonRuntimeTest::TearDown();
351}
352
353void CommonCompilerTest::CompileClass(mirror::ClassLoader* class_loader, const char* class_name) {
354  std::string class_descriptor(DotToDescriptor(class_name));
355  Thread* self = Thread::Current();
356  StackHandleScope<1> hs(self);
357  Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
358  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), loader);
359  CHECK(klass != nullptr) << "Class not found " << class_name;
360  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
361    CompileMethod(klass->GetDirectMethod(i));
362  }
363  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
364    CompileMethod(klass->GetVirtualMethod(i));
365  }
366}
367
368void CommonCompilerTest::CompileMethod(mirror::ArtMethod* method) {
369  CHECK(method != nullptr);
370  TimingLogger timings("CommonTest::CompileMethod", false, false);
371  TimingLogger::ScopedTiming t(__FUNCTION__, &timings);
372  compiler_driver_->CompileOne(method, &timings);
373  TimingLogger::ScopedTiming t2("MakeExecutable", &timings);
374  MakeExecutable(method);
375}
376
377void CommonCompilerTest::CompileDirectMethod(Handle<mirror::ClassLoader> class_loader,
378                                             const char* class_name, const char* method_name,
379                                             const char* signature) {
380  std::string class_descriptor(DotToDescriptor(class_name));
381  Thread* self = Thread::Current();
382  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
383  CHECK(klass != nullptr) << "Class not found " << class_name;
384  mirror::ArtMethod* method = klass->FindDirectMethod(method_name, signature);
385  CHECK(method != nullptr) << "Direct method not found: "
386      << class_name << "." << method_name << signature;
387  CompileMethod(method);
388}
389
390void CommonCompilerTest::CompileVirtualMethod(Handle<mirror::ClassLoader> class_loader, const char* class_name,
391                                              const char* method_name, const char* signature)
392SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
393  std::string class_descriptor(DotToDescriptor(class_name));
394  Thread* self = Thread::Current();
395  mirror::Class* klass = class_linker_->FindClass(self, class_descriptor.c_str(), class_loader);
396  CHECK(klass != nullptr) << "Class not found " << class_name;
397  mirror::ArtMethod* method = klass->FindVirtualMethod(method_name, signature);
398  CHECK(method != NULL) << "Virtual method not found: "
399      << class_name << "." << method_name << signature;
400  CompileMethod(method);
401}
402
403void CommonCompilerTest::ReserveImageSpace() {
404  // Reserve where the image will be loaded up front so that other parts of test set up don't
405  // accidentally end up colliding with the fixed memory address when we need to load the image.
406  std::string error_msg;
407  image_reservation_.reset(MemMap::MapAnonymous("image reservation",
408                                                reinterpret_cast<byte*>(ART_BASE_ADDRESS),
409                                                (size_t)100 * 1024 * 1024,  // 100MB
410                                                PROT_NONE,
411                                                false /* no need for 4gb flag with fixed mmap*/,
412                                                &error_msg));
413  CHECK(image_reservation_.get() != nullptr) << error_msg;
414}
415
416void CommonCompilerTest::UnreserveImageSpace() {
417  image_reservation_.reset();
418}
419
420}  // namespace art
421