1 /*
2  * Copyright (C) 2023 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 "berberis/heavy_optimizer/riscv64/heavy_optimize_region.h"
18 
19 #include <cstdint>
20 #include <tuple>
21 
22 #include "berberis/assembler/machine_code.h"
23 #include "berberis/backend/x86_64/code_gen.h"
24 #include "berberis/backend/x86_64/machine_ir.h"
25 #include "berberis/base/arena_alloc.h"
26 #include "berberis/base/config_globals.h"
27 #include "berberis/base/tracing.h"
28 #include "berberis/decoder/riscv64/decoder.h"
29 #include "berberis/decoder/riscv64/semantics_player.h"
30 #include "berberis/guest_state/guest_addr.h"
31 
32 #include "frontend.h"
33 
34 namespace berberis {
35 
HeavyOptimizeRegion(GuestAddr pc,MachineCode * machine_code,const HeavyOptimizeParams & params)36 std::tuple<GuestAddr, bool, size_t> HeavyOptimizeRegion(GuestAddr pc,
37                                                         MachineCode* machine_code,
38                                                         const HeavyOptimizeParams& params) {
39   Arena arena;
40   x86_64::MachineIR machine_ir(&arena);
41   HeavyOptimizerFrontend frontend(&machine_ir, pc);
42   SemanticsPlayer sem_player(&frontend);
43   Decoder decoder(&sem_player);
44   size_t number_of_instructions = 0;
45 
46   while (number_of_instructions != params.max_number_of_instructions &&
47          !frontend.IsRegionEndReached()) {
48     frontend.StartInsn();
49     auto size = decoder.Decode(ToHostAddr<uint16_t>(frontend.GetInsnAddr()));
50     if (!frontend.success()) {
51       // Do not increment the insn counter if we could not generate the instruction.
52       break;
53     }
54     frontend.IncrementInsnAddr(size);
55     number_of_instructions++;
56   }
57 
58   auto stop_pc = frontend.GetInsnAddr();
59   frontend.Finalize(stop_pc);
60 
61   if (IsConfigFlagSet(kVerboseTranslation)) {
62     // Trace only after all the potential failure points.
63     TRACE("Heavy optimizing 0x%lx (%lu bytes)", pc, stop_pc - pc);
64   }
65 
66   x86_64::GenCode(&machine_ir, machine_code);
67 
68   return {stop_pc, frontend.success(), number_of_instructions};
69 }
70 
71 }  // namespace berberis
72