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