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