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#ifndef ART_COMPILER_DEX_QUICK_ARM_CODEGEN_ARM_H_
18#define ART_COMPILER_DEX_QUICK_ARM_CODEGEN_ARM_H_
19
20#include "arm_lir.h"
21#include "base/arena_containers.h"
22#include "base/logging.h"
23#include "dex/quick/mir_to_lir.h"
24
25namespace art {
26
27struct CompilationUnit;
28
29class ArmMir2Lir FINAL : public Mir2Lir {
30 protected:
31  // Inherited class for ARM backend.
32  class InToRegStorageArmMapper FINAL : public InToRegStorageMapper {
33   public:
34    InToRegStorageArmMapper()
35        : cur_core_reg_(0), cur_fp_reg_(0), cur_fp_double_reg_(0) {
36    }
37
38    RegStorage GetNextReg(ShortyArg arg) OVERRIDE;
39
40    virtual void Reset() OVERRIDE {
41      cur_core_reg_ = 0;
42      cur_fp_reg_ = 0;
43      cur_fp_double_reg_ = 0;
44    }
45
46   private:
47    size_t cur_core_reg_;
48    size_t cur_fp_reg_;
49    size_t cur_fp_double_reg_;
50  };
51
52  InToRegStorageArmMapper in_to_reg_storage_arm_mapper_;
53  InToRegStorageMapper* GetResetedInToRegStorageMapper() OVERRIDE {
54    in_to_reg_storage_arm_mapper_.Reset();
55    return &in_to_reg_storage_arm_mapper_;
56  }
57
58  public:
59    ArmMir2Lir(CompilationUnit* cu, MIRGraph* mir_graph, ArenaAllocator* arena);
60
61    // Required for target - codegen helpers.
62    bool SmallLiteralDivRem(Instruction::Code dalvik_opcode, bool is_div, RegLocation rl_src,
63                            RegLocation rl_dest, int lit);
64    bool EasyMultiply(RegLocation rl_src, RegLocation rl_dest, int lit) OVERRIDE;
65    void GenMultiplyByConstantFloat(RegLocation rl_dest, RegLocation rl_src1,
66                                    int32_t constant) OVERRIDE;
67    void GenMultiplyByConstantDouble(RegLocation rl_dest, RegLocation rl_src1,
68                                     int64_t constant) OVERRIDE;
69    LIR* CheckSuspendUsingLoad() OVERRIDE;
70    RegStorage LoadHelper(QuickEntrypointEnum trampoline) OVERRIDE;
71    LIR* LoadBaseDisp(RegStorage r_base, int displacement, RegStorage r_dest,
72                      OpSize size, VolatileKind is_volatile) OVERRIDE;
73    LIR* LoadBaseIndexed(RegStorage r_base, RegStorage r_index, RegStorage r_dest, int scale,
74                         OpSize size) OVERRIDE;
75    LIR* LoadConstantNoClobber(RegStorage r_dest, int value);
76    LIR* LoadConstantWide(RegStorage r_dest, int64_t value);
77    LIR* StoreBaseDisp(RegStorage r_base, int displacement, RegStorage r_src,
78                       OpSize size, VolatileKind is_volatile) OVERRIDE;
79    LIR* StoreBaseIndexed(RegStorage r_base, RegStorage r_index, RegStorage r_src, int scale,
80                          OpSize size) OVERRIDE;
81
82    /// @copydoc Mir2Lir::UnconditionallyMarkGCCard(RegStorage)
83    void UnconditionallyMarkGCCard(RegStorage tgt_addr_reg) OVERRIDE;
84
85    bool CanUseOpPcRelDexCacheArrayLoad() const OVERRIDE;
86    void OpPcRelDexCacheArrayLoad(const DexFile* dex_file, int offset, RegStorage r_dest,
87                                  bool wide) OVERRIDE;
88
89    // Required for target - register utilities.
90    RegStorage TargetReg(SpecialTargetRegister reg) OVERRIDE;
91    RegStorage TargetReg(SpecialTargetRegister reg, WideKind wide_kind) OVERRIDE {
92      if (wide_kind == kWide) {
93        DCHECK((kArg0 <= reg && reg < kArg3) || (kFArg0 <= reg && reg < kFArg15) || (kRet0 == reg));
94        RegStorage ret_reg = RegStorage::MakeRegPair(TargetReg(reg),
95            TargetReg(static_cast<SpecialTargetRegister>(reg + 1)));
96        if (ret_reg.IsFloat()) {
97          // Regard double as double, be consistent with register allocation.
98          ret_reg = As64BitFloatReg(ret_reg);
99        }
100        return ret_reg;
101      } else {
102        return TargetReg(reg);
103      }
104    }
105
106    RegLocation GetReturnAlt() OVERRIDE;
107    RegLocation GetReturnWideAlt() OVERRIDE;
108    RegLocation LocCReturn() OVERRIDE;
109    RegLocation LocCReturnRef() OVERRIDE;
110    RegLocation LocCReturnDouble() OVERRIDE;
111    RegLocation LocCReturnFloat() OVERRIDE;
112    RegLocation LocCReturnWide() OVERRIDE;
113    ResourceMask GetRegMaskCommon(const RegStorage& reg) const OVERRIDE;
114    void AdjustSpillMask();
115    void ClobberCallerSave();
116    void FreeCallTemps();
117    void LockCallTemps();
118    void MarkPreservedSingle(int v_reg, RegStorage reg);
119    void MarkPreservedDouble(int v_reg, RegStorage reg);
120    void CompilerInitializeRegAlloc();
121
122    // Required for target - miscellaneous.
123    void AssembleLIR();
124    uint32_t LinkFixupInsns(LIR* head_lir, LIR* tail_lir, CodeOffset offset);
125    int AssignInsnOffsets();
126    void AssignOffsets();
127    static uint8_t* EncodeLIRs(uint8_t* write_pos, LIR* lir);
128    void DumpResourceMask(LIR* lir, const ResourceMask& mask, const char* prefix) OVERRIDE;
129    void SetupTargetResourceMasks(LIR* lir, uint64_t flags,
130                                  ResourceMask* use_mask, ResourceMask* def_mask) OVERRIDE;
131    const char* GetTargetInstFmt(int opcode);
132    const char* GetTargetInstName(int opcode);
133    std::string BuildInsnString(const char* fmt, LIR* lir, unsigned char* base_addr);
134    ResourceMask GetPCUseDefEncoding() const OVERRIDE;
135    uint64_t GetTargetInstFlags(int opcode);
136    size_t GetInsnSize(LIR* lir) OVERRIDE;
137    bool IsUnconditionalBranch(LIR* lir);
138
139    // Get the register class for load/store of a field.
140    RegisterClass RegClassForFieldLoadStore(OpSize size, bool is_volatile) OVERRIDE;
141
142    // Required for target - Dalvik-level generators.
143    void GenArithOpLong(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1,
144                        RegLocation rl_src2, int flags) OVERRIDE;
145    void GenArithImmOpLong(Instruction::Code opcode, RegLocation rl_dest,
146                           RegLocation rl_src1, RegLocation rl_src2, int flags);
147    void GenArrayGet(int opt_flags, OpSize size, RegLocation rl_array,
148                     RegLocation rl_index, RegLocation rl_dest, int scale);
149    void GenArrayPut(int opt_flags, OpSize size, RegLocation rl_array, RegLocation rl_index,
150                     RegLocation rl_src, int scale, bool card_mark);
151    void GenShiftImmOpLong(Instruction::Code opcode, RegLocation rl_dest,
152                           RegLocation rl_src1, RegLocation rl_shift, int flags);
153    void GenArithOpDouble(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1,
154                          RegLocation rl_src2);
155    void GenArithOpFloat(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1,
156                         RegLocation rl_src2);
157    void GenCmpFP(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1,
158                  RegLocation rl_src2);
159    void GenConversion(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src);
160    bool GenInlinedAbsFloat(CallInfo* info) OVERRIDE;
161    bool GenInlinedAbsDouble(CallInfo* info) OVERRIDE;
162    bool GenInlinedCas(CallInfo* info, bool is_long, bool is_object);
163    bool GenInlinedMinMax(CallInfo* info, bool is_min, bool is_long);
164    bool GenInlinedSqrt(CallInfo* info);
165    bool GenInlinedPeek(CallInfo* info, OpSize size);
166    bool GenInlinedPoke(CallInfo* info, OpSize size);
167    bool GenInlinedArrayCopyCharArray(CallInfo* info) OVERRIDE;
168    RegLocation GenDivRem(RegLocation rl_dest, RegStorage reg_lo, RegStorage reg_hi, bool is_div);
169    RegLocation GenDivRemLit(RegLocation rl_dest, RegStorage reg_lo, int lit, bool is_div);
170    void GenCmpLong(RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2);
171    void GenDivZeroCheckWide(RegStorage reg);
172    void GenEntrySequence(RegLocation* ArgLocs, RegLocation rl_method);
173    void GenExitSequence();
174    void GenSpecialExitSequence() OVERRIDE;
175    void GenSpecialEntryForSuspend() OVERRIDE;
176    void GenSpecialExitForSuspend() OVERRIDE;
177    void GenFusedFPCmpBranch(BasicBlock* bb, MIR* mir, bool gt_bias, bool is_double);
178    void GenFusedLongCmpBranch(BasicBlock* bb, MIR* mir);
179    void GenSelect(BasicBlock* bb, MIR* mir);
180    void GenSelectConst32(RegStorage left_op, RegStorage right_op, ConditionCode code,
181                          int32_t true_val, int32_t false_val, RegStorage rs_dest,
182                          RegisterClass dest_reg_class) OVERRIDE;
183    bool GenMemBarrier(MemBarrierKind barrier_kind);
184    void GenMonitorEnter(int opt_flags, RegLocation rl_src);
185    void GenMonitorExit(int opt_flags, RegLocation rl_src);
186    void GenMoveException(RegLocation rl_dest);
187    void GenMultiplyByTwoBitMultiplier(RegLocation rl_src, RegLocation rl_result, int lit,
188                                       int first_bit, int second_bit);
189    void GenNegDouble(RegLocation rl_dest, RegLocation rl_src);
190    void GenNegFloat(RegLocation rl_dest, RegLocation rl_src);
191    void GenLargePackedSwitch(MIR* mir, DexOffset table_offset, RegLocation rl_src);
192    void GenLargeSparseSwitch(MIR* mir, DexOffset table_offset, RegLocation rl_src);
193    void GenMaddMsubInt(RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2,
194                        RegLocation rl_src3, bool is_sub);
195
196    // Required for target - single operation generators.
197    LIR* OpUnconditionalBranch(LIR* target);
198    LIR* OpCmpBranch(ConditionCode cond, RegStorage src1, RegStorage src2, LIR* target);
199    LIR* OpCmpImmBranch(ConditionCode cond, RegStorage reg, int check_value, LIR* target);
200    LIR* OpCondBranch(ConditionCode cc, LIR* target);
201    LIR* OpDecAndBranch(ConditionCode c_code, RegStorage reg, LIR* target);
202    LIR* OpFpRegCopy(RegStorage r_dest, RegStorage r_src);
203    LIR* OpIT(ConditionCode cond, const char* guide);
204    void UpdateIT(LIR* it, const char* new_guide);
205    void OpEndIT(LIR* it);
206    LIR* OpMem(OpKind op, RegStorage r_base, int disp);
207    void OpPcRelLoad(RegStorage reg, LIR* target);
208    LIR* OpReg(OpKind op, RegStorage r_dest_src);
209    void OpRegCopy(RegStorage r_dest, RegStorage r_src);
210    LIR* OpRegCopyNoInsert(RegStorage r_dest, RegStorage r_src);
211    LIR* OpRegImm(OpKind op, RegStorage r_dest_src1, int value);
212    LIR* OpRegReg(OpKind op, RegStorage r_dest_src1, RegStorage r_src2);
213    LIR* OpMovRegMem(RegStorage r_dest, RegStorage r_base, int offset, MoveType move_type);
214    LIR* OpMovMemReg(RegStorage r_base, int offset, RegStorage r_src, MoveType move_type);
215    LIR* OpCondRegReg(OpKind op, ConditionCode cc, RegStorage r_dest, RegStorage r_src);
216    LIR* OpRegRegImm(OpKind op, RegStorage r_dest, RegStorage r_src1, int value);
217    LIR* OpRegRegReg(OpKind op, RegStorage r_dest, RegStorage r_src1, RegStorage r_src2);
218    LIR* OpTestSuspend(LIR* target);
219    LIR* OpVldm(RegStorage r_base, int count);
220    LIR* OpVstm(RegStorage r_base, int count);
221    void OpRegCopyWide(RegStorage dest, RegStorage src);
222
223    LIR* LoadBaseDispBody(RegStorage r_base, int displacement, RegStorage r_dest, OpSize size);
224    LIR* StoreBaseDispBody(RegStorage r_base, int displacement, RegStorage r_src, OpSize size);
225    LIR* OpRegRegRegShift(OpKind op, RegStorage r_dest, RegStorage r_src1, RegStorage r_src2,
226                          int shift);
227    LIR* OpRegRegShift(OpKind op, RegStorage r_dest_src1, RegStorage r_src2, int shift);
228    static const ArmEncodingMap EncodingMap[kArmLast];
229    int EncodeShift(int code, int amount);
230    int ModifiedImmediate(uint32_t value);
231    ArmConditionCode ArmConditionEncoding(ConditionCode code);
232    bool InexpensiveConstantInt(int32_t value) OVERRIDE;
233    bool InexpensiveConstantInt(int32_t value, Instruction::Code opcode) OVERRIDE;
234    bool InexpensiveConstantFloat(int32_t value) OVERRIDE;
235    bool InexpensiveConstantLong(int64_t value) OVERRIDE;
236    bool InexpensiveConstantDouble(int64_t value) OVERRIDE;
237    RegStorage AllocPreservedDouble(int s_reg);
238    RegStorage AllocPreservedSingle(int s_reg);
239
240    bool WideGPRsAreAliases() const OVERRIDE {
241      return false;  // Wide GPRs are formed by pairing.
242    }
243    bool WideFPRsAreAliases() const OVERRIDE {
244      return false;  // Wide FPRs are formed by pairing.
245    }
246
247    NextCallInsn GetNextSDCallInsn() OVERRIDE;
248
249    /*
250     * @brief Generate a relative call to the method that will be patched at link time.
251     * @param target_method The MethodReference of the method to be invoked.
252     * @param type How the method will be invoked.
253     * @returns Call instruction
254     */
255    LIR* CallWithLinkerFixup(const MethodReference& target_method, InvokeType type);
256
257    /*
258     * @brief Generate the actual call insn based on the method info.
259     * @param method_info the lowering info for the method call.
260     * @returns Call instruction
261     */
262    LIR* GenCallInsn(const MirMethodLoweringInfo& method_info) OVERRIDE;
263
264    void CountRefs(RefCounts* core_counts, RefCounts* fp_counts, size_t num_regs) OVERRIDE;
265    void DoPromotion() OVERRIDE;
266
267    /*
268     * @brief Handle ARM specific literals.
269     */
270    void InstallLiteralPools() OVERRIDE;
271
272    LIR* InvokeTrampoline(OpKind op, RegStorage r_tgt, QuickEntrypointEnum trampoline) OVERRIDE;
273    size_t GetInstructionOffset(LIR* lir);
274
275    void GenMachineSpecificExtendedMethodMIR(BasicBlock* bb, MIR* mir) OVERRIDE;
276
277    bool HandleEasyDivRem(Instruction::Code dalvik_opcode, bool is_div,
278                          RegLocation rl_src, RegLocation rl_dest, int lit) OVERRIDE;
279
280  private:
281    void GenNegLong(RegLocation rl_dest, RegLocation rl_src);
282    void GenMulLong(Instruction::Code opcode, RegLocation rl_dest, RegLocation rl_src1,
283                    RegLocation rl_src2);
284    void GenFusedLongCmpImmBranch(BasicBlock* bb, RegLocation rl_src1, int64_t val,
285                                  ConditionCode ccode);
286    LIR* LoadFPConstantValue(int r_dest, int value);
287    LIR* LoadStoreUsingInsnWithOffsetImm8Shl2(ArmOpcode opcode, RegStorage r_base,
288                                              int displacement, RegStorage r_src_dest,
289                                              RegStorage r_work = RegStorage::InvalidReg());
290    void ReplaceFixup(LIR* prev_lir, LIR* orig_lir, LIR* new_lir);
291    void InsertFixupBefore(LIR* prev_lir, LIR* orig_lir, LIR* new_lir);
292    void AssignDataOffsets();
293    RegLocation GenDivRem(RegLocation rl_dest, RegLocation rl_src1, RegLocation rl_src2,
294                          bool is_div, int flags) OVERRIDE;
295    RegLocation GenDivRemLit(RegLocation rl_dest, RegLocation rl_src1, int lit, bool is_div) OVERRIDE;
296    struct EasyMultiplyOp {
297      OpKind op;
298      uint32_t shift;
299    };
300    bool GetEasyMultiplyOp(int lit, EasyMultiplyOp* op);
301    bool GetEasyMultiplyTwoOps(int lit, EasyMultiplyOp* ops);
302    void GenEasyMultiplyTwoOps(RegStorage r_dest, RegStorage r_src, EasyMultiplyOp* ops);
303
304    static constexpr ResourceMask GetRegMaskArm(RegStorage reg);
305    static constexpr ResourceMask EncodeArmRegList(int reg_list);
306    static constexpr ResourceMask EncodeArmRegFpcsList(int reg_list);
307
308    ArenaVector<LIR*> call_method_insns_;
309
310    // Instructions needing patching with PC relative code addresses.
311    ArenaVector<LIR*> dex_cache_access_insns_;
312
313    // Register with a reference to the dex cache arrays at dex_cache_arrays_min_offset_,
314    // if promoted.
315    RegStorage dex_cache_arrays_base_reg_;
316
317    /**
318     * @brief Given float register pair, returns Solo64 float register.
319     * @param reg #RegStorage containing a float register pair (e.g. @c s2 and @c s3).
320     * @return A Solo64 float mapping to the register pair (e.g. @c d1).
321     */
322    static RegStorage As64BitFloatReg(RegStorage reg) {
323      DCHECK(reg.IsFloat());
324
325      RegStorage low = reg.GetLow();
326      RegStorage high = reg.GetHigh();
327      DCHECK((low.GetRegNum() % 2 == 0) && (low.GetRegNum() + 1 == high.GetRegNum()));
328
329      return RegStorage::FloatSolo64(low.GetRegNum() / 2);
330    }
331
332    /**
333     * @brief Given Solo64 float register, returns float register pair.
334     * @param reg #RegStorage containing a Solo64 float register (e.g. @c d1).
335     * @return A float register pair mapping to the Solo64 float pair (e.g. @c s2 and s3).
336     */
337    static RegStorage As64BitFloatRegPair(RegStorage reg) {
338      DCHECK(reg.IsDouble() && reg.Is64BitSolo());
339
340      int reg_num = reg.GetRegNum();
341      return RegStorage::MakeRegPair(RegStorage::FloatSolo32(reg_num * 2),
342                                     RegStorage::FloatSolo32(reg_num * 2 + 1));
343    }
344
345    int GenDalvikArgsBulkCopy(CallInfo* info, int first, int count) OVERRIDE;
346
347    static int ArmNextSDCallInsn(CompilationUnit* cu, CallInfo* info ATTRIBUTE_UNUSED,
348                                 int state, const MethodReference& target_method,
349                                 uint32_t unused_idx ATTRIBUTE_UNUSED,
350                                 uintptr_t direct_code, uintptr_t direct_method,
351                                 InvokeType type);
352
353    void OpPcRelDexCacheArrayAddr(const DexFile* dex_file, int offset, RegStorage r_dest);
354};
355
356}  // namespace art
357
358#endif  // ART_COMPILER_DEX_QUICK_ARM_CODEGEN_ARM_H_
359