quick_trampoline_entrypoints.cc revision 966c3ae95d3c699ee9fbdbccc1acdaaf02325faf
1/*
2 * Copyright (C) 2012 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 "callee_save_frame.h"
18#include "common_throws.h"
19#include "dex_file-inl.h"
20#include "dex_instruction-inl.h"
21#include "entrypoints/entrypoint_utils-inl.h"
22#include "entrypoints/runtime_asm_entrypoints.h"
23#include "gc/accounting/card_table-inl.h"
24#include "interpreter/interpreter.h"
25#include "method_reference.h"
26#include "mirror/art_method-inl.h"
27#include "mirror/class-inl.h"
28#include "mirror/dex_cache-inl.h"
29#include "mirror/object-inl.h"
30#include "mirror/object_array-inl.h"
31#include "runtime.h"
32#include "scoped_thread_state_change.h"
33
34namespace art {
35
36// Visits the arguments as saved to the stack by a Runtime::kRefAndArgs callee save frame.
37class QuickArgumentVisitor {
38  // Number of bytes for each out register in the caller method's frame.
39  static constexpr size_t kBytesStackArgLocation = 4;
40  // Frame size in bytes of a callee-save frame for RefsAndArgs.
41  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_FrameSize =
42      GetCalleeSaveFrameSize(kRuntimeISA, Runtime::kRefsAndArgs);
43#if defined(__arm__)
44  // The callee save frame is pointed to by SP.
45  // | argN       |  |
46  // | ...        |  |
47  // | arg4       |  |
48  // | arg3 spill |  |  Caller's frame
49  // | arg2 spill |  |
50  // | arg1 spill |  |
51  // | Method*    | ---
52  // | LR         |
53  // | ...        |    4x6 bytes callee saves
54  // | R3         |
55  // | R2         |
56  // | R1         |
57  // | S15        |
58  // | :          |
59  // | S0         |
60  // |            |    4x2 bytes padding
61  // | Method*    |  <- sp
62  static constexpr bool kAlignPairRegister = !kArm32QuickCodeUseSoftFloat;
63  static constexpr bool kQuickSoftFloatAbi = kArm32QuickCodeUseSoftFloat;
64  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = !kArm32QuickCodeUseSoftFloat;
65  static constexpr size_t kNumQuickGprArgs = 3;
66  static constexpr size_t kNumQuickFprArgs = kArm32QuickCodeUseSoftFloat ? 0 : 16;
67  static constexpr bool kGprFprLockstep = false;
68  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
69      arm::ArmCalleeSaveFpr1Offset(Runtime::kRefsAndArgs);  // Offset of first FPR arg.
70  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
71      arm::ArmCalleeSaveGpr1Offset(Runtime::kRefsAndArgs);  // Offset of first GPR arg.
72  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset =
73      arm::ArmCalleeSaveLrOffset(Runtime::kRefsAndArgs);  // Offset of return address.
74  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
75    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
76  }
77#elif defined(__aarch64__)
78  // The callee save frame is pointed to by SP.
79  // | argN       |  |
80  // | ...        |  |
81  // | arg4       |  |
82  // | arg3 spill |  |  Caller's frame
83  // | arg2 spill |  |
84  // | arg1 spill |  |
85  // | Method*    | ---
86  // | LR         |
87  // | X29        |
88  // |  :         |
89  // | X20        |
90  // | X7         |
91  // | :          |
92  // | X1         |
93  // | D7         |
94  // |  :         |
95  // | D0         |
96  // |            |    padding
97  // | Method*    |  <- sp
98  static constexpr bool kAlignPairRegister = false;
99  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
100  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
101  static constexpr size_t kNumQuickGprArgs = 7;  // 7 arguments passed in GPRs.
102  static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
103  static constexpr bool kGprFprLockstep = false;
104  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset =
105      arm64::Arm64CalleeSaveFpr1Offset(Runtime::kRefsAndArgs);  // Offset of first FPR arg.
106  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset =
107      arm64::Arm64CalleeSaveGpr1Offset(Runtime::kRefsAndArgs);  // Offset of first GPR arg.
108  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset =
109      arm64::Arm64CalleeSaveLrOffset(Runtime::kRefsAndArgs);  // Offset of return address.
110  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
111    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
112  }
113#elif defined(__mips__) && !defined(__LP64__)
114  // The callee save frame is pointed to by SP.
115  // | argN       |  |
116  // | ...        |  |
117  // | arg4       |  |
118  // | arg3 spill |  |  Caller's frame
119  // | arg2 spill |  |
120  // | arg1 spill |  |
121  // | Method*    | ---
122  // | RA         |
123  // | ...        |    callee saves
124  // | A3         |    arg3
125  // | A2         |    arg2
126  // | A1         |    arg1
127  // | A0/Method* |  <- sp
128  static constexpr bool kAlignPairRegister = false;
129  static constexpr bool kQuickSoftFloatAbi = true;  // This is a soft float ABI.
130  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
131  static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
132  static constexpr size_t kNumQuickFprArgs = 0;  // 0 arguments passed in FPRs.
133  static constexpr bool kGprFprLockstep = false;
134  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 0;  // Offset of first FPR arg.
135  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 16;  // Offset of first GPR arg.
136  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 60;  // Offset of return address.
137  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
138    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
139  }
140#elif defined(__mips__) && defined(__LP64__)
141  // The callee save frame is pointed to by SP.
142  // | argN       |  |
143  // | ...        |  |
144  // | arg4       |  |
145  // | arg3 spill |  |  Caller's frame
146  // | arg2 spill |  |
147  // | arg1 spill |  |
148  // | Method*    | ---
149  // | RA         |
150  // | ...        |    callee saves
151  // | F7         |    f_arg7
152  // | F6         |    f_arg6
153  // | F5         |    f_arg5
154  // | F6         |    f_arg6
155  // | F5         |    f_arg5
156  // | F4         |    f_arg4
157  // | F3         |    f_arg3
158  // | F2         |    f_arg2
159  // | F1         |    f_arg1
160  // | F0         |    f_arg0
161  // | A7         |    arg7
162  // | A6         |    arg6
163  // | A5         |    arg5
164  // | A4         |    arg4
165  // | A3         |    arg3
166  // | A2         |    arg2
167  // | A1         |    arg1
168  // |            |    padding
169  // | A0/Method* |  <- sp
170  // NOTE: for Mip64, when A0 is skipped, F0 is also skipped.
171  static constexpr bool kAlignPairRegister = false;
172  static constexpr bool kQuickSoftFloatAbi = false;
173  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
174  // These values are set to zeros because GPR and FPR register
175  // assignments for Mips64 are interleaved, which the current VisitArguments()
176  // function does not support.
177  static constexpr size_t kNumQuickGprArgs = 7;  // 7 arguments passed in GPRs.
178  static constexpr size_t kNumQuickFprArgs = 7;  // 7 arguments passed in FPRs.
179  static constexpr bool kGprFprLockstep = true;
180
181  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 24;  // Offset of first FPR arg (F1).
182  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 80;  // Offset of first GPR arg (A1).
183  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 200;  // Offset of return address.
184  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
185    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
186  }
187#elif defined(__i386__)
188  // The callee save frame is pointed to by SP.
189  // | argN        |  |
190  // | ...         |  |
191  // | arg4        |  |
192  // | arg3 spill  |  |  Caller's frame
193  // | arg2 spill  |  |
194  // | arg1 spill  |  |
195  // | Method*     | ---
196  // | Return      |
197  // | EBP,ESI,EDI |    callee saves
198  // | EBX         |    arg3
199  // | EDX         |    arg2
200  // | ECX         |    arg1
201  // | XMM3        |    float arg 4
202  // | XMM2        |    float arg 3
203  // | XMM1        |    float arg 2
204  // | XMM0        |    float arg 1
205  // | EAX/Method* |  <- sp
206  static constexpr bool kAlignPairRegister = false;
207  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
208  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
209  static constexpr size_t kNumQuickGprArgs = 3;  // 3 arguments passed in GPRs.
210  static constexpr size_t kNumQuickFprArgs = 4;  // 4 arguments passed in FPRs.
211  static constexpr bool kGprFprLockstep = false;
212  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 4;  // Offset of first FPR arg.
213  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 4 + 4*8;  // Offset of first GPR arg.
214  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 28 + 4*8;  // Offset of return address.
215  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
216    return gpr_index * GetBytesPerGprSpillLocation(kRuntimeISA);
217  }
218#elif defined(__x86_64__)
219  // The callee save frame is pointed to by SP.
220  // | argN            |  |
221  // | ...             |  |
222  // | reg. arg spills |  |  Caller's frame
223  // | Method*         | ---
224  // | Return          |
225  // | R15             |    callee save
226  // | R14             |    callee save
227  // | R13             |    callee save
228  // | R12             |    callee save
229  // | R9              |    arg5
230  // | R8              |    arg4
231  // | RSI/R6          |    arg1
232  // | RBP/R5          |    callee save
233  // | RBX/R3          |    callee save
234  // | RDX/R2          |    arg2
235  // | RCX/R1          |    arg3
236  // | XMM7            |    float arg 8
237  // | XMM6            |    float arg 7
238  // | XMM5            |    float arg 6
239  // | XMM4            |    float arg 5
240  // | XMM3            |    float arg 4
241  // | XMM2            |    float arg 3
242  // | XMM1            |    float arg 2
243  // | XMM0            |    float arg 1
244  // | Padding         |
245  // | RDI/Method*     |  <- sp
246  static constexpr bool kAlignPairRegister = false;
247  static constexpr bool kQuickSoftFloatAbi = false;  // This is a hard float ABI.
248  static constexpr bool kQuickDoubleRegAlignedFloatBackFilled = false;
249  static constexpr size_t kNumQuickGprArgs = 5;  // 5 arguments passed in GPRs.
250  static constexpr size_t kNumQuickFprArgs = 8;  // 8 arguments passed in FPRs.
251  static constexpr bool kGprFprLockstep = false;
252  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset = 16;  // Offset of first FPR arg.
253  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset = 80 + 4*8;  // Offset of first GPR arg.
254  static constexpr size_t kQuickCalleeSaveFrame_RefAndArgs_LrOffset = 168 + 4*8;  // Offset of return address.
255  static size_t GprIndexToGprOffset(uint32_t gpr_index) {
256    switch (gpr_index) {
257      case 0: return (4 * GetBytesPerGprSpillLocation(kRuntimeISA));
258      case 1: return (1 * GetBytesPerGprSpillLocation(kRuntimeISA));
259      case 2: return (0 * GetBytesPerGprSpillLocation(kRuntimeISA));
260      case 3: return (5 * GetBytesPerGprSpillLocation(kRuntimeISA));
261      case 4: return (6 * GetBytesPerGprSpillLocation(kRuntimeISA));
262      default:
263      LOG(FATAL) << "Unexpected GPR index: " << gpr_index;
264      return 0;
265    }
266  }
267#else
268#error "Unsupported architecture"
269#endif
270
271 public:
272  // Special handling for proxy methods. Proxy methods are instance methods so the
273  // 'this' object is the 1st argument. They also have the same frame layout as the
274  // kRefAndArgs runtime method. Since 'this' is a reference, it is located in the
275  // 1st GPR.
276  static mirror::Object* GetProxyThisObject(StackReference<mirror::ArtMethod>* sp)
277      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
278    CHECK(sp->AsMirrorPtr()->IsProxyMethod());
279    CHECK_EQ(kQuickCalleeSaveFrame_RefAndArgs_FrameSize, sp->AsMirrorPtr()->GetFrameSizeInBytes());
280    CHECK_GT(kNumQuickGprArgs, 0u);
281    constexpr uint32_t kThisGprIndex = 0u;  // 'this' is in the 1st GPR.
282    size_t this_arg_offset = kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset +
283        GprIndexToGprOffset(kThisGprIndex);
284    uint8_t* this_arg_address = reinterpret_cast<uint8_t*>(sp) + this_arg_offset;
285    return reinterpret_cast<StackReference<mirror::Object>*>(this_arg_address)->AsMirrorPtr();
286  }
287
288  static mirror::ArtMethod* GetCallingMethod(StackReference<mirror::ArtMethod>* sp)
289      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
290    DCHECK(sp->AsMirrorPtr()->IsCalleeSaveMethod());
291    uint8_t* previous_sp = reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize;
292    return reinterpret_cast<StackReference<mirror::ArtMethod>*>(previous_sp)->AsMirrorPtr();
293  }
294
295  // For the given quick ref and args quick frame, return the caller's PC.
296  static uintptr_t GetCallingPc(StackReference<mirror::ArtMethod>* sp)
297      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
298    DCHECK(sp->AsMirrorPtr()->IsCalleeSaveMethod());
299    uint8_t* lr = reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_LrOffset;
300    return *reinterpret_cast<uintptr_t*>(lr);
301  }
302
303  QuickArgumentVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static, const char* shorty,
304                       uint32_t shorty_len) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
305          is_static_(is_static), shorty_(shorty), shorty_len_(shorty_len),
306          gpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Gpr1Offset),
307          fpr_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_Fpr1Offset),
308          stack_args_(reinterpret_cast<uint8_t*>(sp) + kQuickCalleeSaveFrame_RefAndArgs_FrameSize
309              + sizeof(StackReference<mirror::ArtMethod>)),  // Skip StackReference<ArtMethod>.
310          gpr_index_(0), fpr_index_(0), fpr_double_index_(0), stack_index_(0),
311          cur_type_(Primitive::kPrimVoid), is_split_long_or_double_(false) {
312    static_assert(kQuickSoftFloatAbi == (kNumQuickFprArgs == 0),
313                  "Number of Quick FPR arguments unexpected");
314    static_assert(!(kQuickSoftFloatAbi && kQuickDoubleRegAlignedFloatBackFilled),
315                  "Double alignment unexpected");
316    // For register alignment, we want to assume that counters(fpr_double_index_) are even if the
317    // next register is even.
318    static_assert(!kQuickDoubleRegAlignedFloatBackFilled || kNumQuickFprArgs % 2 == 0,
319                  "Number of Quick FPR arguments not even");
320  }
321
322  virtual ~QuickArgumentVisitor() {}
323
324  virtual void Visit() = 0;
325
326  Primitive::Type GetParamPrimitiveType() const {
327    return cur_type_;
328  }
329
330  uint8_t* GetParamAddress() const {
331    if (!kQuickSoftFloatAbi) {
332      Primitive::Type type = GetParamPrimitiveType();
333      if (UNLIKELY((type == Primitive::kPrimDouble) || (type == Primitive::kPrimFloat))) {
334        if (type == Primitive::kPrimDouble && kQuickDoubleRegAlignedFloatBackFilled) {
335          if (fpr_double_index_ + 2 < kNumQuickFprArgs + 1) {
336            return fpr_args_ + (fpr_double_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
337          }
338        } else if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
339          return fpr_args_ + (fpr_index_ * GetBytesPerFprSpillLocation(kRuntimeISA));
340        }
341        return stack_args_ + (stack_index_ * kBytesStackArgLocation);
342      }
343    }
344    if (gpr_index_ < kNumQuickGprArgs) {
345      return gpr_args_ + GprIndexToGprOffset(gpr_index_);
346    }
347    return stack_args_ + (stack_index_ * kBytesStackArgLocation);
348  }
349
350  bool IsSplitLongOrDouble() const {
351    if ((GetBytesPerGprSpillLocation(kRuntimeISA) == 4) || (GetBytesPerFprSpillLocation(kRuntimeISA) == 4)) {
352      return is_split_long_or_double_;
353    } else {
354      return false;  // An optimization for when GPR and FPRs are 64bit.
355    }
356  }
357
358  bool IsParamAReference() const {
359    return GetParamPrimitiveType() == Primitive::kPrimNot;
360  }
361
362  bool IsParamALongOrDouble() const {
363    Primitive::Type type = GetParamPrimitiveType();
364    return type == Primitive::kPrimLong || type == Primitive::kPrimDouble;
365  }
366
367  uint64_t ReadSplitLongParam() const {
368    // The splitted long is always available through the stack.
369    return *reinterpret_cast<uint64_t*>(stack_args_
370        + stack_index_ * kBytesStackArgLocation);
371  }
372
373  void IncGprIndex() {
374    gpr_index_++;
375    if (kGprFprLockstep) {
376      fpr_index_++;
377    }
378  }
379
380  void IncFprIndex() {
381    fpr_index_++;
382    if (kGprFprLockstep) {
383      gpr_index_++;
384    }
385  }
386
387  void VisitArguments() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
388    // (a) 'stack_args_' should point to the first method's argument
389    // (b) whatever the argument type it is, the 'stack_index_' should
390    //     be moved forward along with every visiting.
391    gpr_index_ = 0;
392    fpr_index_ = 0;
393    if (kQuickDoubleRegAlignedFloatBackFilled) {
394      fpr_double_index_ = 0;
395    }
396    stack_index_ = 0;
397    if (!is_static_) {  // Handle this.
398      cur_type_ = Primitive::kPrimNot;
399      is_split_long_or_double_ = false;
400      Visit();
401      stack_index_++;
402      if (kNumQuickGprArgs > 0) {
403        IncGprIndex();
404      }
405    }
406    for (uint32_t shorty_index = 1; shorty_index < shorty_len_; ++shorty_index) {
407      cur_type_ = Primitive::GetType(shorty_[shorty_index]);
408      switch (cur_type_) {
409        case Primitive::kPrimNot:
410        case Primitive::kPrimBoolean:
411        case Primitive::kPrimByte:
412        case Primitive::kPrimChar:
413        case Primitive::kPrimShort:
414        case Primitive::kPrimInt:
415          is_split_long_or_double_ = false;
416          Visit();
417          stack_index_++;
418          if (gpr_index_ < kNumQuickGprArgs) {
419            IncGprIndex();
420          }
421          break;
422        case Primitive::kPrimFloat:
423          is_split_long_or_double_ = false;
424          Visit();
425          stack_index_++;
426          if (kQuickSoftFloatAbi) {
427            if (gpr_index_ < kNumQuickGprArgs) {
428              IncGprIndex();
429            }
430          } else {
431            if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
432              IncFprIndex();
433              if (kQuickDoubleRegAlignedFloatBackFilled) {
434                // Double should not overlap with float.
435                // For example, if fpr_index_ = 3, fpr_double_index_ should be at least 4.
436                fpr_double_index_ = std::max(fpr_double_index_, RoundUp(fpr_index_, 2));
437                // Float should not overlap with double.
438                if (fpr_index_ % 2 == 0) {
439                  fpr_index_ = std::max(fpr_double_index_, fpr_index_);
440                }
441              }
442            }
443          }
444          break;
445        case Primitive::kPrimDouble:
446        case Primitive::kPrimLong:
447          if (kQuickSoftFloatAbi || (cur_type_ == Primitive::kPrimLong)) {
448            if (cur_type_ == Primitive::kPrimLong && kAlignPairRegister && gpr_index_ == 0) {
449              // Currently, this is only for ARM, where the first available parameter register
450              // is R1. So we skip it, and use R2 instead.
451              IncGprIndex();
452            }
453            is_split_long_or_double_ = (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) &&
454                ((gpr_index_ + 1) == kNumQuickGprArgs);
455            Visit();
456            if (kBytesStackArgLocation == 4) {
457              stack_index_+= 2;
458            } else {
459              CHECK_EQ(kBytesStackArgLocation, 8U);
460              stack_index_++;
461            }
462            if (gpr_index_ < kNumQuickGprArgs) {
463              IncGprIndex();
464              if (GetBytesPerGprSpillLocation(kRuntimeISA) == 4) {
465                if (gpr_index_ < kNumQuickGprArgs) {
466                  IncGprIndex();
467                }
468              }
469            }
470          } else {
471            is_split_long_or_double_ = (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) &&
472                ((fpr_index_ + 1) == kNumQuickFprArgs) && !kQuickDoubleRegAlignedFloatBackFilled;
473            Visit();
474            if (kBytesStackArgLocation == 4) {
475              stack_index_+= 2;
476            } else {
477              CHECK_EQ(kBytesStackArgLocation, 8U);
478              stack_index_++;
479            }
480            if (kQuickDoubleRegAlignedFloatBackFilled) {
481              if (fpr_double_index_ + 2 < kNumQuickFprArgs + 1) {
482                fpr_double_index_ += 2;
483                // Float should not overlap with double.
484                if (fpr_index_ % 2 == 0) {
485                  fpr_index_ = std::max(fpr_double_index_, fpr_index_);
486                }
487              }
488            } else if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
489              IncFprIndex();
490              if (GetBytesPerFprSpillLocation(kRuntimeISA) == 4) {
491                if (fpr_index_ + 1 < kNumQuickFprArgs + 1) {
492                  IncFprIndex();
493                }
494              }
495            }
496          }
497          break;
498        default:
499          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty_;
500      }
501    }
502  }
503
504 protected:
505  const bool is_static_;
506  const char* const shorty_;
507  const uint32_t shorty_len_;
508
509 private:
510  uint8_t* const gpr_args_;  // Address of GPR arguments in callee save frame.
511  uint8_t* const fpr_args_;  // Address of FPR arguments in callee save frame.
512  uint8_t* const stack_args_;  // Address of stack arguments in caller's frame.
513  uint32_t gpr_index_;  // Index into spilled GPRs.
514  // Index into spilled FPRs.
515  // In case kQuickDoubleRegAlignedFloatBackFilled, it may index a hole while fpr_double_index_
516  // holds a higher register number.
517  uint32_t fpr_index_;
518  // Index into spilled FPRs for aligned double.
519  // Only used when kQuickDoubleRegAlignedFloatBackFilled. Next available double register indexed in
520  // terms of singles, may be behind fpr_index.
521  uint32_t fpr_double_index_;
522  uint32_t stack_index_;  // Index into arguments on the stack.
523  // The current type of argument during VisitArguments.
524  Primitive::Type cur_type_;
525  // Does a 64bit parameter straddle the register and stack arguments?
526  bool is_split_long_or_double_;
527};
528
529// Returns the 'this' object of a proxy method. This function is only used by StackVisitor. It
530// allows to use the QuickArgumentVisitor constants without moving all the code in its own module.
531extern "C" mirror::Object* artQuickGetProxyThisObject(StackReference<mirror::ArtMethod>* sp)
532    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
533  return QuickArgumentVisitor::GetProxyThisObject(sp);
534}
535
536// Visits arguments on the stack placing them into the shadow frame.
537class BuildQuickShadowFrameVisitor FINAL : public QuickArgumentVisitor {
538 public:
539  BuildQuickShadowFrameVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static,
540                               const char* shorty, uint32_t shorty_len, ShadowFrame* sf,
541                               size_t first_arg_reg) :
542      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), sf_(sf), cur_reg_(first_arg_reg) {}
543
544  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
545
546 private:
547  ShadowFrame* const sf_;
548  uint32_t cur_reg_;
549
550  DISALLOW_COPY_AND_ASSIGN(BuildQuickShadowFrameVisitor);
551};
552
553void BuildQuickShadowFrameVisitor::Visit() {
554  Primitive::Type type = GetParamPrimitiveType();
555  switch (type) {
556    case Primitive::kPrimLong:  // Fall-through.
557    case Primitive::kPrimDouble:
558      if (IsSplitLongOrDouble()) {
559        sf_->SetVRegLong(cur_reg_, ReadSplitLongParam());
560      } else {
561        sf_->SetVRegLong(cur_reg_, *reinterpret_cast<jlong*>(GetParamAddress()));
562      }
563      ++cur_reg_;
564      break;
565    case Primitive::kPrimNot: {
566        StackReference<mirror::Object>* stack_ref =
567            reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
568        sf_->SetVRegReference(cur_reg_, stack_ref->AsMirrorPtr());
569      }
570      break;
571    case Primitive::kPrimBoolean:  // Fall-through.
572    case Primitive::kPrimByte:     // Fall-through.
573    case Primitive::kPrimChar:     // Fall-through.
574    case Primitive::kPrimShort:    // Fall-through.
575    case Primitive::kPrimInt:      // Fall-through.
576    case Primitive::kPrimFloat:
577      sf_->SetVReg(cur_reg_, *reinterpret_cast<jint*>(GetParamAddress()));
578      break;
579    case Primitive::kPrimVoid:
580      LOG(FATAL) << "UNREACHABLE";
581      UNREACHABLE();
582  }
583  ++cur_reg_;
584}
585
586extern "C" uint64_t artQuickToInterpreterBridge(mirror::ArtMethod* method, Thread* self,
587                                                StackReference<mirror::ArtMethod>* sp)
588    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
589  // Ensure we don't get thread suspension until the object arguments are safely in the shadow
590  // frame.
591  ScopedQuickEntrypointChecks sqec(self);
592
593  if (method->IsAbstract()) {
594    ThrowAbstractMethodError(method);
595    return 0;
596  } else {
597    DCHECK(!method->IsNative()) << PrettyMethod(method);
598    const char* old_cause = self->StartAssertNoThreadSuspension(
599        "Building interpreter shadow frame");
600    const DexFile::CodeItem* code_item = method->GetCodeItem();
601    DCHECK(code_item != nullptr) << PrettyMethod(method);
602    uint16_t num_regs = code_item->registers_size_;
603    void* memory = alloca(ShadowFrame::ComputeSize(num_regs));
604    // No last shadow coming from quick.
605    ShadowFrame* shadow_frame(ShadowFrame::Create(num_regs, nullptr, method, 0, memory));
606    size_t first_arg_reg = code_item->registers_size_ - code_item->ins_size_;
607    uint32_t shorty_len = 0;
608    const char* shorty = method->GetShorty(&shorty_len);
609    BuildQuickShadowFrameVisitor shadow_frame_builder(sp, method->IsStatic(), shorty, shorty_len,
610                                                      shadow_frame, first_arg_reg);
611    shadow_frame_builder.VisitArguments();
612    const bool needs_initialization =
613        method->IsStatic() && !method->GetDeclaringClass()->IsInitialized();
614    // Push a transition back into managed code onto the linked list in thread.
615    ManagedStack fragment;
616    self->PushManagedStackFragment(&fragment);
617    self->PushShadowFrame(shadow_frame);
618    self->EndAssertNoThreadSuspension(old_cause);
619
620    if (needs_initialization) {
621      // Ensure static method's class is initialized.
622      StackHandleScope<1> hs(self);
623      Handle<mirror::Class> h_class(hs.NewHandle(shadow_frame->GetMethod()->GetDeclaringClass()));
624      if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
625        DCHECK(Thread::Current()->IsExceptionPending()) << PrettyMethod(shadow_frame->GetMethod());
626        self->PopManagedStackFragment(fragment);
627        return 0;
628      }
629    }
630    JValue result = interpreter::EnterInterpreterFromEntryPoint(self, code_item, shadow_frame);
631    // Pop transition.
632    self->PopManagedStackFragment(fragment);
633    // No need to restore the args since the method has already been run by the interpreter.
634    return result.GetJ();
635  }
636}
637
638// Visits arguments on the stack placing them into the args vector, Object* arguments are converted
639// to jobjects.
640class BuildQuickArgumentVisitor FINAL : public QuickArgumentVisitor {
641 public:
642  BuildQuickArgumentVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static,
643                            const char* shorty, uint32_t shorty_len,
644                            ScopedObjectAccessUnchecked* soa, std::vector<jvalue>* args) :
645      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa), args_(args) {}
646
647  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
648
649  void FixupReferences() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
650
651 private:
652  ScopedObjectAccessUnchecked* const soa_;
653  std::vector<jvalue>* const args_;
654  // References which we must update when exiting in case the GC moved the objects.
655  std::vector<std::pair<jobject, StackReference<mirror::Object>*>> references_;
656
657  DISALLOW_COPY_AND_ASSIGN(BuildQuickArgumentVisitor);
658};
659
660void BuildQuickArgumentVisitor::Visit() {
661  jvalue val;
662  Primitive::Type type = GetParamPrimitiveType();
663  switch (type) {
664    case Primitive::kPrimNot: {
665      StackReference<mirror::Object>* stack_ref =
666          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
667      val.l = soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
668      references_.push_back(std::make_pair(val.l, stack_ref));
669      break;
670    }
671    case Primitive::kPrimLong:  // Fall-through.
672    case Primitive::kPrimDouble:
673      if (IsSplitLongOrDouble()) {
674        val.j = ReadSplitLongParam();
675      } else {
676        val.j = *reinterpret_cast<jlong*>(GetParamAddress());
677      }
678      break;
679    case Primitive::kPrimBoolean:  // Fall-through.
680    case Primitive::kPrimByte:     // Fall-through.
681    case Primitive::kPrimChar:     // Fall-through.
682    case Primitive::kPrimShort:    // Fall-through.
683    case Primitive::kPrimInt:      // Fall-through.
684    case Primitive::kPrimFloat:
685      val.i = *reinterpret_cast<jint*>(GetParamAddress());
686      break;
687    case Primitive::kPrimVoid:
688      LOG(FATAL) << "UNREACHABLE";
689      UNREACHABLE();
690  }
691  args_->push_back(val);
692}
693
694void BuildQuickArgumentVisitor::FixupReferences() {
695  // Fixup any references which may have changed.
696  for (const auto& pair : references_) {
697    pair.second->Assign(soa_->Decode<mirror::Object*>(pair.first));
698    soa_->Env()->DeleteLocalRef(pair.first);
699  }
700}
701
702// Handler for invocation on proxy methods. On entry a frame will exist for the proxy object method
703// which is responsible for recording callee save registers. We explicitly place into jobjects the
704// incoming reference arguments (so they survive GC). We invoke the invocation handler, which is a
705// field within the proxy object, which will box the primitive arguments and deal with error cases.
706extern "C" uint64_t artQuickProxyInvokeHandler(mirror::ArtMethod* proxy_method,
707                                               mirror::Object* receiver,
708                                               Thread* self, StackReference<mirror::ArtMethod>* sp)
709    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
710  DCHECK(proxy_method->IsProxyMethod()) << PrettyMethod(proxy_method);
711  DCHECK(receiver->GetClass()->IsProxyClass()) << PrettyMethod(proxy_method);
712  // Ensure we don't get thread suspension until the object arguments are safely in jobjects.
713  const char* old_cause =
714      self->StartAssertNoThreadSuspension("Adding to IRT proxy object arguments");
715  // Register the top of the managed stack, making stack crawlable.
716  DCHECK_EQ(sp->AsMirrorPtr(), proxy_method) << PrettyMethod(proxy_method);
717  DCHECK_EQ(proxy_method->GetFrameSizeInBytes(),
718            Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs)->GetFrameSizeInBytes())
719      << PrettyMethod(proxy_method);
720  self->VerifyStack();
721  // Start new JNI local reference state.
722  JNIEnvExt* env = self->GetJniEnv();
723  ScopedObjectAccessUnchecked soa(env);
724  ScopedJniEnvLocalRefState env_state(env);
725  // Create local ref. copies of proxy method and the receiver.
726  jobject rcvr_jobj = soa.AddLocalReference<jobject>(receiver);
727
728  // Placing arguments into args vector and remove the receiver.
729  mirror::ArtMethod* non_proxy_method = proxy_method->GetInterfaceMethodIfProxy();
730  CHECK(!non_proxy_method->IsStatic()) << PrettyMethod(proxy_method) << " "
731                                       << PrettyMethod(non_proxy_method);
732  std::vector<jvalue> args;
733  uint32_t shorty_len = 0;
734  const char* shorty = proxy_method->GetShorty(&shorty_len);
735  BuildQuickArgumentVisitor local_ref_visitor(sp, false, shorty, shorty_len, &soa, &args);
736
737  local_ref_visitor.VisitArguments();
738  DCHECK_GT(args.size(), 0U) << PrettyMethod(proxy_method);
739  args.erase(args.begin());
740
741  // Convert proxy method into expected interface method.
742  mirror::ArtMethod* interface_method = proxy_method->FindOverriddenMethod();
743  DCHECK(interface_method != nullptr) << PrettyMethod(proxy_method);
744  DCHECK(!interface_method->IsProxyMethod()) << PrettyMethod(interface_method);
745  jobject interface_method_jobj = soa.AddLocalReference<jobject>(interface_method);
746
747  // All naked Object*s should now be in jobjects, so its safe to go into the main invoke code
748  // that performs allocations.
749  self->EndAssertNoThreadSuspension(old_cause);
750  JValue result = InvokeProxyInvocationHandler(soa, shorty, rcvr_jobj, interface_method_jobj, args);
751  // Restore references which might have moved.
752  local_ref_visitor.FixupReferences();
753  return result.GetJ();
754}
755
756// Read object references held in arguments from quick frames and place in a JNI local references,
757// so they don't get garbage collected.
758class RememberForGcArgumentVisitor FINAL : public QuickArgumentVisitor {
759 public:
760  RememberForGcArgumentVisitor(StackReference<mirror::ArtMethod>* sp, bool is_static,
761                               const char* shorty, uint32_t shorty_len,
762                               ScopedObjectAccessUnchecked* soa) :
763      QuickArgumentVisitor(sp, is_static, shorty, shorty_len), soa_(soa) {}
764
765  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
766
767  void FixupReferences() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
768
769 private:
770  ScopedObjectAccessUnchecked* const soa_;
771  // References which we must update when exiting in case the GC moved the objects.
772  std::vector<std::pair<jobject, StackReference<mirror::Object>*> > references_;
773
774  DISALLOW_COPY_AND_ASSIGN(RememberForGcArgumentVisitor);
775};
776
777void RememberForGcArgumentVisitor::Visit() {
778  if (IsParamAReference()) {
779    StackReference<mirror::Object>* stack_ref =
780        reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
781    jobject reference =
782        soa_->AddLocalReference<jobject>(stack_ref->AsMirrorPtr());
783    references_.push_back(std::make_pair(reference, stack_ref));
784  }
785}
786
787void RememberForGcArgumentVisitor::FixupReferences() {
788  // Fixup any references which may have changed.
789  for (const auto& pair : references_) {
790    pair.second->Assign(soa_->Decode<mirror::Object*>(pair.first));
791    soa_->Env()->DeleteLocalRef(pair.first);
792  }
793}
794
795// Lazily resolve a method for quick. Called by stub code.
796extern "C" const void* artQuickResolutionTrampoline(mirror::ArtMethod* called,
797                                                    mirror::Object* receiver,
798                                                    Thread* self,
799                                                    StackReference<mirror::ArtMethod>* sp)
800    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
801  ScopedQuickEntrypointChecks sqec(self);
802  // Start new JNI local reference state
803  JNIEnvExt* env = self->GetJniEnv();
804  ScopedObjectAccessUnchecked soa(env);
805  ScopedJniEnvLocalRefState env_state(env);
806  const char* old_cause = self->StartAssertNoThreadSuspension("Quick method resolution set up");
807
808  // Compute details about the called method (avoid GCs)
809  ClassLinker* linker = Runtime::Current()->GetClassLinker();
810  mirror::ArtMethod* caller = QuickArgumentVisitor::GetCallingMethod(sp);
811  InvokeType invoke_type;
812  MethodReference called_method(nullptr, 0);
813  const bool called_method_known_on_entry = !called->IsRuntimeMethod();
814  if (!called_method_known_on_entry) {
815    uint32_t dex_pc = caller->ToDexPc(QuickArgumentVisitor::GetCallingPc(sp));
816    const DexFile::CodeItem* code;
817    called_method.dex_file = caller->GetDexFile();
818    code = caller->GetCodeItem();
819    CHECK_LT(dex_pc, code->insns_size_in_code_units_);
820    const Instruction* instr = Instruction::At(&code->insns_[dex_pc]);
821    Instruction::Code instr_code = instr->Opcode();
822    bool is_range;
823    switch (instr_code) {
824      case Instruction::INVOKE_DIRECT:
825        invoke_type = kDirect;
826        is_range = false;
827        break;
828      case Instruction::INVOKE_DIRECT_RANGE:
829        invoke_type = kDirect;
830        is_range = true;
831        break;
832      case Instruction::INVOKE_STATIC:
833        invoke_type = kStatic;
834        is_range = false;
835        break;
836      case Instruction::INVOKE_STATIC_RANGE:
837        invoke_type = kStatic;
838        is_range = true;
839        break;
840      case Instruction::INVOKE_SUPER:
841        invoke_type = kSuper;
842        is_range = false;
843        break;
844      case Instruction::INVOKE_SUPER_RANGE:
845        invoke_type = kSuper;
846        is_range = true;
847        break;
848      case Instruction::INVOKE_VIRTUAL:
849        invoke_type = kVirtual;
850        is_range = false;
851        break;
852      case Instruction::INVOKE_VIRTUAL_RANGE:
853        invoke_type = kVirtual;
854        is_range = true;
855        break;
856      case Instruction::INVOKE_INTERFACE:
857        invoke_type = kInterface;
858        is_range = false;
859        break;
860      case Instruction::INVOKE_INTERFACE_RANGE:
861        invoke_type = kInterface;
862        is_range = true;
863        break;
864      default:
865        LOG(FATAL) << "Unexpected call into trampoline: " << instr->DumpString(nullptr);
866        UNREACHABLE();
867    }
868    called_method.dex_method_index = (is_range) ? instr->VRegB_3rc() : instr->VRegB_35c();
869  } else {
870    invoke_type = kStatic;
871    called_method.dex_file = called->GetDexFile();
872    called_method.dex_method_index = called->GetDexMethodIndex();
873  }
874  uint32_t shorty_len;
875  const char* shorty =
876      called_method.dex_file->GetMethodShorty(
877          called_method.dex_file->GetMethodId(called_method.dex_method_index), &shorty_len);
878  RememberForGcArgumentVisitor visitor(sp, invoke_type == kStatic, shorty, shorty_len, &soa);
879  visitor.VisitArguments();
880  self->EndAssertNoThreadSuspension(old_cause);
881  const bool virtual_or_interface = invoke_type == kVirtual || invoke_type == kInterface;
882  // Resolve method filling in dex cache.
883  if (!called_method_known_on_entry) {
884    StackHandleScope<1> hs(self);
885    mirror::Object* dummy = nullptr;
886    HandleWrapper<mirror::Object> h_receiver(
887        hs.NewHandleWrapper(virtual_or_interface ? &receiver : &dummy));
888    DCHECK_EQ(caller->GetDexFile(), called_method.dex_file);
889    called = linker->ResolveMethod(self, called_method.dex_method_index, &caller, invoke_type);
890  }
891  const void* code = nullptr;
892  if (LIKELY(!self->IsExceptionPending())) {
893    // Incompatible class change should have been handled in resolve method.
894    CHECK(!called->CheckIncompatibleClassChange(invoke_type))
895        << PrettyMethod(called) << " " << invoke_type;
896    if (virtual_or_interface) {
897      // Refine called method based on receiver.
898      CHECK(receiver != nullptr) << invoke_type;
899
900      mirror::ArtMethod* orig_called = called;
901      if (invoke_type == kVirtual) {
902        called = receiver->GetClass()->FindVirtualMethodForVirtual(called);
903      } else {
904        called = receiver->GetClass()->FindVirtualMethodForInterface(called);
905      }
906
907      CHECK(called != nullptr) << PrettyMethod(orig_called) << " "
908                               << PrettyTypeOf(receiver) << " "
909                               << invoke_type << " " << orig_called->GetVtableIndex();
910
911      // We came here because of sharpening. Ensure the dex cache is up-to-date on the method index
912      // of the sharpened method avoiding dirtying the dex cache if possible.
913      // Note, called_method.dex_method_index references the dex method before the
914      // FindVirtualMethodFor... This is ok for FindDexMethodIndexInOtherDexFile that only cares
915      // about the name and signature.
916      uint32_t update_dex_cache_method_index = called->GetDexMethodIndex();
917      if (!called->HasSameDexCacheResolvedMethods(caller)) {
918        // Calling from one dex file to another, need to compute the method index appropriate to
919        // the caller's dex file. Since we get here only if the original called was a runtime
920        // method, we've got the correct dex_file and a dex_method_idx from above.
921        DCHECK(!called_method_known_on_entry);
922        DCHECK_EQ(caller->GetDexFile(), called_method.dex_file);
923        const DexFile* caller_dex_file = called_method.dex_file;
924        uint32_t caller_method_name_and_sig_index = called_method.dex_method_index;
925        update_dex_cache_method_index =
926            called->FindDexMethodIndexInOtherDexFile(*caller_dex_file,
927                                                     caller_method_name_and_sig_index);
928      }
929      if ((update_dex_cache_method_index != DexFile::kDexNoIndex) &&
930          (caller->GetDexCacheResolvedMethod(update_dex_cache_method_index) != called)) {
931        caller->SetDexCacheResolvedMethod(update_dex_cache_method_index, called);
932      }
933    }
934    // Ensure that the called method's class is initialized.
935    StackHandleScope<1> hs(soa.Self());
936    Handle<mirror::Class> called_class(hs.NewHandle(called->GetDeclaringClass()));
937    linker->EnsureInitialized(soa.Self(), called_class, true, true);
938    if (LIKELY(called_class->IsInitialized())) {
939      code = called->GetEntryPointFromQuickCompiledCode();
940    } else if (called_class->IsInitializing()) {
941      if (invoke_type == kStatic) {
942        // Class is still initializing, go to oat and grab code (trampoline must be left in place
943        // until class is initialized to stop races between threads).
944        code = linker->GetQuickOatCodeFor(called);
945      } else {
946        // No trampoline for non-static methods.
947        code = called->GetEntryPointFromQuickCompiledCode();
948      }
949    } else {
950      DCHECK(called_class->IsErroneous());
951    }
952  }
953  CHECK_EQ(code == nullptr, self->IsExceptionPending());
954  // Fixup any locally saved objects may have moved during a GC.
955  visitor.FixupReferences();
956  // Place called method in callee-save frame to be placed as first argument to quick method.
957  sp->Assign(called);
958  return code;
959}
960
961/*
962 * This class uses a couple of observations to unite the different calling conventions through
963 * a few constants.
964 *
965 * 1) Number of registers used for passing is normally even, so counting down has no penalty for
966 *    possible alignment.
967 * 2) Known 64b architectures store 8B units on the stack, both for integral and floating point
968 *    types, so using uintptr_t is OK. Also means that we can use kRegistersNeededX to denote
969 *    when we have to split things
970 * 3) The only soft-float, Arm, is 32b, so no widening needs to be taken into account for floats
971 *    and we can use Int handling directly.
972 * 4) Only 64b architectures widen, and their stack is aligned 8B anyways, so no padding code
973 *    necessary when widening. Also, widening of Ints will take place implicitly, and the
974 *    extension should be compatible with Aarch64, which mandates copying the available bits
975 *    into LSB and leaving the rest unspecified.
976 * 5) Aligning longs and doubles is necessary on arm only, and it's the same in registers and on
977 *    the stack.
978 * 6) There is only little endian.
979 *
980 *
981 * Actual work is supposed to be done in a delegate of the template type. The interface is as
982 * follows:
983 *
984 * void PushGpr(uintptr_t):   Add a value for the next GPR
985 *
986 * void PushFpr4(float):      Add a value for the next FPR of size 32b. Is only called if we need
987 *                            padding, that is, think the architecture is 32b and aligns 64b.
988 *
989 * void PushFpr8(uint64_t):   Push a double. We _will_ call this on 32b, it's the callee's job to
990 *                            split this if necessary. The current state will have aligned, if
991 *                            necessary.
992 *
993 * void PushStack(uintptr_t): Push a value to the stack.
994 *
995 * uintptr_t PushHandleScope(mirror::Object* ref): Add a reference to the HandleScope. This _will_ have nullptr,
996 *                                          as this might be important for null initialization.
997 *                                          Must return the jobject, that is, the reference to the
998 *                                          entry in the HandleScope (nullptr if necessary).
999 *
1000 */
1001template<class T> class BuildNativeCallFrameStateMachine {
1002 public:
1003#if defined(__arm__)
1004  // TODO: These are all dummy values!
1005  static constexpr bool kNativeSoftFloatAbi = true;
1006  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs, r0-r3
1007  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1008
1009  static constexpr size_t kRegistersNeededForLong = 2;
1010  static constexpr size_t kRegistersNeededForDouble = 2;
1011  static constexpr bool kMultiRegistersAligned = true;
1012  static constexpr bool kMultiFPRegistersWidened = false;
1013  static constexpr bool kMultiGPRegistersWidened = false;
1014  static constexpr bool kAlignLongOnStack = true;
1015  static constexpr bool kAlignDoubleOnStack = true;
1016#elif defined(__aarch64__)
1017  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1018  static constexpr size_t kNumNativeGprArgs = 8;  // 6 arguments passed in GPRs.
1019  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1020
1021  static constexpr size_t kRegistersNeededForLong = 1;
1022  static constexpr size_t kRegistersNeededForDouble = 1;
1023  static constexpr bool kMultiRegistersAligned = false;
1024  static constexpr bool kMultiFPRegistersWidened = false;
1025  static constexpr bool kMultiGPRegistersWidened = false;
1026  static constexpr bool kAlignLongOnStack = false;
1027  static constexpr bool kAlignDoubleOnStack = false;
1028#elif defined(__mips__) && !defined(__LP64__)
1029  static constexpr bool kNativeSoftFloatAbi = true;  // This is a hard float ABI.
1030  static constexpr size_t kNumNativeGprArgs = 4;  // 4 arguments passed in GPRs.
1031  static constexpr size_t kNumNativeFprArgs = 0;  // 0 arguments passed in FPRs.
1032
1033  static constexpr size_t kRegistersNeededForLong = 2;
1034  static constexpr size_t kRegistersNeededForDouble = 2;
1035  static constexpr bool kMultiRegistersAligned = true;
1036  static constexpr bool kMultiFPRegistersWidened = true;
1037  static constexpr bool kMultiGPRegistersWidened = false;
1038  static constexpr bool kAlignLongOnStack = true;
1039  static constexpr bool kAlignDoubleOnStack = true;
1040#elif defined(__mips__) && defined(__LP64__)
1041  // Let the code prepare GPRs only and we will load the FPRs with same data.
1042  static constexpr bool kNativeSoftFloatAbi = true;
1043  static constexpr size_t kNumNativeGprArgs = 8;
1044  static constexpr size_t kNumNativeFprArgs = 0;
1045
1046  static constexpr size_t kRegistersNeededForLong = 1;
1047  static constexpr size_t kRegistersNeededForDouble = 1;
1048  static constexpr bool kMultiRegistersAligned = false;
1049  static constexpr bool kMultiFPRegistersWidened = false;
1050  static constexpr bool kMultiGPRegistersWidened = true;
1051  static constexpr bool kAlignLongOnStack = false;
1052  static constexpr bool kAlignDoubleOnStack = false;
1053#elif defined(__i386__)
1054  // TODO: Check these!
1055  static constexpr bool kNativeSoftFloatAbi = false;  // Not using int registers for fp
1056  static constexpr size_t kNumNativeGprArgs = 0;  // 6 arguments passed in GPRs.
1057  static constexpr size_t kNumNativeFprArgs = 0;  // 8 arguments passed in FPRs.
1058
1059  static constexpr size_t kRegistersNeededForLong = 2;
1060  static constexpr size_t kRegistersNeededForDouble = 2;
1061  static constexpr bool kMultiRegistersAligned = false;  // x86 not using regs, anyways
1062  static constexpr bool kMultiFPRegistersWidened = false;
1063  static constexpr bool kMultiGPRegistersWidened = false;
1064  static constexpr bool kAlignLongOnStack = false;
1065  static constexpr bool kAlignDoubleOnStack = false;
1066#elif defined(__x86_64__)
1067  static constexpr bool kNativeSoftFloatAbi = false;  // This is a hard float ABI.
1068  static constexpr size_t kNumNativeGprArgs = 6;  // 6 arguments passed in GPRs.
1069  static constexpr size_t kNumNativeFprArgs = 8;  // 8 arguments passed in FPRs.
1070
1071  static constexpr size_t kRegistersNeededForLong = 1;
1072  static constexpr size_t kRegistersNeededForDouble = 1;
1073  static constexpr bool kMultiRegistersAligned = false;
1074  static constexpr bool kMultiFPRegistersWidened = false;
1075  static constexpr bool kMultiGPRegistersWidened = false;
1076  static constexpr bool kAlignLongOnStack = false;
1077  static constexpr bool kAlignDoubleOnStack = false;
1078#else
1079#error "Unsupported architecture"
1080#endif
1081
1082 public:
1083  explicit BuildNativeCallFrameStateMachine(T* delegate)
1084      : gpr_index_(kNumNativeGprArgs),
1085        fpr_index_(kNumNativeFprArgs),
1086        stack_entries_(0),
1087        delegate_(delegate) {
1088    // For register alignment, we want to assume that counters (gpr_index_, fpr_index_) are even iff
1089    // the next register is even; counting down is just to make the compiler happy...
1090    static_assert(kNumNativeGprArgs % 2 == 0U, "Number of native GPR arguments not even");
1091    static_assert(kNumNativeFprArgs % 2 == 0U, "Number of native FPR arguments not even");
1092  }
1093
1094  virtual ~BuildNativeCallFrameStateMachine() {}
1095
1096  bool HavePointerGpr() const {
1097    return gpr_index_ > 0;
1098  }
1099
1100  void AdvancePointer(const void* val) {
1101    if (HavePointerGpr()) {
1102      gpr_index_--;
1103      PushGpr(reinterpret_cast<uintptr_t>(val));
1104    } else {
1105      stack_entries_++;  // TODO: have a field for pointer length as multiple of 32b
1106      PushStack(reinterpret_cast<uintptr_t>(val));
1107      gpr_index_ = 0;
1108    }
1109  }
1110
1111  bool HaveHandleScopeGpr() const {
1112    return gpr_index_ > 0;
1113  }
1114
1115  void AdvanceHandleScope(mirror::Object* ptr) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1116    uintptr_t handle = PushHandle(ptr);
1117    if (HaveHandleScopeGpr()) {
1118      gpr_index_--;
1119      PushGpr(handle);
1120    } else {
1121      stack_entries_++;
1122      PushStack(handle);
1123      gpr_index_ = 0;
1124    }
1125  }
1126
1127  bool HaveIntGpr() const {
1128    return gpr_index_ > 0;
1129  }
1130
1131  void AdvanceInt(uint32_t val) {
1132    if (HaveIntGpr()) {
1133      gpr_index_--;
1134      if (kMultiGPRegistersWidened) {
1135        DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1136        PushGpr(static_cast<int64_t>(bit_cast<uint32_t, int32_t>(val)));
1137      } else {
1138        PushGpr(val);
1139      }
1140    } else {
1141      stack_entries_++;
1142      if (kMultiGPRegistersWidened) {
1143        DCHECK_EQ(sizeof(uintptr_t), sizeof(int64_t));
1144        PushStack(static_cast<int64_t>(bit_cast<uint32_t, int32_t>(val)));
1145      } else {
1146        PushStack(val);
1147      }
1148      gpr_index_ = 0;
1149    }
1150  }
1151
1152  bool HaveLongGpr() const {
1153    return gpr_index_ >= kRegistersNeededForLong + (LongGprNeedsPadding() ? 1 : 0);
1154  }
1155
1156  bool LongGprNeedsPadding() const {
1157    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1158        kAlignLongOnStack &&                  // and when it needs alignment
1159        (gpr_index_ & 1) == 1;                // counter is odd, see constructor
1160  }
1161
1162  bool LongStackNeedsPadding() const {
1163    return kRegistersNeededForLong > 1 &&     // only pad when using multiple registers
1164        kAlignLongOnStack &&                  // and when it needs 8B alignment
1165        (stack_entries_ & 1) == 1;            // counter is odd
1166  }
1167
1168  void AdvanceLong(uint64_t val) {
1169    if (HaveLongGpr()) {
1170      if (LongGprNeedsPadding()) {
1171        PushGpr(0);
1172        gpr_index_--;
1173      }
1174      if (kRegistersNeededForLong == 1) {
1175        PushGpr(static_cast<uintptr_t>(val));
1176      } else {
1177        PushGpr(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1178        PushGpr(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1179      }
1180      gpr_index_ -= kRegistersNeededForLong;
1181    } else {
1182      if (LongStackNeedsPadding()) {
1183        PushStack(0);
1184        stack_entries_++;
1185      }
1186      if (kRegistersNeededForLong == 1) {
1187        PushStack(static_cast<uintptr_t>(val));
1188        stack_entries_++;
1189      } else {
1190        PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1191        PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1192        stack_entries_ += 2;
1193      }
1194      gpr_index_ = 0;
1195    }
1196  }
1197
1198  bool HaveFloatFpr() const {
1199    return fpr_index_ > 0;
1200  }
1201
1202  void AdvanceFloat(float val) {
1203    if (kNativeSoftFloatAbi) {
1204      AdvanceInt(bit_cast<float, uint32_t>(val));
1205    } else {
1206      if (HaveFloatFpr()) {
1207        fpr_index_--;
1208        if (kRegistersNeededForDouble == 1) {
1209          if (kMultiFPRegistersWidened) {
1210            PushFpr8(bit_cast<double, uint64_t>(val));
1211          } else {
1212            // No widening, just use the bits.
1213            PushFpr8(bit_cast<float, uint64_t>(val));
1214          }
1215        } else {
1216          PushFpr4(val);
1217        }
1218      } else {
1219        stack_entries_++;
1220        if (kRegistersNeededForDouble == 1 && kMultiFPRegistersWidened) {
1221          // Need to widen before storing: Note the "double" in the template instantiation.
1222          // Note: We need to jump through those hoops to make the compiler happy.
1223          DCHECK_EQ(sizeof(uintptr_t), sizeof(uint64_t));
1224          PushStack(static_cast<uintptr_t>(bit_cast<double, uint64_t>(val)));
1225        } else {
1226          PushStack(bit_cast<float, uintptr_t>(val));
1227        }
1228        fpr_index_ = 0;
1229      }
1230    }
1231  }
1232
1233  bool HaveDoubleFpr() const {
1234    return fpr_index_ >= kRegistersNeededForDouble + (DoubleFprNeedsPadding() ? 1 : 0);
1235  }
1236
1237  bool DoubleFprNeedsPadding() const {
1238    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1239        kAlignDoubleOnStack &&                  // and when it needs alignment
1240        (fpr_index_ & 1) == 1;                  // counter is odd, see constructor
1241  }
1242
1243  bool DoubleStackNeedsPadding() const {
1244    return kRegistersNeededForDouble > 1 &&     // only pad when using multiple registers
1245        kAlignDoubleOnStack &&                  // and when it needs 8B alignment
1246        (stack_entries_ & 1) == 1;              // counter is odd
1247  }
1248
1249  void AdvanceDouble(uint64_t val) {
1250    if (kNativeSoftFloatAbi) {
1251      AdvanceLong(val);
1252    } else {
1253      if (HaveDoubleFpr()) {
1254        if (DoubleFprNeedsPadding()) {
1255          PushFpr4(0);
1256          fpr_index_--;
1257        }
1258        PushFpr8(val);
1259        fpr_index_ -= kRegistersNeededForDouble;
1260      } else {
1261        if (DoubleStackNeedsPadding()) {
1262          PushStack(0);
1263          stack_entries_++;
1264        }
1265        if (kRegistersNeededForDouble == 1) {
1266          PushStack(static_cast<uintptr_t>(val));
1267          stack_entries_++;
1268        } else {
1269          PushStack(static_cast<uintptr_t>(val & 0xFFFFFFFF));
1270          PushStack(static_cast<uintptr_t>((val >> 32) & 0xFFFFFFFF));
1271          stack_entries_ += 2;
1272        }
1273        fpr_index_ = 0;
1274      }
1275    }
1276  }
1277
1278  uint32_t GetStackEntries() const {
1279    return stack_entries_;
1280  }
1281
1282  uint32_t GetNumberOfUsedGprs() const {
1283    return kNumNativeGprArgs - gpr_index_;
1284  }
1285
1286  uint32_t GetNumberOfUsedFprs() const {
1287    return kNumNativeFprArgs - fpr_index_;
1288  }
1289
1290 private:
1291  void PushGpr(uintptr_t val) {
1292    delegate_->PushGpr(val);
1293  }
1294  void PushFpr4(float val) {
1295    delegate_->PushFpr4(val);
1296  }
1297  void PushFpr8(uint64_t val) {
1298    delegate_->PushFpr8(val);
1299  }
1300  void PushStack(uintptr_t val) {
1301    delegate_->PushStack(val);
1302  }
1303  uintptr_t PushHandle(mirror::Object* ref) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1304    return delegate_->PushHandle(ref);
1305  }
1306
1307  uint32_t gpr_index_;      // Number of free GPRs
1308  uint32_t fpr_index_;      // Number of free FPRs
1309  uint32_t stack_entries_;  // Stack entries are in multiples of 32b, as floats are usually not
1310                            // extended
1311  T* const delegate_;             // What Push implementation gets called
1312};
1313
1314// Computes the sizes of register stacks and call stack area. Handling of references can be extended
1315// in subclasses.
1316//
1317// To handle native pointers, use "L" in the shorty for an object reference, which simulates
1318// them with handles.
1319class ComputeNativeCallFrameSize {
1320 public:
1321  ComputeNativeCallFrameSize() : num_stack_entries_(0) {}
1322
1323  virtual ~ComputeNativeCallFrameSize() {}
1324
1325  uint32_t GetStackSize() const {
1326    return num_stack_entries_ * sizeof(uintptr_t);
1327  }
1328
1329  uint8_t* LayoutCallStack(uint8_t* sp8) const {
1330    sp8 -= GetStackSize();
1331    // Align by kStackAlignment.
1332    sp8 = reinterpret_cast<uint8_t*>(RoundDown(reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1333    return sp8;
1334  }
1335
1336  uint8_t* LayoutCallRegisterStacks(uint8_t* sp8, uintptr_t** start_gpr, uint32_t** start_fpr)
1337      const {
1338    // Assumption is OK right now, as we have soft-float arm
1339    size_t fregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeFprArgs;
1340    sp8 -= fregs * sizeof(uintptr_t);
1341    *start_fpr = reinterpret_cast<uint32_t*>(sp8);
1342    size_t iregs = BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>::kNumNativeGprArgs;
1343    sp8 -= iregs * sizeof(uintptr_t);
1344    *start_gpr = reinterpret_cast<uintptr_t*>(sp8);
1345    return sp8;
1346  }
1347
1348  uint8_t* LayoutNativeCall(uint8_t* sp8, uintptr_t** start_stack, uintptr_t** start_gpr,
1349                            uint32_t** start_fpr) const {
1350    // Native call stack.
1351    sp8 = LayoutCallStack(sp8);
1352    *start_stack = reinterpret_cast<uintptr_t*>(sp8);
1353
1354    // Put fprs and gprs below.
1355    sp8 = LayoutCallRegisterStacks(sp8, start_gpr, start_fpr);
1356
1357    // Return the new bottom.
1358    return sp8;
1359  }
1360
1361  virtual void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm)
1362      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1363    UNUSED(sm);
1364  }
1365
1366  void Walk(const char* shorty, uint32_t shorty_len) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1367    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize> sm(this);
1368
1369    WalkHeader(&sm);
1370
1371    for (uint32_t i = 1; i < shorty_len; ++i) {
1372      Primitive::Type cur_type_ = Primitive::GetType(shorty[i]);
1373      switch (cur_type_) {
1374        case Primitive::kPrimNot:
1375          // TODO: fix abuse of mirror types.
1376          sm.AdvanceHandleScope(
1377              reinterpret_cast<mirror::Object*>(0x12345678));
1378          break;
1379
1380        case Primitive::kPrimBoolean:
1381        case Primitive::kPrimByte:
1382        case Primitive::kPrimChar:
1383        case Primitive::kPrimShort:
1384        case Primitive::kPrimInt:
1385          sm.AdvanceInt(0);
1386          break;
1387        case Primitive::kPrimFloat:
1388          sm.AdvanceFloat(0);
1389          break;
1390        case Primitive::kPrimDouble:
1391          sm.AdvanceDouble(0);
1392          break;
1393        case Primitive::kPrimLong:
1394          sm.AdvanceLong(0);
1395          break;
1396        default:
1397          LOG(FATAL) << "Unexpected type: " << cur_type_ << " in " << shorty;
1398          UNREACHABLE();
1399      }
1400    }
1401
1402    num_stack_entries_ = sm.GetStackEntries();
1403  }
1404
1405  void PushGpr(uintptr_t /* val */) {
1406    // not optimizing registers, yet
1407  }
1408
1409  void PushFpr4(float /* val */) {
1410    // not optimizing registers, yet
1411  }
1412
1413  void PushFpr8(uint64_t /* val */) {
1414    // not optimizing registers, yet
1415  }
1416
1417  void PushStack(uintptr_t /* val */) {
1418    // counting is already done in the superclass
1419  }
1420
1421  virtual uintptr_t PushHandle(mirror::Object* /* ptr */) {
1422    return reinterpret_cast<uintptr_t>(nullptr);
1423  }
1424
1425 protected:
1426  uint32_t num_stack_entries_;
1427};
1428
1429class ComputeGenericJniFrameSize FINAL : public ComputeNativeCallFrameSize {
1430 public:
1431  ComputeGenericJniFrameSize() : num_handle_scope_references_(0) {}
1432
1433  // Lays out the callee-save frame. Assumes that the incorrect frame corresponding to RefsAndArgs
1434  // is at *m = sp. Will update to point to the bottom of the save frame.
1435  //
1436  // Note: assumes ComputeAll() has been run before.
1437  void LayoutCalleeSaveFrame(Thread* self, StackReference<mirror::ArtMethod>** m, void* sp,
1438                             HandleScope** handle_scope)
1439      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1440    mirror::ArtMethod* method = (*m)->AsMirrorPtr();
1441
1442    uint8_t* sp8 = reinterpret_cast<uint8_t*>(sp);
1443
1444    // First, fix up the layout of the callee-save frame.
1445    // We have to squeeze in the HandleScope, and relocate the method pointer.
1446
1447    // "Free" the slot for the method.
1448    sp8 += sizeof(void*);  // In the callee-save frame we use a full pointer.
1449
1450    // Under the callee saves put handle scope and new method stack reference.
1451    size_t handle_scope_size = HandleScope::SizeOf(num_handle_scope_references_);
1452    size_t scope_and_method = handle_scope_size + sizeof(StackReference<mirror::ArtMethod>);
1453
1454    sp8 -= scope_and_method;
1455    // Align by kStackAlignment.
1456    sp8 = reinterpret_cast<uint8_t*>(RoundDown(
1457        reinterpret_cast<uintptr_t>(sp8), kStackAlignment));
1458
1459    uint8_t* sp8_table = sp8 + sizeof(StackReference<mirror::ArtMethod>);
1460    *handle_scope = HandleScope::Create(sp8_table, self->GetTopHandleScope(),
1461                                        num_handle_scope_references_);
1462
1463    // Add a slot for the method pointer, and fill it. Fix the pointer-pointer given to us.
1464    uint8_t* method_pointer = sp8;
1465    StackReference<mirror::ArtMethod>* new_method_ref =
1466        reinterpret_cast<StackReference<mirror::ArtMethod>*>(method_pointer);
1467    new_method_ref->Assign(method);
1468    *m = new_method_ref;
1469  }
1470
1471  // Adds space for the cookie. Note: may leave stack unaligned.
1472  void LayoutCookie(uint8_t** sp) const {
1473    // Reference cookie and padding
1474    *sp -= 8;
1475  }
1476
1477  // Re-layout the callee-save frame (insert a handle-scope). Then add space for the cookie.
1478  // Returns the new bottom. Note: this may be unaligned.
1479  uint8_t* LayoutJNISaveFrame(Thread* self, StackReference<mirror::ArtMethod>** m, void* sp,
1480                              HandleScope** handle_scope)
1481      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1482    // First, fix up the layout of the callee-save frame.
1483    // We have to squeeze in the HandleScope, and relocate the method pointer.
1484    LayoutCalleeSaveFrame(self, m, sp, handle_scope);
1485
1486    // The bottom of the callee-save frame is now where the method is, *m.
1487    uint8_t* sp8 = reinterpret_cast<uint8_t*>(*m);
1488
1489    // Add space for cookie.
1490    LayoutCookie(&sp8);
1491
1492    return sp8;
1493  }
1494
1495  // WARNING: After this, *sp won't be pointing to the method anymore!
1496  uint8_t* ComputeLayout(Thread* self, StackReference<mirror::ArtMethod>** m,
1497                         const char* shorty, uint32_t shorty_len, HandleScope** handle_scope,
1498                         uintptr_t** start_stack, uintptr_t** start_gpr, uint32_t** start_fpr)
1499      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1500    Walk(shorty, shorty_len);
1501
1502    // JNI part.
1503    uint8_t* sp8 = LayoutJNISaveFrame(self, m, reinterpret_cast<void*>(*m), handle_scope);
1504
1505    sp8 = LayoutNativeCall(sp8, start_stack, start_gpr, start_fpr);
1506
1507    // Return the new bottom.
1508    return sp8;
1509  }
1510
1511  uintptr_t PushHandle(mirror::Object* /* ptr */) OVERRIDE;
1512
1513  // Add JNIEnv* and jobj/jclass before the shorty-derived elements.
1514  void WalkHeader(BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) OVERRIDE
1515      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
1516
1517 private:
1518  uint32_t num_handle_scope_references_;
1519};
1520
1521uintptr_t ComputeGenericJniFrameSize::PushHandle(mirror::Object* /* ptr */) {
1522  num_handle_scope_references_++;
1523  return reinterpret_cast<uintptr_t>(nullptr);
1524}
1525
1526void ComputeGenericJniFrameSize::WalkHeader(
1527    BuildNativeCallFrameStateMachine<ComputeNativeCallFrameSize>* sm) {
1528  // JNIEnv
1529  sm->AdvancePointer(nullptr);
1530
1531  // Class object or this as first argument
1532  sm->AdvanceHandleScope(reinterpret_cast<mirror::Object*>(0x12345678));
1533}
1534
1535// Class to push values to three separate regions. Used to fill the native call part. Adheres to
1536// the template requirements of BuildGenericJniFrameStateMachine.
1537class FillNativeCall {
1538 public:
1539  FillNativeCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) :
1540      cur_gpr_reg_(gpr_regs), cur_fpr_reg_(fpr_regs), cur_stack_arg_(stack_args) {}
1541
1542  virtual ~FillNativeCall() {}
1543
1544  void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args) {
1545    cur_gpr_reg_ = gpr_regs;
1546    cur_fpr_reg_ = fpr_regs;
1547    cur_stack_arg_ = stack_args;
1548  }
1549
1550  void PushGpr(uintptr_t val) {
1551    *cur_gpr_reg_ = val;
1552    cur_gpr_reg_++;
1553  }
1554
1555  void PushFpr4(float val) {
1556    *cur_fpr_reg_ = val;
1557    cur_fpr_reg_++;
1558  }
1559
1560  void PushFpr8(uint64_t val) {
1561    uint64_t* tmp = reinterpret_cast<uint64_t*>(cur_fpr_reg_);
1562    *tmp = val;
1563    cur_fpr_reg_ += 2;
1564  }
1565
1566  void PushStack(uintptr_t val) {
1567    *cur_stack_arg_ = val;
1568    cur_stack_arg_++;
1569  }
1570
1571  virtual uintptr_t PushHandle(mirror::Object*) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1572    LOG(FATAL) << "(Non-JNI) Native call does not use handles.";
1573    UNREACHABLE();
1574  }
1575
1576 private:
1577  uintptr_t* cur_gpr_reg_;
1578  uint32_t* cur_fpr_reg_;
1579  uintptr_t* cur_stack_arg_;
1580};
1581
1582// Visits arguments on the stack placing them into a region lower down the stack for the benefit
1583// of transitioning into native code.
1584class BuildGenericJniFrameVisitor FINAL : public QuickArgumentVisitor {
1585 public:
1586  BuildGenericJniFrameVisitor(Thread* self, bool is_static, const char* shorty, uint32_t shorty_len,
1587                              StackReference<mirror::ArtMethod>** sp)
1588     : QuickArgumentVisitor(*sp, is_static, shorty, shorty_len),
1589       jni_call_(nullptr, nullptr, nullptr, nullptr), sm_(&jni_call_) {
1590    ComputeGenericJniFrameSize fsc;
1591    uintptr_t* start_gpr_reg;
1592    uint32_t* start_fpr_reg;
1593    uintptr_t* start_stack_arg;
1594    bottom_of_used_area_ = fsc.ComputeLayout(self, sp, shorty, shorty_len,
1595                                             &handle_scope_,
1596                                             &start_stack_arg,
1597                                             &start_gpr_reg, &start_fpr_reg);
1598
1599    jni_call_.Reset(start_gpr_reg, start_fpr_reg, start_stack_arg, handle_scope_);
1600
1601    // jni environment is always first argument
1602    sm_.AdvancePointer(self->GetJniEnv());
1603
1604    if (is_static) {
1605      sm_.AdvanceHandleScope((*sp)->AsMirrorPtr()->GetDeclaringClass());
1606    }
1607  }
1608
1609  void Visit() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) OVERRIDE;
1610
1611  void FinalizeHandleScope(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
1612
1613  StackReference<mirror::Object>* GetFirstHandleScopeEntry()
1614      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1615    return handle_scope_->GetHandle(0).GetReference();
1616  }
1617
1618  jobject GetFirstHandleScopeJObject() const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1619    return handle_scope_->GetHandle(0).ToJObject();
1620  }
1621
1622  void* GetBottomOfUsedArea() const {
1623    return bottom_of_used_area_;
1624  }
1625
1626 private:
1627  // A class to fill a JNI call. Adds reference/handle-scope management to FillNativeCall.
1628  class FillJniCall FINAL : public FillNativeCall {
1629   public:
1630    FillJniCall(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args,
1631                HandleScope* handle_scope) : FillNativeCall(gpr_regs, fpr_regs, stack_args),
1632                                             handle_scope_(handle_scope), cur_entry_(0) {}
1633
1634    uintptr_t PushHandle(mirror::Object* ref) OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
1635
1636    void Reset(uintptr_t* gpr_regs, uint32_t* fpr_regs, uintptr_t* stack_args, HandleScope* scope) {
1637      FillNativeCall::Reset(gpr_regs, fpr_regs, stack_args);
1638      handle_scope_ = scope;
1639      cur_entry_ = 0U;
1640    }
1641
1642    void ResetRemainingScopeSlots() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1643      // Initialize padding entries.
1644      size_t expected_slots = handle_scope_->NumberOfReferences();
1645      while (cur_entry_ < expected_slots) {
1646        handle_scope_->GetMutableHandle(cur_entry_++).Assign(nullptr);
1647      }
1648      DCHECK_NE(cur_entry_, 0U);
1649    }
1650
1651   private:
1652    HandleScope* handle_scope_;
1653    size_t cur_entry_;
1654  };
1655
1656  HandleScope* handle_scope_;
1657  FillJniCall jni_call_;
1658  void* bottom_of_used_area_;
1659
1660  BuildNativeCallFrameStateMachine<FillJniCall> sm_;
1661
1662  DISALLOW_COPY_AND_ASSIGN(BuildGenericJniFrameVisitor);
1663};
1664
1665uintptr_t BuildGenericJniFrameVisitor::FillJniCall::PushHandle(mirror::Object* ref) {
1666  uintptr_t tmp;
1667  MutableHandle<mirror::Object> h = handle_scope_->GetMutableHandle(cur_entry_);
1668  h.Assign(ref);
1669  tmp = reinterpret_cast<uintptr_t>(h.ToJObject());
1670  cur_entry_++;
1671  return tmp;
1672}
1673
1674void BuildGenericJniFrameVisitor::Visit() {
1675  Primitive::Type type = GetParamPrimitiveType();
1676  switch (type) {
1677    case Primitive::kPrimLong: {
1678      jlong long_arg;
1679      if (IsSplitLongOrDouble()) {
1680        long_arg = ReadSplitLongParam();
1681      } else {
1682        long_arg = *reinterpret_cast<jlong*>(GetParamAddress());
1683      }
1684      sm_.AdvanceLong(long_arg);
1685      break;
1686    }
1687    case Primitive::kPrimDouble: {
1688      uint64_t double_arg;
1689      if (IsSplitLongOrDouble()) {
1690        // Read into union so that we don't case to a double.
1691        double_arg = ReadSplitLongParam();
1692      } else {
1693        double_arg = *reinterpret_cast<uint64_t*>(GetParamAddress());
1694      }
1695      sm_.AdvanceDouble(double_arg);
1696      break;
1697    }
1698    case Primitive::kPrimNot: {
1699      StackReference<mirror::Object>* stack_ref =
1700          reinterpret_cast<StackReference<mirror::Object>*>(GetParamAddress());
1701      sm_.AdvanceHandleScope(stack_ref->AsMirrorPtr());
1702      break;
1703    }
1704    case Primitive::kPrimFloat:
1705      sm_.AdvanceFloat(*reinterpret_cast<float*>(GetParamAddress()));
1706      break;
1707    case Primitive::kPrimBoolean:  // Fall-through.
1708    case Primitive::kPrimByte:     // Fall-through.
1709    case Primitive::kPrimChar:     // Fall-through.
1710    case Primitive::kPrimShort:    // Fall-through.
1711    case Primitive::kPrimInt:      // Fall-through.
1712      sm_.AdvanceInt(*reinterpret_cast<jint*>(GetParamAddress()));
1713      break;
1714    case Primitive::kPrimVoid:
1715      LOG(FATAL) << "UNREACHABLE";
1716      UNREACHABLE();
1717  }
1718}
1719
1720void BuildGenericJniFrameVisitor::FinalizeHandleScope(Thread* self) {
1721  // Clear out rest of the scope.
1722  jni_call_.ResetRemainingScopeSlots();
1723  // Install HandleScope.
1724  self->PushHandleScope(handle_scope_);
1725}
1726
1727#if defined(__arm__) || defined(__aarch64__)
1728extern "C" void* artFindNativeMethod();
1729#else
1730extern "C" void* artFindNativeMethod(Thread* self);
1731#endif
1732
1733uint64_t artQuickGenericJniEndJNIRef(Thread* self, uint32_t cookie, jobject l, jobject lock) {
1734  if (lock != nullptr) {
1735    return reinterpret_cast<uint64_t>(JniMethodEndWithReferenceSynchronized(l, cookie, lock, self));
1736  } else {
1737    return reinterpret_cast<uint64_t>(JniMethodEndWithReference(l, cookie, self));
1738  }
1739}
1740
1741void artQuickGenericJniEndJNINonRef(Thread* self, uint32_t cookie, jobject lock) {
1742  if (lock != nullptr) {
1743    JniMethodEndSynchronized(cookie, lock, self);
1744  } else {
1745    JniMethodEnd(cookie, self);
1746  }
1747}
1748
1749/*
1750 * Initializes an alloca region assumed to be directly below sp for a native call:
1751 * Create a HandleScope and call stack and fill a mini stack with values to be pushed to registers.
1752 * The final element on the stack is a pointer to the native code.
1753 *
1754 * On entry, the stack has a standard callee-save frame above sp, and an alloca below it.
1755 * We need to fix this, as the handle scope needs to go into the callee-save frame.
1756 *
1757 * The return of this function denotes:
1758 * 1) How many bytes of the alloca can be released, if the value is non-negative.
1759 * 2) An error, if the value is negative.
1760 */
1761extern "C" TwoWordReturn artQuickGenericJniTrampoline(Thread* self,
1762                                                      StackReference<mirror::ArtMethod>* sp)
1763    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1764  mirror::ArtMethod* called = sp->AsMirrorPtr();
1765  DCHECK(called->IsNative()) << PrettyMethod(called, true);
1766  uint32_t shorty_len = 0;
1767  const char* shorty = called->GetShorty(&shorty_len);
1768
1769  // Run the visitor and update sp.
1770  BuildGenericJniFrameVisitor visitor(self, called->IsStatic(), shorty, shorty_len, &sp);
1771  visitor.VisitArguments();
1772  visitor.FinalizeHandleScope(self);
1773
1774  // Fix up managed-stack things in Thread.
1775  self->SetTopOfStack(sp);
1776
1777  self->VerifyStack();
1778
1779  // Start JNI, save the cookie.
1780  uint32_t cookie;
1781  if (called->IsSynchronized()) {
1782    cookie = JniMethodStartSynchronized(visitor.GetFirstHandleScopeJObject(), self);
1783    if (self->IsExceptionPending()) {
1784      self->PopHandleScope();
1785      // A negative value denotes an error.
1786      return GetTwoWordFailureValue();
1787    }
1788  } else {
1789    cookie = JniMethodStart(self);
1790  }
1791  uint32_t* sp32 = reinterpret_cast<uint32_t*>(sp);
1792  *(sp32 - 1) = cookie;
1793
1794  // Retrieve the stored native code.
1795  void* nativeCode = called->GetEntryPointFromJni();
1796
1797  // There are two cases for the content of nativeCode:
1798  // 1) Pointer to the native function.
1799  // 2) Pointer to the trampoline for native code binding.
1800  // In the second case, we need to execute the binding and continue with the actual native function
1801  // pointer.
1802  DCHECK(nativeCode != nullptr);
1803  if (nativeCode == GetJniDlsymLookupStub()) {
1804#if defined(__arm__) || defined(__aarch64__)
1805    nativeCode = artFindNativeMethod();
1806#else
1807    nativeCode = artFindNativeMethod(self);
1808#endif
1809
1810    if (nativeCode == nullptr) {
1811      DCHECK(self->IsExceptionPending());    // There should be an exception pending now.
1812
1813      // End JNI, as the assembly will move to deliver the exception.
1814      jobject lock = called->IsSynchronized() ? visitor.GetFirstHandleScopeJObject() : nullptr;
1815      if (shorty[0] == 'L') {
1816        artQuickGenericJniEndJNIRef(self, cookie, nullptr, lock);
1817      } else {
1818        artQuickGenericJniEndJNINonRef(self, cookie, lock);
1819      }
1820
1821      return GetTwoWordFailureValue();
1822    }
1823    // Note that the native code pointer will be automatically set by artFindNativeMethod().
1824  }
1825
1826  // Return native code addr(lo) and bottom of alloca address(hi).
1827  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(visitor.GetBottomOfUsedArea()),
1828                                reinterpret_cast<uintptr_t>(nativeCode));
1829}
1830
1831/*
1832 * Is called after the native JNI code. Responsible for cleanup (handle scope, saved state) and
1833 * unlocking.
1834 */
1835extern "C" uint64_t artQuickGenericJniEndTrampoline(Thread* self, jvalue result, uint64_t result_f)
1836    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1837  StackReference<mirror::ArtMethod>* sp = self->GetManagedStack()->GetTopQuickFrame();
1838  uint32_t* sp32 = reinterpret_cast<uint32_t*>(sp);
1839  mirror::ArtMethod* called = sp->AsMirrorPtr();
1840  uint32_t cookie = *(sp32 - 1);
1841
1842  jobject lock = nullptr;
1843  if (called->IsSynchronized()) {
1844    HandleScope* table = reinterpret_cast<HandleScope*>(reinterpret_cast<uint8_t*>(sp)
1845        + sizeof(StackReference<mirror::ArtMethod>));
1846    lock = table->GetHandle(0).ToJObject();
1847  }
1848
1849  char return_shorty_char = called->GetShorty()[0];
1850
1851  if (return_shorty_char == 'L') {
1852    return artQuickGenericJniEndJNIRef(self, cookie, result.l, lock);
1853  } else {
1854    artQuickGenericJniEndJNINonRef(self, cookie, lock);
1855
1856    switch (return_shorty_char) {
1857      case 'F': {
1858        if (kRuntimeISA == kX86) {
1859          // Convert back the result to float.
1860          double d = bit_cast<uint64_t, double>(result_f);
1861          return bit_cast<float, uint32_t>(static_cast<float>(d));
1862        } else {
1863          return result_f;
1864        }
1865      }
1866      case 'D':
1867        return result_f;
1868      case 'Z':
1869        return result.z;
1870      case 'B':
1871        return result.b;
1872      case 'C':
1873        return result.c;
1874      case 'S':
1875        return result.s;
1876      case 'I':
1877        return result.i;
1878      case 'J':
1879        return result.j;
1880      case 'V':
1881        return 0;
1882      default:
1883        LOG(FATAL) << "Unexpected return shorty character " << return_shorty_char;
1884        return 0;
1885    }
1886  }
1887}
1888
1889// We use TwoWordReturn to optimize scalar returns. We use the hi value for code, and the lo value
1890// for the method pointer.
1891//
1892// It is valid to use this, as at the usage points here (returns from C functions) we are assuming
1893// to hold the mutator lock (see SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) annotations).
1894
1895template<InvokeType type, bool access_check>
1896static TwoWordReturn artInvokeCommon(uint32_t method_idx, mirror::Object* this_object,
1897                                     mirror::ArtMethod* caller_method,
1898                                     Thread* self, StackReference<mirror::ArtMethod>* sp);
1899
1900template<InvokeType type, bool access_check>
1901static TwoWordReturn artInvokeCommon(uint32_t method_idx, mirror::Object* this_object,
1902                                     mirror::ArtMethod* caller_method,
1903                                     Thread* self, StackReference<mirror::ArtMethod>* sp) {
1904  ScopedQuickEntrypointChecks sqec(self);
1905  DCHECK_EQ(sp->AsMirrorPtr(), Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
1906  mirror::ArtMethod* method = FindMethodFast(method_idx, this_object, caller_method, access_check,
1907                                             type);
1908  if (UNLIKELY(method == nullptr)) {
1909    const DexFile* dex_file = caller_method->GetDeclaringClass()->GetDexCache()->GetDexFile();
1910    uint32_t shorty_len;
1911    const char* shorty = dex_file->GetMethodShorty(dex_file->GetMethodId(method_idx), &shorty_len);
1912    {
1913      // Remember the args in case a GC happens in FindMethodFromCode.
1914      ScopedObjectAccessUnchecked soa(self->GetJniEnv());
1915      RememberForGcArgumentVisitor visitor(sp, type == kStatic, shorty, shorty_len, &soa);
1916      visitor.VisitArguments();
1917      method = FindMethodFromCode<type, access_check>(method_idx, &this_object, &caller_method,
1918                                                      self);
1919      visitor.FixupReferences();
1920    }
1921
1922    if (UNLIKELY(method == nullptr)) {
1923      CHECK(self->IsExceptionPending());
1924      return GetTwoWordFailureValue();  // Failure.
1925    }
1926  }
1927  DCHECK(!self->IsExceptionPending());
1928  const void* code = method->GetEntryPointFromQuickCompiledCode();
1929
1930  // When we return, the caller will branch to this address, so it had better not be 0!
1931  DCHECK(code != nullptr) << "Code was null in method: " << PrettyMethod(method)
1932                          << " location: "
1933                          << method->GetDexFile()->GetLocation();
1934
1935  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
1936                                reinterpret_cast<uintptr_t>(method));
1937}
1938
1939// Explicit artInvokeCommon template function declarations to please analysis tool.
1940#define EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(type, access_check)                                \
1941  template SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)                                          \
1942  TwoWordReturn artInvokeCommon<type, access_check>(uint32_t method_idx,                        \
1943                                                    mirror::Object* this_object,                \
1944                                                    mirror::ArtMethod* caller_method,           \
1945                                                    Thread* self,                               \
1946                                                    StackReference<mirror::ArtMethod>* sp)      \
1947
1948EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual, false);
1949EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kVirtual, true);
1950EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface, false);
1951EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kInterface, true);
1952EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect, false);
1953EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kDirect, true);
1954EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic, false);
1955EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kStatic, true);
1956EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper, false);
1957EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL(kSuper, true);
1958#undef EXPLICIT_INVOKE_COMMON_TEMPLATE_DECL
1959
1960// See comments in runtime_support_asm.S
1961extern "C" TwoWordReturn artInvokeInterfaceTrampolineWithAccessCheck(
1962    uint32_t method_idx, mirror::Object* this_object,
1963    mirror::ArtMethod* caller_method, Thread* self,
1964    StackReference<mirror::ArtMethod>* sp)
1965        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1966  return artInvokeCommon<kInterface, true>(method_idx, this_object,
1967                                           caller_method, self, sp);
1968}
1969
1970extern "C" TwoWordReturn artInvokeDirectTrampolineWithAccessCheck(
1971    uint32_t method_idx, mirror::Object* this_object,
1972    mirror::ArtMethod* caller_method, Thread* self,
1973    StackReference<mirror::ArtMethod>* sp)
1974        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1975  return artInvokeCommon<kDirect, true>(method_idx, this_object, caller_method,
1976                                        self, sp);
1977}
1978
1979extern "C" TwoWordReturn artInvokeStaticTrampolineWithAccessCheck(
1980    uint32_t method_idx, mirror::Object* this_object,
1981    mirror::ArtMethod* caller_method, Thread* self,
1982    StackReference<mirror::ArtMethod>* sp)
1983        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1984  return artInvokeCommon<kStatic, true>(method_idx, this_object, caller_method,
1985                                        self, sp);
1986}
1987
1988extern "C" TwoWordReturn artInvokeSuperTrampolineWithAccessCheck(
1989    uint32_t method_idx, mirror::Object* this_object,
1990    mirror::ArtMethod* caller_method, Thread* self,
1991    StackReference<mirror::ArtMethod>* sp)
1992        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1993  return artInvokeCommon<kSuper, true>(method_idx, this_object, caller_method,
1994                                       self, sp);
1995}
1996
1997extern "C" TwoWordReturn artInvokeVirtualTrampolineWithAccessCheck(
1998    uint32_t method_idx, mirror::Object* this_object,
1999    mirror::ArtMethod* caller_method, Thread* self,
2000    StackReference<mirror::ArtMethod>* sp)
2001        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2002  return artInvokeCommon<kVirtual, true>(method_idx, this_object, caller_method,
2003                                         self, sp);
2004}
2005
2006// Determine target of interface dispatch. This object is known non-null.
2007extern "C" TwoWordReturn artInvokeInterfaceTrampoline(mirror::ArtMethod* interface_method,
2008                                                      mirror::Object* this_object,
2009                                                      mirror::ArtMethod* caller_method,
2010                                                      Thread* self,
2011                                                      StackReference<mirror::ArtMethod>* sp)
2012    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2013  ScopedQuickEntrypointChecks sqec(self);
2014  mirror::ArtMethod* method;
2015  if (LIKELY(interface_method->GetDexMethodIndex() != DexFile::kDexNoIndex)) {
2016    method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
2017    if (UNLIKELY(method == nullptr)) {
2018      ThrowIncompatibleClassChangeErrorClassForInterfaceDispatch(interface_method, this_object,
2019                                                                 caller_method);
2020      return GetTwoWordFailureValue();  // Failure.
2021    }
2022  } else {
2023    DCHECK(interface_method == Runtime::Current()->GetResolutionMethod());
2024
2025    // Find the caller PC.
2026    constexpr size_t pc_offset = GetCalleeSaveReturnPcOffset(kRuntimeISA, Runtime::kRefsAndArgs);
2027    uintptr_t caller_pc = *reinterpret_cast<uintptr_t*>(reinterpret_cast<uint8_t*>(sp) + pc_offset);
2028
2029    // Map the caller PC to a dex PC.
2030    uint32_t dex_pc = caller_method->ToDexPc(caller_pc);
2031    const DexFile::CodeItem* code = caller_method->GetCodeItem();
2032    CHECK_LT(dex_pc, code->insns_size_in_code_units_);
2033    const Instruction* instr = Instruction::At(&code->insns_[dex_pc]);
2034    Instruction::Code instr_code = instr->Opcode();
2035    CHECK(instr_code == Instruction::INVOKE_INTERFACE ||
2036          instr_code == Instruction::INVOKE_INTERFACE_RANGE)
2037        << "Unexpected call into interface trampoline: " << instr->DumpString(nullptr);
2038    uint32_t dex_method_idx;
2039    if (instr_code == Instruction::INVOKE_INTERFACE) {
2040      dex_method_idx = instr->VRegB_35c();
2041    } else {
2042      DCHECK_EQ(instr_code, Instruction::INVOKE_INTERFACE_RANGE);
2043      dex_method_idx = instr->VRegB_3rc();
2044    }
2045
2046    const DexFile* dex_file = caller_method->GetDeclaringClass()->GetDexCache()
2047        ->GetDexFile();
2048    uint32_t shorty_len;
2049    const char* shorty = dex_file->GetMethodShorty(dex_file->GetMethodId(dex_method_idx),
2050                                                   &shorty_len);
2051    {
2052      // Remember the args in case a GC happens in FindMethodFromCode.
2053      ScopedObjectAccessUnchecked soa(self->GetJniEnv());
2054      RememberForGcArgumentVisitor visitor(sp, false, shorty, shorty_len, &soa);
2055      visitor.VisitArguments();
2056      method = FindMethodFromCode<kInterface, false>(dex_method_idx, &this_object, &caller_method,
2057                                                     self);
2058      visitor.FixupReferences();
2059    }
2060
2061    if (UNLIKELY(method == nullptr)) {
2062      CHECK(self->IsExceptionPending());
2063      return GetTwoWordFailureValue();  // Failure.
2064    }
2065  }
2066  const void* code = method->GetEntryPointFromQuickCompiledCode();
2067
2068  // When we return, the caller will branch to this address, so it had better not be 0!
2069  DCHECK(code != nullptr) << "Code was null in method: " << PrettyMethod(method)
2070                          << " location: " << method->GetDexFile()->GetLocation();
2071
2072  return GetTwoWordSuccessValue(reinterpret_cast<uintptr_t>(code),
2073                                reinterpret_cast<uintptr_t>(method));
2074}
2075
2076}  // namespace art
2077