blob: c2397f9e44c040ed319e2d6c0f912594a66f5e58 [file] [log] [blame]
Ben Chengba4fc8b2009-06-01 13:00:29 -07001/*
2 * Copyright (C) 2008 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#ifdef WITH_JIT
17
18/*
19 * Target independent portion of Android's Jit
20 */
21
22#include "Dalvik.h"
23#include "Jit.h"
24
25
Dan Bornsteindf4daaf2010-12-01 14:23:44 -080026#include "libdex/DexOpcodes.h"
Ben Chengba4fc8b2009-06-01 13:00:29 -070027#include <unistd.h>
28#include <pthread.h>
29#include <sys/time.h>
30#include <signal.h>
31#include "compiler/Compiler.h"
Bill Buzbee6e963e12009-06-17 16:56:19 -070032#include "compiler/CompilerUtility.h"
33#include "compiler/CompilerIR.h"
Ben Chengba4fc8b2009-06-01 13:00:29 -070034#include <errno.h>
35
Jeff Hao97319a82009-08-12 16:57:15 -070036#if defined(WITH_SELF_VERIFICATION)
37/* Allocate space for per-thread ShadowSpace data structures */
38void* dvmSelfVerificationShadowSpaceAlloc(Thread* self)
39{
40 self->shadowSpace = (ShadowSpace*) calloc(1, sizeof(ShadowSpace));
41 if (self->shadowSpace == NULL)
42 return NULL;
43
44 self->shadowSpace->registerSpaceSize = REG_SPACE;
45 self->shadowSpace->registerSpace =
46 (int*) calloc(self->shadowSpace->registerSpaceSize, sizeof(int));
47
48 return self->shadowSpace->registerSpace;
49}
50
51/* Free per-thread ShadowSpace data structures */
52void dvmSelfVerificationShadowSpaceFree(Thread* self)
53{
54 free(self->shadowSpace->registerSpace);
55 free(self->shadowSpace);
56}
57
58/*
buzbee9f601a92011-02-11 17:48:20 -080059 * Save out PC, FP, thread state, and registers to shadow space.
Jeff Hao97319a82009-08-12 16:57:15 -070060 * Return a pointer to the shadow space for JIT to use.
buzbee9f601a92011-02-11 17:48:20 -080061 *
62 * The set of saved state from the Thread structure is:
63 * pc (Dalvik PC)
64 * fp (Dalvik FP)
65 * retval
66 * method
67 * methodClassDex
68 * interpStackEnd
Jeff Hao97319a82009-08-12 16:57:15 -070069 */
buzbee9f601a92011-02-11 17:48:20 -080070void* dvmSelfVerificationSaveState(const u2* pc, u4* fp,
71 Thread* self, int targetTrace)
Jeff Hao97319a82009-08-12 16:57:15 -070072{
Jeff Hao97319a82009-08-12 16:57:15 -070073 ShadowSpace *shadowSpace = self->shadowSpace;
buzbee9f601a92011-02-11 17:48:20 -080074 unsigned preBytes = self->interpSave.method->outsSize*4 +
75 sizeof(StackSaveArea);
76 unsigned postBytes = self->interpSave.method->registersSize*4;
Jeff Hao97319a82009-08-12 16:57:15 -070077
78 //LOGD("### selfVerificationSaveState(%d) pc: 0x%x fp: 0x%x",
79 // self->threadId, (int)pc, (int)fp);
80
81 if (shadowSpace->selfVerificationState != kSVSIdle) {
82 LOGD("~~~ Save: INCORRECT PREVIOUS STATE(%d): %d",
83 self->threadId, shadowSpace->selfVerificationState);
84 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -070085 LOGD("PC: 0x%x FP: 0x%x", (int)pc, (int)fp);
Jeff Hao97319a82009-08-12 16:57:15 -070086 }
87 shadowSpace->selfVerificationState = kSVSStart;
88
buzbee9f601a92011-02-11 17:48:20 -080089 if (self->entryPoint == kInterpEntryResume) {
90 self->entryPoint = kInterpEntryInstr;
Ben Chengd5adae12010-03-26 17:45:28 -070091#if 0
92 /* Tracking the success rate of resume after single-stepping */
buzbee9f601a92011-02-11 17:48:20 -080093 if (self->jitResumeDPC == pc) {
Ben Chengd5adae12010-03-26 17:45:28 -070094 LOGD("SV single step resumed at %p", pc);
95 }
96 else {
buzbee9f601a92011-02-11 17:48:20 -080097 LOGD("real %p DPC %p NPC %p", pc, self->jitResumeDPC,
98 self->jitResumeNPC);
Ben Chengd5adae12010-03-26 17:45:28 -070099 }
100#endif
101 }
102
Jeff Hao97319a82009-08-12 16:57:15 -0700103 // Dynamically grow shadow register space if necessary
Ben Cheng11d8f142010-03-24 15:24:19 -0700104 if (preBytes + postBytes > shadowSpace->registerSpaceSize * sizeof(u4)) {
Jeff Hao97319a82009-08-12 16:57:15 -0700105 free(shadowSpace->registerSpace);
Ben Cheng11d8f142010-03-24 15:24:19 -0700106 shadowSpace->registerSpaceSize = (preBytes + postBytes) / sizeof(u4);
Jeff Hao97319a82009-08-12 16:57:15 -0700107 shadowSpace->registerSpace =
Ben Cheng11d8f142010-03-24 15:24:19 -0700108 (int*) calloc(shadowSpace->registerSpaceSize, sizeof(u4));
Jeff Hao97319a82009-08-12 16:57:15 -0700109 }
110
111 // Remember original state
112 shadowSpace->startPC = pc;
113 shadowSpace->fp = fp;
buzbee9f601a92011-02-11 17:48:20 -0800114 shadowSpace->retval = self->retval;
115 shadowSpace->interpStackEnd = self->interpStackEnd;
116
Ben Chengccd6c012009-10-15 14:52:45 -0700117 /*
118 * Store the original method here in case the trace ends with a
119 * return/invoke, the last method.
120 */
buzbee9f601a92011-02-11 17:48:20 -0800121 shadowSpace->method = self->interpSave.method;
122 shadowSpace->methodClassDex = self->interpSave.methodClassDex;
123
Jeff Hao97319a82009-08-12 16:57:15 -0700124 shadowSpace->shadowFP = shadowSpace->registerSpace +
125 shadowSpace->registerSpaceSize - postBytes/4;
126
buzbee9f601a92011-02-11 17:48:20 -0800127 self->interpSave.fp = (u4*)shadowSpace->shadowFP;
128 self->interpStackEnd = (u1*)shadowSpace->registerSpace;
Jeff Hao97319a82009-08-12 16:57:15 -0700129
130 // Create a copy of the stack
131 memcpy(((char*)shadowSpace->shadowFP)-preBytes, ((char*)fp)-preBytes,
132 preBytes+postBytes);
133
134 // Setup the shadowed heap space
135 shadowSpace->heapSpaceTail = shadowSpace->heapSpace;
136
137 // Reset trace length
138 shadowSpace->traceLength = 0;
139
140 return shadowSpace;
141}
142
143/*
144 * Save ending PC, FP and compiled code exit point to shadow space.
145 * Return a pointer to the shadow space for JIT to restore state.
146 */
buzbee9f601a92011-02-11 17:48:20 -0800147void* dvmSelfVerificationRestoreState(const u2* pc, u4* fp,
148 SelfVerificationState exitState,
149 Thread* self)
Jeff Hao97319a82009-08-12 16:57:15 -0700150{
Jeff Hao97319a82009-08-12 16:57:15 -0700151 ShadowSpace *shadowSpace = self->shadowSpace;
152 shadowSpace->endPC = pc;
153 shadowSpace->endShadowFP = fp;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700154 shadowSpace->jitExitState = exitState;
Jeff Hao97319a82009-08-12 16:57:15 -0700155
156 //LOGD("### selfVerificationRestoreState(%d) pc: 0x%x fp: 0x%x endPC: 0x%x",
157 // self->threadId, (int)shadowSpace->startPC, (int)shadowSpace->fp,
158 // (int)pc);
159
160 if (shadowSpace->selfVerificationState != kSVSStart) {
161 LOGD("~~~ Restore: INCORRECT PREVIOUS STATE(%d): %d",
162 self->threadId, shadowSpace->selfVerificationState);
163 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -0700164 LOGD("Dalvik PC: 0x%x endPC: 0x%x", (int)shadowSpace->startPC,
Jeff Hao97319a82009-08-12 16:57:15 -0700165 (int)shadowSpace->endPC);
Ben Chengccd6c012009-10-15 14:52:45 -0700166 LOGD("Interp FP: 0x%x", (int)shadowSpace->fp);
167 LOGD("Shadow FP: 0x%x endFP: 0x%x", (int)shadowSpace->shadowFP,
Jeff Hao97319a82009-08-12 16:57:15 -0700168 (int)shadowSpace->endShadowFP);
169 }
170
171 // Special case when punting after a single instruction
Ben Cheng7a2697d2010-06-07 13:44:23 -0700172 if (exitState == kSVSPunt && pc == shadowSpace->startPC) {
Jeff Hao97319a82009-08-12 16:57:15 -0700173 shadowSpace->selfVerificationState = kSVSIdle;
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700174 } else if (exitState == kSVSBackwardBranch && pc < shadowSpace->startPC) {
Ben Cheng60c6dbf2010-08-26 12:28:56 -0700175 /*
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700176 * Consider a trace with a backward branch:
Ben Cheng60c6dbf2010-08-26 12:28:56 -0700177 * 1: ..
178 * 2: ..
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700179 * 3: ..
Ben Cheng60c6dbf2010-08-26 12:28:56 -0700180 * 4: ..
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700181 * 5: Goto {1 or 2 or 3 or 4}
Ben Cheng60c6dbf2010-08-26 12:28:56 -0700182 *
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700183 * If there instruction 5 goes to 1 and there is no single-step
184 * instruction in the loop, pc is equal to shadowSpace->startPC and
185 * we will honor the backward branch condition.
Ben Cheng60c6dbf2010-08-26 12:28:56 -0700186 *
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700187 * If the single-step instruction is outside the loop, then after
188 * resuming in the trace the startPC will be less than pc so we will
189 * also honor the backward branch condition.
190 *
191 * If the single-step is inside the loop, we won't hit the same endPC
192 * twice when the interpreter is re-executing the trace so we want to
193 * cancel the backward branch condition. In this case it can be
194 * detected as the endPC (ie pc) will be less than startPC.
Ben Cheng60c6dbf2010-08-26 12:28:56 -0700195 */
196 shadowSpace->selfVerificationState = kSVSNormal;
Jeff Hao97319a82009-08-12 16:57:15 -0700197 } else {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700198 shadowSpace->selfVerificationState = exitState;
Jeff Hao97319a82009-08-12 16:57:15 -0700199 }
200
buzbee9f601a92011-02-11 17:48:20 -0800201 /* Restore state before returning */
202 self->interpSave.pc = shadowSpace->startPC;
203 self->interpSave.fp = shadowSpace->fp;
204 self->interpSave.method = shadowSpace->method;
205 self->interpSave.methodClassDex = shadowSpace->methodClassDex;
206 self->retval = shadowSpace->retval;
207 self->interpStackEnd = shadowSpace->interpStackEnd;
208
Jeff Hao97319a82009-08-12 16:57:15 -0700209 return shadowSpace;
210}
211
212/* Print contents of virtual registers */
Ben Chengccd6c012009-10-15 14:52:45 -0700213static void selfVerificationPrintRegisters(int* addr, int* addrRef,
214 int numWords)
Jeff Hao97319a82009-08-12 16:57:15 -0700215{
216 int i;
217 for (i = 0; i < numWords; i++) {
Ben Chengccd6c012009-10-15 14:52:45 -0700218 LOGD("(v%d) 0x%8x%s", i, addr[i], addr[i] != addrRef[i] ? " X" : "");
Jeff Hao97319a82009-08-12 16:57:15 -0700219 }
220}
221
222/* Print values maintained in shadowSpace */
223static void selfVerificationDumpState(const u2* pc, Thread* self)
224{
225 ShadowSpace* shadowSpace = self->shadowSpace;
226 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
227 int frameBytes = (int) shadowSpace->registerSpace +
228 shadowSpace->registerSpaceSize*4 -
229 (int) shadowSpace->shadowFP;
230 int localRegs = 0;
231 int frameBytes2 = 0;
buzbee9f601a92011-02-11 17:48:20 -0800232 if ((uintptr_t)self->curFrame < (uintptr_t)shadowSpace->fp) {
Jeff Hao97319a82009-08-12 16:57:15 -0700233 localRegs = (stackSave->method->registersSize -
234 stackSave->method->insSize)*4;
235 frameBytes2 = (int) shadowSpace->fp - (int) self->curFrame - localRegs;
236 }
237 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -0700238 LOGD("CurrentPC: 0x%x, Offset: 0x%04x", (int)pc,
Jeff Hao97319a82009-08-12 16:57:15 -0700239 (int)(pc - stackSave->method->insns));
Ben Chengccd6c012009-10-15 14:52:45 -0700240 LOGD("Class: %s", shadowSpace->method->clazz->descriptor);
241 LOGD("Method: %s", shadowSpace->method->name);
242 LOGD("Dalvik PC: 0x%x endPC: 0x%x", (int)shadowSpace->startPC,
Jeff Hao97319a82009-08-12 16:57:15 -0700243 (int)shadowSpace->endPC);
Ben Chengccd6c012009-10-15 14:52:45 -0700244 LOGD("Interp FP: 0x%x endFP: 0x%x", (int)shadowSpace->fp,
Jeff Hao97319a82009-08-12 16:57:15 -0700245 (int)self->curFrame);
Ben Chengccd6c012009-10-15 14:52:45 -0700246 LOGD("Shadow FP: 0x%x endFP: 0x%x", (int)shadowSpace->shadowFP,
Jeff Hao97319a82009-08-12 16:57:15 -0700247 (int)shadowSpace->endShadowFP);
Ben Chengccd6c012009-10-15 14:52:45 -0700248 LOGD("Frame1 Bytes: %d Frame2 Local: %d Bytes: %d", frameBytes,
Jeff Hao97319a82009-08-12 16:57:15 -0700249 localRegs, frameBytes2);
Ben Chengccd6c012009-10-15 14:52:45 -0700250 LOGD("Trace length: %d State: %d", shadowSpace->traceLength,
Jeff Hao97319a82009-08-12 16:57:15 -0700251 shadowSpace->selfVerificationState);
252}
253
254/* Print decoded instructions in the current trace */
255static void selfVerificationDumpTrace(const u2* pc, Thread* self)
256{
257 ShadowSpace* shadowSpace = self->shadowSpace;
258 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700259 int i, addr, offset;
260 DecodedInstruction *decInsn;
Jeff Hao97319a82009-08-12 16:57:15 -0700261
262 LOGD("********** SHADOW TRACE DUMP **********");
263 for (i = 0; i < shadowSpace->traceLength; i++) {
Ben Chengbcdc1de2009-08-21 16:18:46 -0700264 addr = shadowSpace->trace[i].addr;
265 offset = (int)((u2*)addr - stackSave->method->insns);
266 decInsn = &(shadowSpace->trace[i].decInsn);
267 /* Not properly decoding instruction, some registers may be garbage */
Andy McFaddenc6b25c72010-06-22 11:01:20 -0700268 LOGD("0x%x: (0x%04x) %s",
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800269 addr, offset, dexGetOpcodeName(decInsn->opcode));
Jeff Hao97319a82009-08-12 16:57:15 -0700270 }
271}
272
Ben Chengbcdc1de2009-08-21 16:18:46 -0700273/* Code is forced into this spin loop when a divergence is detected */
Ben Chengccd6c012009-10-15 14:52:45 -0700274static void selfVerificationSpinLoop(ShadowSpace *shadowSpace)
Ben Chengbcdc1de2009-08-21 16:18:46 -0700275{
Ben Chengccd6c012009-10-15 14:52:45 -0700276 const u2 *startPC = shadowSpace->startPC;
Ben Cheng88a0f972010-02-24 15:00:40 -0800277 JitTraceDescription* desc = dvmCopyTraceDescriptor(startPC, NULL);
Ben Chengccd6c012009-10-15 14:52:45 -0700278 if (desc) {
279 dvmCompilerWorkEnqueue(startPC, kWorkOrderTraceDebug, desc);
Ben Cheng1357e942010-02-10 17:21:39 -0800280 /*
281 * This function effectively terminates the VM right here, so not
282 * freeing the desc pointer when the enqueuing fails is acceptable.
283 */
Ben Chengccd6c012009-10-15 14:52:45 -0700284 }
Ben Chengbcdc1de2009-08-21 16:18:46 -0700285 gDvmJit.selfVerificationSpin = true;
286 while(gDvmJit.selfVerificationSpin) sleep(10);
287}
288
Jeff Hao97319a82009-08-12 16:57:15 -0700289/* Manage self verification while in the debug interpreter */
buzbee9f601a92011-02-11 17:48:20 -0800290static bool selfVerificationDebugInterp(const u2* pc, Thread* self)
Jeff Hao97319a82009-08-12 16:57:15 -0700291{
292 ShadowSpace *shadowSpace = self->shadowSpace;
Jeff Hao97319a82009-08-12 16:57:15 -0700293 SelfVerificationState state = shadowSpace->selfVerificationState;
Ben Chengbcdc1de2009-08-21 16:18:46 -0700294
295 DecodedInstruction decInsn;
Dan Bornstein54322392010-11-17 14:16:56 -0800296 dexDecodeInstruction(pc, &decInsn);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700297
Jeff Hao97319a82009-08-12 16:57:15 -0700298 //LOGD("### DbgIntp(%d): PC: 0x%x endPC: 0x%x state: %d len: %d %s",
299 // self->threadId, (int)pc, (int)shadowSpace->endPC, state,
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800300 // shadowSpace->traceLength, dexGetOpcodeName(decInsn.opcode));
Jeff Hao97319a82009-08-12 16:57:15 -0700301
302 if (state == kSVSIdle || state == kSVSStart) {
303 LOGD("~~~ DbgIntrp: INCORRECT PREVIOUS STATE(%d): %d",
304 self->threadId, state);
305 selfVerificationDumpState(pc, self);
306 selfVerificationDumpTrace(pc, self);
307 }
308
Ben Chengd5adae12010-03-26 17:45:28 -0700309 /*
310 * Skip endPC once when trace has a backward branch. If the SV state is
311 * single step, keep it that way.
312 */
Jeff Hao97319a82009-08-12 16:57:15 -0700313 if ((state == kSVSBackwardBranch && pc == shadowSpace->endPC) ||
Ben Chengd5adae12010-03-26 17:45:28 -0700314 (state != kSVSBackwardBranch && state != kSVSSingleStep)) {
Jeff Hao97319a82009-08-12 16:57:15 -0700315 shadowSpace->selfVerificationState = kSVSDebugInterp;
316 }
317
318 /* Check that the current pc is the end of the trace */
Ben Chengd5adae12010-03-26 17:45:28 -0700319 if ((state == kSVSDebugInterp || state == kSVSSingleStep) &&
320 pc == shadowSpace->endPC) {
Jeff Hao97319a82009-08-12 16:57:15 -0700321
322 shadowSpace->selfVerificationState = kSVSIdle;
323
324 /* Check register space */
325 int frameBytes = (int) shadowSpace->registerSpace +
326 shadowSpace->registerSpaceSize*4 -
327 (int) shadowSpace->shadowFP;
328 if (memcmp(shadowSpace->fp, shadowSpace->shadowFP, frameBytes)) {
Ben Chengccd6c012009-10-15 14:52:45 -0700329 LOGD("~~~ DbgIntp(%d): REGISTERS DIVERGENCE!", self->threadId);
Jeff Hao97319a82009-08-12 16:57:15 -0700330 selfVerificationDumpState(pc, self);
331 selfVerificationDumpTrace(pc, self);
332 LOGD("*** Interp Registers: addr: 0x%x bytes: %d",
333 (int)shadowSpace->fp, frameBytes);
Ben Chengccd6c012009-10-15 14:52:45 -0700334 selfVerificationPrintRegisters((int*)shadowSpace->fp,
335 (int*)shadowSpace->shadowFP,
336 frameBytes/4);
Jeff Hao97319a82009-08-12 16:57:15 -0700337 LOGD("*** Shadow Registers: addr: 0x%x bytes: %d",
338 (int)shadowSpace->shadowFP, frameBytes);
339 selfVerificationPrintRegisters((int*)shadowSpace->shadowFP,
Ben Chengccd6c012009-10-15 14:52:45 -0700340 (int*)shadowSpace->fp,
341 frameBytes/4);
342 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700343 }
344 /* Check new frame if it exists (invokes only) */
buzbee9f601a92011-02-11 17:48:20 -0800345 if ((uintptr_t)self->curFrame < (uintptr_t)shadowSpace->fp) {
Jeff Hao97319a82009-08-12 16:57:15 -0700346 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
347 int localRegs = (stackSave->method->registersSize -
348 stackSave->method->insSize)*4;
349 int frameBytes2 = (int) shadowSpace->fp -
350 (int) self->curFrame - localRegs;
351 if (memcmp(((char*)self->curFrame)+localRegs,
352 ((char*)shadowSpace->endShadowFP)+localRegs, frameBytes2)) {
Ben Chengccd6c012009-10-15 14:52:45 -0700353 LOGD("~~~ DbgIntp(%d): REGISTERS (FRAME2) DIVERGENCE!",
Jeff Hao97319a82009-08-12 16:57:15 -0700354 self->threadId);
355 selfVerificationDumpState(pc, self);
356 selfVerificationDumpTrace(pc, self);
357 LOGD("*** Interp Registers: addr: 0x%x l: %d bytes: %d",
358 (int)self->curFrame, localRegs, frameBytes2);
359 selfVerificationPrintRegisters((int*)self->curFrame,
Ben Chengccd6c012009-10-15 14:52:45 -0700360 (int*)shadowSpace->endShadowFP,
361 (frameBytes2+localRegs)/4);
Jeff Hao97319a82009-08-12 16:57:15 -0700362 LOGD("*** Shadow Registers: addr: 0x%x l: %d bytes: %d",
363 (int)shadowSpace->endShadowFP, localRegs, frameBytes2);
364 selfVerificationPrintRegisters((int*)shadowSpace->endShadowFP,
Ben Chengccd6c012009-10-15 14:52:45 -0700365 (int*)self->curFrame,
366 (frameBytes2+localRegs)/4);
367 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700368 }
369 }
370
371 /* Check memory space */
Ben Chengbcdc1de2009-08-21 16:18:46 -0700372 bool memDiff = false;
Jeff Hao97319a82009-08-12 16:57:15 -0700373 ShadowHeap* heapSpacePtr;
374 for (heapSpacePtr = shadowSpace->heapSpace;
375 heapSpacePtr != shadowSpace->heapSpaceTail; heapSpacePtr++) {
Ben Chengbcdc1de2009-08-21 16:18:46 -0700376 int memData = *((unsigned int*) heapSpacePtr->addr);
377 if (heapSpacePtr->data != memData) {
Ben Chengccd6c012009-10-15 14:52:45 -0700378 LOGD("~~~ DbgIntp(%d): MEMORY DIVERGENCE!", self->threadId);
379 LOGD("Addr: 0x%x Intrp Data: 0x%x Jit Data: 0x%x",
Ben Chengbcdc1de2009-08-21 16:18:46 -0700380 heapSpacePtr->addr, memData, heapSpacePtr->data);
Jeff Hao97319a82009-08-12 16:57:15 -0700381 selfVerificationDumpState(pc, self);
382 selfVerificationDumpTrace(pc, self);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700383 memDiff = true;
Jeff Hao97319a82009-08-12 16:57:15 -0700384 }
385 }
Ben Chengccd6c012009-10-15 14:52:45 -0700386 if (memDiff) selfVerificationSpinLoop(shadowSpace);
Ben Chengd5adae12010-03-26 17:45:28 -0700387
388 /*
389 * Switch to JIT single step mode to stay in the debug interpreter for
390 * one more instruction
391 */
392 if (state == kSVSSingleStep) {
buzbee9f601a92011-02-11 17:48:20 -0800393 self->jitState = kJitSingleStepEnd;
Ben Chengd5adae12010-03-26 17:45:28 -0700394 }
Jeff Hao97319a82009-08-12 16:57:15 -0700395 return true;
396
397 /* If end not been reached, make sure max length not exceeded */
398 } else if (shadowSpace->traceLength >= JIT_MAX_TRACE_LEN) {
399 LOGD("~~~ DbgIntp(%d): CONTROL DIVERGENCE!", self->threadId);
Ben Chengccd6c012009-10-15 14:52:45 -0700400 LOGD("startPC: 0x%x endPC: 0x%x currPC: 0x%x",
Jeff Hao97319a82009-08-12 16:57:15 -0700401 (int)shadowSpace->startPC, (int)shadowSpace->endPC, (int)pc);
402 selfVerificationDumpState(pc, self);
403 selfVerificationDumpTrace(pc, self);
Ben Chengccd6c012009-10-15 14:52:45 -0700404 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700405
406 return true;
407 }
Ben Chengbcdc1de2009-08-21 16:18:46 -0700408 /* Log the instruction address and decoded instruction for debug */
Jeff Hao97319a82009-08-12 16:57:15 -0700409 shadowSpace->trace[shadowSpace->traceLength].addr = (int)pc;
Ben Chengbcdc1de2009-08-21 16:18:46 -0700410 shadowSpace->trace[shadowSpace->traceLength].decInsn = decInsn;
Jeff Hao97319a82009-08-12 16:57:15 -0700411 shadowSpace->traceLength++;
412
413 return false;
414}
415#endif
416
Ben Chengba4fc8b2009-06-01 13:00:29 -0700417/*
418 * If one of our fixed tables or the translation buffer fills up,
419 * call this routine to avoid wasting cycles on future translation requests.
420 */
421void dvmJitStopTranslationRequests()
422{
423 /*
424 * Note 1: This won't necessarily stop all translation requests, and
425 * operates on a delayed mechanism. Running threads look to the copy
buzbee9f601a92011-02-11 17:48:20 -0800426 * of this value in their private thread structures and won't see
Ben Chengba4fc8b2009-06-01 13:00:29 -0700427 * this change until it is refreshed (which happens on interpreter
428 * entry).
429 * Note 2: This is a one-shot memory leak on this table. Because this is a
430 * permanent off switch for Jit profiling, it is a one-time leak of 1K
431 * bytes, and no further attempt will be made to re-allocate it. Can't
432 * free it because some thread may be holding a reference.
433 */
Bill Buzbeeb1d80442009-12-17 14:55:21 -0800434 gDvmJit.pProfTable = NULL;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700435}
436
Ben Cheng978738d2010-05-13 13:45:57 -0700437#if defined(WITH_JIT_TUNING)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700438/* Convenience function to increment counter from assembly code */
Ben Cheng6c10a972009-10-29 14:39:18 -0700439void dvmBumpNoChain(int from)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700440{
Ben Cheng6c10a972009-10-29 14:39:18 -0700441 gDvmJit.noChainExit[from]++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700442}
443
444/* Convenience function to increment counter from assembly code */
445void dvmBumpNormal()
446{
Ben Cheng6c10a972009-10-29 14:39:18 -0700447 gDvmJit.normalExit++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700448}
449
450/* Convenience function to increment counter from assembly code */
451void dvmBumpPunt(int from)
452{
Ben Cheng6c10a972009-10-29 14:39:18 -0700453 gDvmJit.puntExit++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700454}
455#endif
456
457/* Dumps debugging & tuning stats to the log */
458void dvmJitStats()
459{
460 int i;
461 int hit;
462 int not_hit;
463 int chains;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800464 int stubs;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700465 if (gDvmJit.pJitEntryTable) {
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800466 for (i=0, stubs=chains=hit=not_hit=0;
Bill Buzbee27176222009-06-09 09:20:16 -0700467 i < (int) gDvmJit.jitTableSize;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700468 i++) {
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800469 if (gDvmJit.pJitEntryTable[i].dPC != 0) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700470 hit++;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800471 if (gDvmJit.pJitEntryTable[i].codeAddress ==
Bill Buzbeebd047242010-05-13 13:02:53 -0700472 dvmCompilerGetInterpretTemplate())
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800473 stubs++;
474 } else
Ben Chengba4fc8b2009-06-01 13:00:29 -0700475 not_hit++;
Bill Buzbee716f1202009-07-23 13:22:09 -0700476 if (gDvmJit.pJitEntryTable[i].u.info.chain != gDvmJit.jitTableSize)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700477 chains++;
478 }
Ben Cheng72621c92010-03-10 13:12:55 -0800479 LOGD("JIT: table size is %d, entries used is %d",
Ben Cheng86717f72010-03-05 15:27:21 -0800480 gDvmJit.jitTableSize, gDvmJit.jitTableEntriesUsed);
Ben Cheng72621c92010-03-10 13:12:55 -0800481 LOGD("JIT: %d traces, %d slots, %d chains, %d thresh, %s",
482 hit, not_hit + hit, chains, gDvmJit.threshold,
483 gDvmJit.blockingMode ? "Blocking" : "Non-blocking");
Ben Cheng86717f72010-03-05 15:27:21 -0800484
Ben Cheng978738d2010-05-13 13:45:57 -0700485#if defined(WITH_JIT_TUNING)
486 LOGD("JIT: Code cache patches: %d", gDvmJit.codeCachePatches);
487
Ben Cheng72621c92010-03-10 13:12:55 -0800488 LOGD("JIT: Lookups: %d hits, %d misses; %d normal, %d punt",
489 gDvmJit.addrLookupsFound, gDvmJit.addrLookupsNotFound,
490 gDvmJit.normalExit, gDvmJit.puntExit);
Ben Cheng452efba2010-04-30 15:14:00 -0700491
Ben Cheng978738d2010-05-13 13:45:57 -0700492 LOGD("JIT: ICHits: %d", gDvmICHitCount);
493
Ben Cheng72621c92010-03-10 13:12:55 -0800494 LOGD("JIT: noChainExit: %d IC miss, %d interp callsite, "
495 "%d switch overflow",
496 gDvmJit.noChainExit[kInlineCacheMiss],
497 gDvmJit.noChainExit[kCallsiteInterpreted],
498 gDvmJit.noChainExit[kSwitchOverflow]);
Ben Cheng86717f72010-03-05 15:27:21 -0800499
Ben Chengb88ec3c2010-05-17 12:50:33 -0700500 LOGD("JIT: ICPatch: %d init, %d rejected, %d lock-free, %d queued, "
501 "%d dropped",
502 gDvmJit.icPatchInit, gDvmJit.icPatchRejected,
503 gDvmJit.icPatchLockFree, gDvmJit.icPatchQueued,
Ben Cheng452efba2010-04-30 15:14:00 -0700504 gDvmJit.icPatchDropped);
505
Ben Cheng86717f72010-03-05 15:27:21 -0800506 LOGD("JIT: Invoke: %d mono, %d poly, %d native, %d return",
507 gDvmJit.invokeMonomorphic, gDvmJit.invokePolymorphic,
508 gDvmJit.invokeNative, gDvmJit.returnOp);
Ben Cheng7a2697d2010-06-07 13:44:23 -0700509 LOGD("JIT: Inline: %d mgetter, %d msetter, %d pgetter, %d psetter",
510 gDvmJit.invokeMonoGetterInlined, gDvmJit.invokeMonoSetterInlined,
511 gDvmJit.invokePolyGetterInlined, gDvmJit.invokePolySetterInlined);
Ben Cheng86717f72010-03-05 15:27:21 -0800512 LOGD("JIT: Total compilation time: %llu ms", gDvmJit.jitTime / 1000);
513 LOGD("JIT: Avg unit compilation time: %llu us",
Andy McFaddenb7a797d2011-02-24 16:55:40 -0800514 gDvmJit.numCompilations == 0 ? 0 :
Ben Cheng86717f72010-03-05 15:27:21 -0800515 gDvmJit.jitTime / gDvmJit.numCompilations);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700516#endif
Ben Cheng86717f72010-03-05 15:27:21 -0800517
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800518 LOGD("JIT: %d Translation chains, %d interp stubs",
519 gDvmJit.translationChains, stubs);
buzbee2e152ba2010-12-15 16:32:35 -0800520 if (gDvmJit.profileMode == kTraceProfilingContinuous) {
Bill Buzbee716f1202009-07-23 13:22:09 -0700521 dvmCompilerSortAndPrintTraceProfiles();
Bill Buzbee6e963e12009-06-17 16:56:19 -0700522 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700523 }
524}
525
Bill Buzbee716f1202009-07-23 13:22:09 -0700526
Bill Buzbee1b3da592011-02-03 07:38:22 -0800527/* End current trace after last successful instruction */
buzbee9f601a92011-02-11 17:48:20 -0800528void dvmJitEndTraceSelect(Thread* self)
Bill Buzbeed7269912009-11-10 14:31:32 -0800529{
buzbee9f601a92011-02-11 17:48:20 -0800530 if (self->jitState == kJitTSelect)
531 self->jitState = kJitTSelectEnd;
Bill Buzbeed7269912009-11-10 14:31:32 -0800532}
533
Ben Chengba4fc8b2009-06-01 13:00:29 -0700534/*
Bill Buzbee964a7b02010-01-28 12:54:19 -0800535 * Find an entry in the JitTable, creating if necessary.
536 * Returns null if table is full.
537 */
Ben Chengcfdeca32011-01-14 11:36:46 -0800538static JitEntry *lookupAndAdd(const u2* dPC, bool callerLocked,
539 bool isMethodEntry)
Bill Buzbee964a7b02010-01-28 12:54:19 -0800540{
541 u4 chainEndMarker = gDvmJit.jitTableSize;
542 u4 idx = dvmJitHash(dPC);
543
Ben Chengcfdeca32011-01-14 11:36:46 -0800544 /*
545 * Walk the bucket chain to find an exact match for our PC and trace/method
546 * type
547 */
Bill Buzbee964a7b02010-01-28 12:54:19 -0800548 while ((gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) &&
Ben Chengcfdeca32011-01-14 11:36:46 -0800549 ((gDvmJit.pJitEntryTable[idx].dPC != dPC) ||
550 (gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry !=
551 isMethodEntry))) {
Bill Buzbee964a7b02010-01-28 12:54:19 -0800552 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
553 }
554
Ben Chengcfdeca32011-01-14 11:36:46 -0800555 if (gDvmJit.pJitEntryTable[idx].dPC != dPC ||
556 gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry != isMethodEntry) {
Bill Buzbee964a7b02010-01-28 12:54:19 -0800557 /*
558 * No match. Aquire jitTableLock and find the last
559 * slot in the chain. Possibly continue the chain walk in case
560 * some other thread allocated the slot we were looking
561 * at previuosly (perhaps even the dPC we're trying to enter).
562 */
563 if (!callerLocked)
564 dvmLockMutex(&gDvmJit.tableLock);
565 /*
566 * At this point, if .dPC is NULL, then the slot we're
567 * looking at is the target slot from the primary hash
568 * (the simple, and common case). Otherwise we're going
569 * to have to find a free slot and chain it.
570 */
Andy McFadden6e10b9a2010-06-14 15:24:39 -0700571 ANDROID_MEMBAR_FULL(); /* Make sure we reload [].dPC after lock */
Bill Buzbee964a7b02010-01-28 12:54:19 -0800572 if (gDvmJit.pJitEntryTable[idx].dPC != NULL) {
573 u4 prev;
574 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
Ben Chengcfdeca32011-01-14 11:36:46 -0800575 if (gDvmJit.pJitEntryTable[idx].dPC == dPC &&
576 gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry ==
577 isMethodEntry) {
Bill Buzbee964a7b02010-01-28 12:54:19 -0800578 /* Another thread got there first for this dPC */
579 if (!callerLocked)
580 dvmUnlockMutex(&gDvmJit.tableLock);
581 return &gDvmJit.pJitEntryTable[idx];
582 }
583 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
584 }
585 /* Here, idx should be pointing to the last cell of an
586 * active chain whose last member contains a valid dPC */
587 assert(gDvmJit.pJitEntryTable[idx].dPC != NULL);
588 /* Linear walk to find a free cell and add it to the end */
589 prev = idx;
590 while (true) {
591 idx++;
592 if (idx == chainEndMarker)
593 idx = 0; /* Wraparound */
594 if ((gDvmJit.pJitEntryTable[idx].dPC == NULL) ||
595 (idx == prev))
596 break;
597 }
598 if (idx != prev) {
599 JitEntryInfoUnion oldValue;
600 JitEntryInfoUnion newValue;
601 /*
602 * Although we hold the lock so that noone else will
603 * be trying to update a chain field, the other fields
604 * packed into the word may be in use by other threads.
605 */
606 do {
607 oldValue = gDvmJit.pJitEntryTable[prev].u;
608 newValue = oldValue;
609 newValue.info.chain = idx;
Andy McFadden6e10b9a2010-06-14 15:24:39 -0700610 } while (android_atomic_release_cas(oldValue.infoWord,
611 newValue.infoWord,
612 &gDvmJit.pJitEntryTable[prev].u.infoWord) != 0);
Bill Buzbee964a7b02010-01-28 12:54:19 -0800613 }
614 }
615 if (gDvmJit.pJitEntryTable[idx].dPC == NULL) {
Ben Chengcfdeca32011-01-14 11:36:46 -0800616 gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry = isMethodEntry;
Bill Buzbee964a7b02010-01-28 12:54:19 -0800617 /*
618 * Initialize codeAddress and allocate the slot. Must
619 * happen in this order (since dPC is set, the entry is live.
620 */
Ben Chengcfdeca32011-01-14 11:36:46 -0800621 android_atomic_release_store((int32_t)dPC,
622 (volatile int32_t *)(void *)&gDvmJit.pJitEntryTable[idx].dPC);
Bill Buzbee964a7b02010-01-28 12:54:19 -0800623 gDvmJit.pJitEntryTable[idx].dPC = dPC;
624 gDvmJit.jitTableEntriesUsed++;
625 } else {
626 /* Table is full */
627 idx = chainEndMarker;
628 }
629 if (!callerLocked)
630 dvmUnlockMutex(&gDvmJit.tableLock);
631 }
632 return (idx == chainEndMarker) ? NULL : &gDvmJit.pJitEntryTable[idx];
633}
Ben Chenga4973592010-03-31 11:59:18 -0700634
Bill Buzbee964a7b02010-01-28 12:54:19 -0800635/*
Ben Cheng7a2697d2010-06-07 13:44:23 -0700636 * Append the class ptr of "this" and the current method ptr to the current
637 * trace. That is, the trace runs will contain the following components:
638 * + trace run that ends with an invoke (existing entry)
639 * + thisClass (new)
640 * + calleeMethod (new)
641 */
buzbee9f601a92011-02-11 17:48:20 -0800642static void insertClassMethodInfo(Thread* self,
Ben Cheng7a2697d2010-06-07 13:44:23 -0700643 const ClassObject* thisClass,
644 const Method* calleeMethod,
645 const DecodedInstruction* insn)
646{
buzbee9f601a92011-02-11 17:48:20 -0800647 int currTraceRun = ++self->currTraceRun;
648 self->trace[currTraceRun].meta = (void *) thisClass;
649 currTraceRun = ++self->currTraceRun;
650 self->trace[currTraceRun].meta = (void *) calleeMethod;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700651}
652
653/*
Ben Chengd44faf52010-06-02 15:33:51 -0700654 * Check if the next instruction following the invoke is a move-result and if
Ben Cheng7a2697d2010-06-07 13:44:23 -0700655 * so add it to the trace. That is, this will add the trace run that includes
656 * the move-result to the trace list.
657 *
658 * + trace run that ends with an invoke (existing entry)
659 * + thisClass (existing entry)
660 * + calleeMethod (existing entry)
661 * + move result (new)
Ben Chengd44faf52010-06-02 15:33:51 -0700662 *
663 * lastPC, len, offset are all from the preceding invoke instruction
664 */
665static void insertMoveResult(const u2 *lastPC, int len, int offset,
buzbee9f601a92011-02-11 17:48:20 -0800666 Thread *self)
Ben Chengd44faf52010-06-02 15:33:51 -0700667{
668 DecodedInstruction nextDecInsn;
669 const u2 *moveResultPC = lastPC + len;
670
Dan Bornstein54322392010-11-17 14:16:56 -0800671 dexDecodeInstruction(moveResultPC, &nextDecInsn);
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800672 if ((nextDecInsn.opcode != OP_MOVE_RESULT) &&
673 (nextDecInsn.opcode != OP_MOVE_RESULT_WIDE) &&
674 (nextDecInsn.opcode != OP_MOVE_RESULT_OBJECT))
Ben Chengd44faf52010-06-02 15:33:51 -0700675 return;
676
677 /* We need to start a new trace run */
buzbee9f601a92011-02-11 17:48:20 -0800678 int currTraceRun = ++self->currTraceRun;
679 self->currRunHead = moveResultPC;
680 self->trace[currTraceRun].frag.startOffset = offset + len;
681 self->trace[currTraceRun].frag.numInsts = 1;
682 self->trace[currTraceRun].frag.runEnd = false;
683 self->trace[currTraceRun].frag.hint = kJitHintNone;
684 self->trace[currTraceRun].frag.isCode = true;
685 self->totalTraceLen++;
Ben Chengd44faf52010-06-02 15:33:51 -0700686
buzbee9f601a92011-02-11 17:48:20 -0800687 self->currRunLen = dexGetWidthFromInstruction(moveResultPC);
Ben Chengd44faf52010-06-02 15:33:51 -0700688}
689
690/*
Ben Chengba4fc8b2009-06-01 13:00:29 -0700691 * Adds to the current trace request one instruction at a time, just
692 * before that instruction is interpreted. This is the primary trace
693 * selection function. NOTE: return instruction are handled a little
694 * differently. In general, instructions are "proposed" to be added
695 * to the current trace prior to interpretation. If the interpreter
696 * then successfully completes the instruction, is will be considered
697 * part of the request. This allows us to examine machine state prior
698 * to interpretation, and also abort the trace request if the instruction
699 * throws or does something unexpected. However, return instructions
700 * will cause an immediate end to the translation request - which will
701 * be passed to the compiler before the return completes. This is done
702 * in response to special handling of returns by the interpreter (and
703 * because returns cannot throw in a way that causes problems for the
704 * translated code.
705 */
buzbee9f601a92011-02-11 17:48:20 -0800706int dvmCheckJit(const u2* pc, Thread* self, const ClassObject* thisClass,
707 const Method* curMethod)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700708{
Carl Shapiroe3c01da2010-05-20 22:54:18 -0700709 int flags, len;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700710 int switchInterp = false;
Ben Chenga4973592010-03-31 11:59:18 -0700711 bool debugOrProfile = dvmDebuggerOrProfilerActive();
Ben Cheng7a2697d2010-06-07 13:44:23 -0700712 /* Stay in the dbg interpreter for the next instruction */
713 bool stayOneMoreInst = false;
Bill Buzbeed7269912009-11-10 14:31:32 -0800714
Ben Cheng1c52e6d2010-07-02 13:00:39 -0700715 /*
716 * Bug 2710533 - dalvik crash when disconnecting debugger
717 *
718 * Reset the entry point to the default value. If needed it will be set to a
719 * specific value in the corresponding case statement (eg kJitSingleStepEnd)
720 */
buzbee9f601a92011-02-11 17:48:20 -0800721 self->entryPoint = kInterpEntryInstr;
Ben Cheng1c52e6d2010-07-02 13:00:39 -0700722
Ben Cheng79d173c2009-09-29 16:12:51 -0700723 /* Prepare to handle last PC and stage the current PC */
buzbee9f601a92011-02-11 17:48:20 -0800724 const u2 *lastPC = self->lastPC;
725 self->lastPC = pc;
Ben Cheng79d173c2009-09-29 16:12:51 -0700726
buzbee9f601a92011-02-11 17:48:20 -0800727 switch (self->jitState) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700728 int offset;
729 DecodedInstruction decInsn;
730 case kJitTSelect:
Ben Chengdc84bb22009-10-02 12:58:52 -0700731 /* First instruction - just remember the PC and exit */
732 if (lastPC == NULL) break;
Ben Cheng79d173c2009-09-29 16:12:51 -0700733 /* Grow the trace around the last PC if jitState is kJitTSelect */
Dan Bornstein54322392010-11-17 14:16:56 -0800734 dexDecodeInstruction(lastPC, &decInsn);
Ben Cheng6c10a972009-10-29 14:39:18 -0700735
736 /*
737 * Treat {PACKED,SPARSE}_SWITCH as trace-ending instructions due
738 * to the amount of space it takes to generate the chaining
739 * cells.
740 */
buzbee9f601a92011-02-11 17:48:20 -0800741 if (self->totalTraceLen != 0 &&
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800742 (decInsn.opcode == OP_PACKED_SWITCH ||
743 decInsn.opcode == OP_SPARSE_SWITCH)) {
buzbee9f601a92011-02-11 17:48:20 -0800744 self->jitState = kJitTSelectEnd;
Ben Cheng6c10a972009-10-29 14:39:18 -0700745 break;
746 }
747
Bill Buzbeef9f33282009-11-22 12:45:30 -0800748
Ben Chengba4fc8b2009-06-01 13:00:29 -0700749#if defined(SHOW_TRACE)
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800750 LOGD("TraceGen: adding %s", dexGetOpcodeName(decInsn.opcode));
Ben Chengba4fc8b2009-06-01 13:00:29 -0700751#endif
Dan Bornsteine4852762010-12-02 12:45:00 -0800752 flags = dexGetFlagsFromOpcode(decInsn.opcode);
753 len = dexGetWidthFromInstruction(lastPC);
buzbee9f601a92011-02-11 17:48:20 -0800754 offset = lastPC - self->interpSave.method->insns;
Ben Cheng79d173c2009-09-29 16:12:51 -0700755 assert((unsigned) offset <
buzbee9f601a92011-02-11 17:48:20 -0800756 dvmGetMethodInsnsSize(self->interpSave.method));
757 if (lastPC != self->currRunHead + self->currRunLen) {
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700758 int currTraceRun;
759 /* We need to start a new trace run */
buzbee9f601a92011-02-11 17:48:20 -0800760 currTraceRun = ++self->currTraceRun;
761 self->currRunLen = 0;
762 self->currRunHead = (u2*)lastPC;
763 self->trace[currTraceRun].frag.startOffset = offset;
764 self->trace[currTraceRun].frag.numInsts = 0;
765 self->trace[currTraceRun].frag.runEnd = false;
766 self->trace[currTraceRun].frag.hint = kJitHintNone;
767 self->trace[currTraceRun].frag.isCode = true;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700768 }
buzbee9f601a92011-02-11 17:48:20 -0800769 self->trace[self->currTraceRun].frag.numInsts++;
770 self->totalTraceLen++;
771 self->currRunLen += len;
Ben Cheng79d173c2009-09-29 16:12:51 -0700772
Ben Chengd44faf52010-06-02 15:33:51 -0700773 /*
774 * If the last instruction is an invoke, we will try to sneak in
775 * the move-result* (if existent) into a separate trace run.
776 */
777 int needReservedRun = (flags & kInstrInvoke) ? 1 : 0;
778
Ben Cheng79d173c2009-09-29 16:12:51 -0700779 /* Will probably never hit this with the current trace buildier */
buzbee9f601a92011-02-11 17:48:20 -0800780 if (self->currTraceRun ==
Ben Chengd44faf52010-06-02 15:33:51 -0700781 (MAX_JIT_RUN_LEN - 1 - needReservedRun)) {
buzbee9f601a92011-02-11 17:48:20 -0800782 self->jitState = kJitTSelectEnd;
Ben Cheng79d173c2009-09-29 16:12:51 -0700783 }
784
Dan Bornsteinc2b486f2010-11-12 16:07:16 -0800785 if (!dexIsGoto(flags) &&
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700786 ((flags & (kInstrCanBranch |
787 kInstrCanSwitch |
788 kInstrCanReturn |
789 kInstrInvoke)) != 0)) {
buzbee9f601a92011-02-11 17:48:20 -0800790 self->jitState = kJitTSelectEnd;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700791#if defined(SHOW_TRACE)
Ben Chengd44faf52010-06-02 15:33:51 -0700792 LOGD("TraceGen: ending on %s, basic block end",
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800793 dexGetOpcodeName(decInsn.opcode));
Ben Chengba4fc8b2009-06-01 13:00:29 -0700794#endif
Ben Chengd44faf52010-06-02 15:33:51 -0700795
796 /*
Ben Cheng7a2697d2010-06-07 13:44:23 -0700797 * If the current invoke is a {virtual,interface}, get the
798 * current class/method pair into the trace as well.
Ben Chengd44faf52010-06-02 15:33:51 -0700799 * If the next instruction is a variant of move-result, insert
Ben Cheng7a2697d2010-06-07 13:44:23 -0700800 * it to the trace too.
Ben Chengd44faf52010-06-02 15:33:51 -0700801 */
802 if (flags & kInstrInvoke) {
buzbee9f601a92011-02-11 17:48:20 -0800803 insertClassMethodInfo(self, thisClass, curMethod,
Ben Cheng7a2697d2010-06-07 13:44:23 -0700804 &decInsn);
buzbee9f601a92011-02-11 17:48:20 -0800805 insertMoveResult(lastPC, len, offset, self);
Ben Chengd44faf52010-06-02 15:33:51 -0700806 }
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700807 }
Bill Buzbee2ce8a6c2009-12-03 15:09:32 -0800808 /* Break on throw or self-loop */
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800809 if ((decInsn.opcode == OP_THROW) || (lastPC == pc)){
buzbee9f601a92011-02-11 17:48:20 -0800810 self->jitState = kJitTSelectEnd;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700811 }
buzbee9f601a92011-02-11 17:48:20 -0800812 if (self->totalTraceLen >= JIT_MAX_TRACE_LEN) {
813 self->jitState = kJitTSelectEnd;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700814 }
Ben Chenga4973592010-03-31 11:59:18 -0700815 /* Abandon the trace request if debugger/profiler is attached */
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700816 if (debugOrProfile) {
buzbee9f601a92011-02-11 17:48:20 -0800817 self->jitState = kJitDone;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700818 break;
819 }
820 if ((flags & kInstrCanReturn) != kInstrCanReturn) {
821 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700822 }
Ben Cheng7a2697d2010-06-07 13:44:23 -0700823 else {
824 /*
825 * Last instruction is a return - stay in the dbg interpreter
826 * for one more instruction if it is a non-void return, since
827 * we don't want to start a trace with move-result as the first
828 * instruction (which is already included in the trace
829 * containing the invoke.
830 */
Dan Bornstein9a1f8162010-12-01 17:02:26 -0800831 if (decInsn.opcode != OP_RETURN_VOID) {
Ben Cheng7a2697d2010-06-07 13:44:23 -0700832 stayOneMoreInst = true;
833 }
834 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700835 /* NOTE: intentional fallthrough for returns */
836 case kJitTSelectEnd:
837 {
Bill Buzbee1b3da592011-02-03 07:38:22 -0800838 /* Empty trace - set to bail to interpreter */
buzbee9f601a92011-02-11 17:48:20 -0800839 if (self->totalTraceLen == 0) {
840 dvmJitSetCodeAddr(self->currTraceHead,
Bill Buzbee1b3da592011-02-03 07:38:22 -0800841 dvmCompilerGetInterpretTemplate(),
842 dvmCompilerGetInterpretTemplateSet(),
843 false /* Not method entry */, 0);
buzbee9f601a92011-02-11 17:48:20 -0800844 self->jitState = kJitDone;
Ben Chenga4973592010-03-31 11:59:18 -0700845 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700846 break;
847 }
Ben Cheng7a2697d2010-06-07 13:44:23 -0700848
buzbee9f601a92011-02-11 17:48:20 -0800849 int lastTraceDesc = self->currTraceRun;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700850
851 /* Extend a new empty desc if the last slot is meta info */
buzbee9f601a92011-02-11 17:48:20 -0800852 if (!self->trace[lastTraceDesc].frag.isCode) {
853 lastTraceDesc = ++self->currTraceRun;
854 self->trace[lastTraceDesc].frag.startOffset = 0;
855 self->trace[lastTraceDesc].frag.numInsts = 0;
856 self->trace[lastTraceDesc].frag.hint = kJitHintNone;
857 self->trace[lastTraceDesc].frag.isCode = true;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700858 }
859
860 /* Mark the end of the trace runs */
buzbee9f601a92011-02-11 17:48:20 -0800861 self->trace[lastTraceDesc].frag.runEnd = true;
Ben Cheng7a2697d2010-06-07 13:44:23 -0700862
Ben Chengba4fc8b2009-06-01 13:00:29 -0700863 JitTraceDescription* desc =
864 (JitTraceDescription*)malloc(sizeof(JitTraceDescription) +
buzbee9f601a92011-02-11 17:48:20 -0800865 sizeof(JitTraceRun) * (self->currTraceRun+1));
Ben Cheng7a2697d2010-06-07 13:44:23 -0700866
Ben Chengba4fc8b2009-06-01 13:00:29 -0700867 if (desc == NULL) {
868 LOGE("Out of memory in trace selection");
869 dvmJitStopTranslationRequests();
buzbee9f601a92011-02-11 17:48:20 -0800870 self->jitState = kJitDone;
Ben Chenga4973592010-03-31 11:59:18 -0700871 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700872 break;
873 }
Ben Cheng7a2697d2010-06-07 13:44:23 -0700874
buzbee9f601a92011-02-11 17:48:20 -0800875 desc->method = self->interpSave.method;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700876 memcpy((char*)&(desc->trace[0]),
buzbee9f601a92011-02-11 17:48:20 -0800877 (char*)&(self->trace[0]),
878 sizeof(JitTraceRun) * (self->currTraceRun+1));
Ben Chengba4fc8b2009-06-01 13:00:29 -0700879#if defined(SHOW_TRACE)
880 LOGD("TraceGen: trace done, adding to queue");
881#endif
Bill Buzbee964a7b02010-01-28 12:54:19 -0800882 if (dvmCompilerWorkEnqueue(
buzbee9f601a92011-02-11 17:48:20 -0800883 self->currTraceHead,kWorkOrderTrace,desc)) {
Bill Buzbee964a7b02010-01-28 12:54:19 -0800884 /* Work order successfully enqueued */
885 if (gDvmJit.blockingMode) {
886 dvmCompilerDrainQueue();
887 }
Ben Cheng1357e942010-02-10 17:21:39 -0800888 } else {
889 /*
890 * Make sure the descriptor for the abandoned work order is
891 * freed.
892 */
893 free(desc);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700894 }
buzbee9f601a92011-02-11 17:48:20 -0800895 self->jitState = kJitDone;
Ben Chenga4973592010-03-31 11:59:18 -0700896 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700897 }
898 break;
899 case kJitSingleStep:
buzbee9f601a92011-02-11 17:48:20 -0800900 self->jitState = kJitSingleStepEnd;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700901 break;
902 case kJitSingleStepEnd:
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700903 /*
904 * Clear the inJitCodeCache flag and abandon the resume attempt if
905 * we cannot switch back to the translation due to corner-case
906 * conditions. If the flag is not cleared and the code cache is full
907 * we will be stuck in the debug interpreter as the code cache
908 * cannot be reset.
909 */
910 if (dvmJitStayInPortableInterpreter()) {
buzbee9f601a92011-02-11 17:48:20 -0800911 self->entryPoint = kInterpEntryInstr;
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700912 self->inJitCodeCache = 0;
913 } else {
buzbee9f601a92011-02-11 17:48:20 -0800914 self->entryPoint = kInterpEntryResume;
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700915 }
buzbee9f601a92011-02-11 17:48:20 -0800916 self->jitState = kJitDone;
Ben Chenga4973592010-03-31 11:59:18 -0700917 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700918 break;
Ben Chenga4973592010-03-31 11:59:18 -0700919 case kJitDone:
920 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700921 break;
Jeff Hao97319a82009-08-12 16:57:15 -0700922#if defined(WITH_SELF_VERIFICATION)
923 case kJitSelfVerification:
buzbee9f601a92011-02-11 17:48:20 -0800924 if (selfVerificationDebugInterp(pc, self)) {
Ben Chengd5adae12010-03-26 17:45:28 -0700925 /*
926 * If the next state is not single-step end, we can switch
927 * interpreter now.
928 */
buzbee9f601a92011-02-11 17:48:20 -0800929 if (self->jitState != kJitSingleStepEnd) {
930 self->jitState = kJitDone;
Ben Chenga4973592010-03-31 11:59:18 -0700931 switchInterp = true;
Ben Chengd5adae12010-03-26 17:45:28 -0700932 }
Jeff Hao97319a82009-08-12 16:57:15 -0700933 }
934 break;
935#endif
Ben Chenga4973592010-03-31 11:59:18 -0700936 case kJitNot:
Ben Cheng1c52e6d2010-07-02 13:00:39 -0700937 switchInterp = !debugOrProfile;
Ben Chenged79ff02009-10-13 13:26:40 -0700938 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700939 default:
Ben Chenga4973592010-03-31 11:59:18 -0700940 LOGE("Unexpected JIT state: %d entry point: %d",
buzbee9f601a92011-02-11 17:48:20 -0800941 self->jitState, self->entryPoint);
Ben Chenga4973592010-03-31 11:59:18 -0700942 dvmAbort();
Ben Cheng9c147b82009-10-07 16:41:46 -0700943 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700944 }
Ben Chenga4973592010-03-31 11:59:18 -0700945 /*
946 * Final check to see if we can really switch the interpreter. Make sure
947 * the jitState is kJitDone or kJitNot when switchInterp is set to true.
948 */
buzbee9f601a92011-02-11 17:48:20 -0800949 assert(switchInterp == false || self->jitState == kJitDone ||
950 self->jitState == kJitNot);
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700951 return switchInterp && !debugOrProfile && !stayOneMoreInst &&
952 !dvmJitStayInPortableInterpreter();
Ben Chengba4fc8b2009-06-01 13:00:29 -0700953}
954
Bill Buzbee1b3da592011-02-03 07:38:22 -0800955JitEntry *dvmJitFindEntry(const u2* pc, bool isMethodEntry)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700956{
957 int idx = dvmJitHash(pc);
958
959 /* Expect a high hit rate on 1st shot */
Bill Buzbee1b3da592011-02-03 07:38:22 -0800960 if ((gDvmJit.pJitEntryTable[idx].dPC == pc) &&
961 (gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry == isMethodEntry))
Ben Chengba4fc8b2009-06-01 13:00:29 -0700962 return &gDvmJit.pJitEntryTable[idx];
963 else {
Bill Buzbee27176222009-06-09 09:20:16 -0700964 int chainEndMarker = gDvmJit.jitTableSize;
Bill Buzbee716f1202009-07-23 13:22:09 -0700965 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
966 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
Bill Buzbee1b3da592011-02-03 07:38:22 -0800967 if ((gDvmJit.pJitEntryTable[idx].dPC == pc) &&
968 (gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry ==
969 isMethodEntry))
Ben Chengba4fc8b2009-06-01 13:00:29 -0700970 return &gDvmJit.pJitEntryTable[idx];
971 }
972 }
973 return NULL;
974}
975
Bill Buzbee27176222009-06-09 09:20:16 -0700976/*
Ben Chengcfdeca32011-01-14 11:36:46 -0800977 * Walk through the JIT profile table and find the corresponding JIT code, in
978 * the specified format (ie trace vs method). This routine needs to be fast.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700979 */
Ben Chengcfdeca32011-01-14 11:36:46 -0800980void* getCodeAddrCommon(const u2* dPC, bool methodEntry)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700981{
982 int idx = dvmJitHash(dPC);
Ben Chengcfdeca32011-01-14 11:36:46 -0800983 const u2* pc = gDvmJit.pJitEntryTable[idx].dPC;
984 if (pc != NULL) {
Ben Cheng1a7b9d72010-09-20 22:20:31 -0700985 bool hideTranslation = dvmJitHideTranslation();
Ben Chengcfdeca32011-01-14 11:36:46 -0800986 if (pc == dPC &&
987 gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry == methodEntry) {
buzbee2e152ba2010-12-15 16:32:35 -0800988 int offset = (gDvmJit.profileMode >= kTraceProfilingContinuous) ?
989 0 : gDvmJit.pJitEntryTable[idx].u.info.profileOffset;
990 intptr_t codeAddress =
991 (intptr_t)gDvmJit.pJitEntryTable[idx].codeAddress;
Ben Cheng978738d2010-05-13 13:45:57 -0700992#if defined(WITH_JIT_TUNING)
Bill Buzbee9797a232010-01-12 12:20:13 -0800993 gDvmJit.addrLookupsFound++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700994#endif
buzbee99ddb1e2011-01-28 10:44:30 -0800995 return hideTranslation || !codeAddress ? NULL :
996 (void *)(codeAddress + offset);
Bill Buzbee9797a232010-01-12 12:20:13 -0800997 } else {
998 int chainEndMarker = gDvmJit.jitTableSize;
999 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
1000 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
Ben Chengcfdeca32011-01-14 11:36:46 -08001001 if (gDvmJit.pJitEntryTable[idx].dPC == dPC &&
1002 gDvmJit.pJitEntryTable[idx].u.info.isMethodEntry ==
1003 methodEntry) {
buzbee2e152ba2010-12-15 16:32:35 -08001004 int offset = (gDvmJit.profileMode >=
1005 kTraceProfilingContinuous) ? 0 :
1006 gDvmJit.pJitEntryTable[idx].u.info.profileOffset;
1007 intptr_t codeAddress =
1008 (intptr_t)gDvmJit.pJitEntryTable[idx].codeAddress;
Ben Cheng978738d2010-05-13 13:45:57 -07001009#if defined(WITH_JIT_TUNING)
Bill Buzbee9797a232010-01-12 12:20:13 -08001010 gDvmJit.addrLookupsFound++;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001011#endif
buzbee99ddb1e2011-01-28 10:44:30 -08001012 return hideTranslation || !codeAddress ? NULL :
buzbee2e152ba2010-12-15 16:32:35 -08001013 (void *)(codeAddress + offset);
Bill Buzbee9797a232010-01-12 12:20:13 -08001014 }
Ben Chengba4fc8b2009-06-01 13:00:29 -07001015 }
1016 }
1017 }
Ben Cheng978738d2010-05-13 13:45:57 -07001018#if defined(WITH_JIT_TUNING)
Ben Chengba4fc8b2009-06-01 13:00:29 -07001019 gDvmJit.addrLookupsNotFound++;
1020#endif
1021 return NULL;
1022}
1023
1024/*
Ben Chengcfdeca32011-01-14 11:36:46 -08001025 * If a translated code address, in trace format, exists for the davik byte code
1026 * pointer return it.
1027 */
1028void* dvmJitGetTraceAddr(const u2* dPC)
1029{
1030 return getCodeAddrCommon(dPC, false /* method entry */);
1031}
1032
1033/*
1034 * If a translated code address, in whole-method format, exists for the davik
1035 * byte code pointer return it.
1036 */
1037void* dvmJitGetMethodAddr(const u2* dPC)
1038{
1039 return getCodeAddrCommon(dPC, true /* method entry */);
1040}
1041
1042/*
Ben Chengba4fc8b2009-06-01 13:00:29 -07001043 * Register the translated code pointer into the JitTable.
Bill Buzbee9a8c75a2009-11-08 14:31:20 -08001044 * NOTE: Once a codeAddress field transitions from initial state to
Ben Chengba4fc8b2009-06-01 13:00:29 -07001045 * JIT'd code, it must not be altered without first halting all
Bill Buzbee716f1202009-07-23 13:22:09 -07001046 * threads. This routine should only be called by the compiler
buzbee2e152ba2010-12-15 16:32:35 -08001047 * thread. We defer the setting of the profile prefix size until
1048 * after the new code address is set to ensure that the prefix offset
1049 * is never applied to the initial interpret-only translation. All
1050 * translations with non-zero profile prefixes will still be correct
1051 * if entered as if the profile offset is 0, but the interpret-only
1052 * template cannot handle a non-zero prefix.
Ben Chengba4fc8b2009-06-01 13:00:29 -07001053 */
buzbee2e152ba2010-12-15 16:32:35 -08001054void dvmJitSetCodeAddr(const u2* dPC, void *nPC, JitInstructionSetType set,
Ben Chengcfdeca32011-01-14 11:36:46 -08001055 bool isMethodEntry, int profilePrefixSize)
buzbee2e152ba2010-12-15 16:32:35 -08001056{
Bill Buzbee716f1202009-07-23 13:22:09 -07001057 JitEntryInfoUnion oldValue;
1058 JitEntryInfoUnion newValue;
Ben Cheng20d7e6c2011-02-18 17:12:42 -08001059 /*
1060 * Method-based JIT doesn't go through the normal profiling phase, so use
1061 * lookupAndAdd here to request a new entry in the table.
1062 */
1063 JitEntry *jitEntry = isMethodEntry ?
1064 lookupAndAdd(dPC, false /* caller locked */, true) :
1065 dvmJitFindEntry(dPC, isMethodEntry);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001066 assert(jitEntry);
Bill Buzbee716f1202009-07-23 13:22:09 -07001067 /* Note: order of update is important */
1068 do {
1069 oldValue = jitEntry->u;
1070 newValue = oldValue;
Ben Chengcfdeca32011-01-14 11:36:46 -08001071 newValue.info.isMethodEntry = isMethodEntry;
Bill Buzbee716f1202009-07-23 13:22:09 -07001072 newValue.info.instructionSet = set;
buzbee99ddb1e2011-01-28 10:44:30 -08001073 newValue.info.profileOffset = profilePrefixSize;
Andy McFadden6e10b9a2010-06-14 15:24:39 -07001074 } while (android_atomic_release_cas(
1075 oldValue.infoWord, newValue.infoWord,
1076 &jitEntry->u.infoWord) != 0);
Bill Buzbee716f1202009-07-23 13:22:09 -07001077 jitEntry->codeAddress = nPC;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001078}
1079
1080/*
1081 * Determine if valid trace-bulding request is active. Return true
1082 * if we need to abort and switch back to the fast interpreter, false
Ben Chenga4973592010-03-31 11:59:18 -07001083 * otherwise.
Ben Chengba4fc8b2009-06-01 13:00:29 -07001084 */
buzbee9f601a92011-02-11 17:48:20 -08001085bool dvmJitCheckTraceRequest(Thread* self)
Ben Chengba4fc8b2009-06-01 13:00:29 -07001086{
Ben Chenga4973592010-03-31 11:59:18 -07001087 bool switchInterp = false; /* Assume success */
Bill Buzbee48f18242009-06-19 16:02:27 -07001088 int i;
buzbee852aacd2010-06-08 16:24:46 -07001089 /*
1090 * A note on trace "hotness" filtering:
1091 *
1092 * Our first level trigger is intentionally loose - we need it to
1093 * fire easily not just to identify potential traces to compile, but
1094 * also to allow re-entry into the code cache.
1095 *
1096 * The 2nd level filter (done here) exists to be selective about
1097 * what we actually compile. It works by requiring the same
1098 * trace head "key" (defined as filterKey below) to appear twice in
1099 * a relatively short period of time. The difficulty is defining the
1100 * shape of the filterKey. Unfortunately, there is no "one size fits
1101 * all" approach.
1102 *
1103 * For spiky execution profiles dominated by a smallish
1104 * number of very hot loops, we would want the second-level filter
1105 * to be very selective. A good selective filter is requiring an
1106 * exact match of the Dalvik PC. In other words, defining filterKey as:
buzbee9f601a92011-02-11 17:48:20 -08001107 * intptr_t filterKey = (intptr_t)self->interpSave.pc
buzbee852aacd2010-06-08 16:24:46 -07001108 *
1109 * However, for flat execution profiles we do best when aggressively
1110 * translating. A heuristically decent proxy for this is to use
1111 * the value of the method pointer containing the trace as the filterKey.
1112 * Intuitively, this is saying that once any trace in a method appears hot,
1113 * immediately translate any other trace from that same method that
1114 * survives the first-level filter. Here, filterKey would be defined as:
buzbee9f601a92011-02-11 17:48:20 -08001115 * intptr_t filterKey = (intptr_t)self->interpSave.method
buzbee852aacd2010-06-08 16:24:46 -07001116 *
1117 * The problem is that we can't easily detect whether we're dealing
1118 * with a spiky or flat profile. If we go with the "pc" match approach,
1119 * flat profiles perform poorly. If we go with the loose "method" match,
1120 * we end up generating a lot of useless translations. Probably the
1121 * best approach in the future will be to retain profile information
1122 * across runs of each application in order to determine it's profile,
1123 * and then choose once we have enough history.
1124 *
1125 * However, for now we've decided to chose a compromise filter scheme that
1126 * includes elements of both. The high order bits of the filter key
1127 * are drawn from the enclosing method, and are combined with a slice
1128 * of the low-order bits of the Dalvik pc of the trace head. The
1129 * looseness of the filter can be adjusted by changing with width of
1130 * the Dalvik pc slice (JIT_TRACE_THRESH_FILTER_PC_BITS). The wider
1131 * the slice, the tighter the filter.
1132 *
1133 * Note: the fixed shifts in the function below reflect assumed word
1134 * alignment for method pointers, and half-word alignment of the Dalvik pc.
1135 * for method pointers and half-word alignment for dalvik pc.
1136 */
buzbee9f601a92011-02-11 17:48:20 -08001137 u4 methodKey = (u4)self->interpSave.method <<
buzbeec35294d2010-06-09 14:22:50 -07001138 (JIT_TRACE_THRESH_FILTER_PC_BITS - 2);
buzbee9f601a92011-02-11 17:48:20 -08001139 u4 pcKey = ((u4)self->interpSave.pc >> 1) &
buzbeec35294d2010-06-09 14:22:50 -07001140 ((1 << JIT_TRACE_THRESH_FILTER_PC_BITS) - 1);
1141 intptr_t filterKey = (intptr_t)(methodKey | pcKey);
Ben Chenga4973592010-03-31 11:59:18 -07001142 bool debugOrProfile = dvmDebuggerOrProfilerActive();
Ben Cheng40094c12010-02-24 20:58:44 -08001143
Ben Chenga4973592010-03-31 11:59:18 -07001144 /* Check if the JIT request can be handled now */
1145 if (gDvmJit.pJitEntryTable != NULL && debugOrProfile == false) {
1146 /* Bypass the filter for hot trace requests or during stress mode */
buzbee9f601a92011-02-11 17:48:20 -08001147 if (self->jitState == kJitTSelectRequest &&
Ben Chenga4973592010-03-31 11:59:18 -07001148 gDvmJit.threshold > 6) {
Ben Cheng40094c12010-02-24 20:58:44 -08001149 /* Two-level filtering scheme */
1150 for (i=0; i< JIT_TRACE_THRESH_FILTER_SIZE; i++) {
buzbee9f601a92011-02-11 17:48:20 -08001151 if (filterKey == self->threshFilter[i]) {
1152 self->threshFilter[i] = 0; // Reset filter entry
Ben Cheng40094c12010-02-24 20:58:44 -08001153 break;
1154 }
Bill Buzbee48f18242009-06-19 16:02:27 -07001155 }
Ben Cheng40094c12010-02-24 20:58:44 -08001156 if (i == JIT_TRACE_THRESH_FILTER_SIZE) {
1157 /*
1158 * Use random replacement policy - otherwise we could miss a
1159 * large loop that contains more traces than the size of our
1160 * filter array.
1161 */
1162 i = rand() % JIT_TRACE_THRESH_FILTER_SIZE;
buzbee9f601a92011-02-11 17:48:20 -08001163 self->threshFilter[i] = filterKey;
1164 self->jitState = kJitDone;
Ben Cheng40094c12010-02-24 20:58:44 -08001165 }
Ben Chenga4973592010-03-31 11:59:18 -07001166 }
Bill Buzbeed7269912009-11-10 14:31:32 -08001167
Ben Chenga4973592010-03-31 11:59:18 -07001168 /* If the compiler is backlogged, cancel any JIT actions */
1169 if (gDvmJit.compilerQueueLength >= gDvmJit.compilerHighWater) {
buzbee9f601a92011-02-11 17:48:20 -08001170 self->jitState = kJitDone;
Ben Cheng40094c12010-02-24 20:58:44 -08001171 }
Bill Buzbeed7269912009-11-10 14:31:32 -08001172
Ben Chengba4fc8b2009-06-01 13:00:29 -07001173 /*
Ben Chenga4973592010-03-31 11:59:18 -07001174 * Check for additional reasons that might force the trace select
1175 * request to be dropped
Ben Chengba4fc8b2009-06-01 13:00:29 -07001176 */
buzbee9f601a92011-02-11 17:48:20 -08001177 if (self->jitState == kJitTSelectRequest ||
1178 self->jitState == kJitTSelectRequestHot) {
1179 if (dvmJitFindEntry(self->interpSave.pc, false)) {
Bill Buzbee1b3da592011-02-03 07:38:22 -08001180 /* In progress - nothing do do */
buzbee9f601a92011-02-11 17:48:20 -08001181 self->jitState = kJitDone;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001182 } else {
buzbee9f601a92011-02-11 17:48:20 -08001183 JitEntry *slot = lookupAndAdd(self->interpSave.pc,
Bill Buzbee1b3da592011-02-03 07:38:22 -08001184 false /* lock */,
1185 false /* method entry */);
1186 if (slot == NULL) {
1187 /*
1188 * Table is full. This should have been
1189 * detected by the compiler thread and the table
1190 * resized before we run into it here. Assume bad things
1191 * are afoot and disable profiling.
1192 */
buzbee9f601a92011-02-11 17:48:20 -08001193 self->jitState = kJitDone;
Bill Buzbee1b3da592011-02-03 07:38:22 -08001194 LOGD("JIT: JitTable full, disabling profiling");
1195 dvmJitStopTranslationRequests();
1196 }
Ben Chengba4fc8b2009-06-01 13:00:29 -07001197 }
1198 }
Ben Chenga4973592010-03-31 11:59:18 -07001199
buzbee9f601a92011-02-11 17:48:20 -08001200 switch (self->jitState) {
Ben Chengba4fc8b2009-06-01 13:00:29 -07001201 case kJitTSelectRequest:
Ben Cheng40094c12010-02-24 20:58:44 -08001202 case kJitTSelectRequestHot:
buzbee9f601a92011-02-11 17:48:20 -08001203 self->jitState = kJitTSelect;
1204 self->currTraceHead = self->interpSave.pc;
1205 self->currTraceRun = 0;
1206 self->totalTraceLen = 0;
1207 self->currRunHead = self->interpSave.pc;
1208 self->currRunLen = 0;
1209 self->trace[0].frag.startOffset =
1210 self->interpSave.pc - self->interpSave.method->insns;
1211 self->trace[0].frag.numInsts = 0;
1212 self->trace[0].frag.runEnd = false;
1213 self->trace[0].frag.hint = kJitHintNone;
1214 self->trace[0].frag.isCode = true;
1215 self->lastPC = 0;
Ben Chenga4973592010-03-31 11:59:18 -07001216 break;
1217 /*
1218 * For JIT's perspective there is no need to stay in the debug
1219 * interpreter unless debugger/profiler is attached.
1220 */
1221 case kJitDone:
1222 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001223 break;
1224 default:
Ben Chenga4973592010-03-31 11:59:18 -07001225 LOGE("Unexpected JIT state: %d entry point: %d",
buzbee9f601a92011-02-11 17:48:20 -08001226 self->jitState, self->entryPoint);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001227 dvmAbort();
1228 }
Ben Chenga4973592010-03-31 11:59:18 -07001229 } else {
1230 /*
1231 * Cannot build trace this time - ready to leave the dbg interpreter
1232 */
buzbee9f601a92011-02-11 17:48:20 -08001233 self->jitState = kJitDone;
Ben Chenga4973592010-03-31 11:59:18 -07001234 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001235 }
Ben Chenga4973592010-03-31 11:59:18 -07001236
1237 /*
1238 * Final check to see if we can really switch the interpreter. Make sure
1239 * the jitState is kJitDone when switchInterp is set to true.
1240 */
buzbee9f601a92011-02-11 17:48:20 -08001241 assert(switchInterp == false || self->jitState == kJitDone);
Ben Cheng1a7b9d72010-09-20 22:20:31 -07001242 return switchInterp && !debugOrProfile &&
1243 !dvmJitStayInPortableInterpreter();
Ben Chengba4fc8b2009-06-01 13:00:29 -07001244}
1245
Bill Buzbee27176222009-06-09 09:20:16 -07001246/*
1247 * Resizes the JitTable. Must be a power of 2, and returns true on failure.
Bill Buzbee964a7b02010-01-28 12:54:19 -08001248 * Stops all threads, and thus is a heavyweight operation. May only be called
1249 * by the compiler thread.
Bill Buzbee27176222009-06-09 09:20:16 -07001250 */
1251bool dvmJitResizeJitTable( unsigned int size )
1252{
Bill Buzbee716f1202009-07-23 13:22:09 -07001253 JitEntry *pNewTable;
1254 JitEntry *pOldTable;
Bill Buzbee964a7b02010-01-28 12:54:19 -08001255 JitEntry tempEntry;
Bill Buzbee27176222009-06-09 09:20:16 -07001256 u4 newMask;
Bill Buzbee716f1202009-07-23 13:22:09 -07001257 unsigned int oldSize;
Bill Buzbee27176222009-06-09 09:20:16 -07001258 unsigned int i;
1259
Ben Cheng3f02aa42009-08-14 13:52:09 -07001260 assert(gDvmJit.pJitEntryTable != NULL);
Bill Buzbee27176222009-06-09 09:20:16 -07001261 assert(size && !(size & (size - 1))); /* Is power of 2? */
1262
Ben Chenga4973592010-03-31 11:59:18 -07001263 LOGI("Jit: resizing JitTable from %d to %d", gDvmJit.jitTableSize, size);
Bill Buzbee27176222009-06-09 09:20:16 -07001264
1265 newMask = size - 1;
1266
1267 if (size <= gDvmJit.jitTableSize) {
1268 return true;
1269 }
1270
Bill Buzbee964a7b02010-01-28 12:54:19 -08001271 /* Make sure requested size is compatible with chain field width */
1272 tempEntry.u.info.chain = size;
1273 if (tempEntry.u.info.chain != size) {
1274 LOGD("Jit: JitTable request of %d too big", size);
1275 return true;
1276 }
1277
Bill Buzbee716f1202009-07-23 13:22:09 -07001278 pNewTable = (JitEntry*)calloc(size, sizeof(*pNewTable));
Bill Buzbee27176222009-06-09 09:20:16 -07001279 if (pNewTable == NULL) {
1280 return true;
1281 }
1282 for (i=0; i< size; i++) {
Bill Buzbee716f1202009-07-23 13:22:09 -07001283 pNewTable[i].u.info.chain = size; /* Initialize chain termination */
Bill Buzbee27176222009-06-09 09:20:16 -07001284 }
1285
1286 /* Stop all other interpreting/jit'ng threads */
Ben Chenga8e64a72009-10-20 13:01:36 -07001287 dvmSuspendAllThreads(SUSPEND_FOR_TBL_RESIZE);
Bill Buzbee27176222009-06-09 09:20:16 -07001288
Bill Buzbee716f1202009-07-23 13:22:09 -07001289 pOldTable = gDvmJit.pJitEntryTable;
1290 oldSize = gDvmJit.jitTableSize;
Bill Buzbee27176222009-06-09 09:20:16 -07001291
1292 dvmLockMutex(&gDvmJit.tableLock);
Bill Buzbee27176222009-06-09 09:20:16 -07001293 gDvmJit.pJitEntryTable = pNewTable;
1294 gDvmJit.jitTableSize = size;
1295 gDvmJit.jitTableMask = size - 1;
Bill Buzbee716f1202009-07-23 13:22:09 -07001296 gDvmJit.jitTableEntriesUsed = 0;
Bill Buzbee27176222009-06-09 09:20:16 -07001297
Bill Buzbee716f1202009-07-23 13:22:09 -07001298 for (i=0; i < oldSize; i++) {
1299 if (pOldTable[i].dPC) {
1300 JitEntry *p;
1301 u2 chain;
Ben Chengcfdeca32011-01-14 11:36:46 -08001302 p = lookupAndAdd(pOldTable[i].dPC, true /* holds tableLock*/,
1303 pOldTable[i].u.info.isMethodEntry);
Bill Buzbee964a7b02010-01-28 12:54:19 -08001304 p->codeAddress = pOldTable[i].codeAddress;
Bill Buzbee716f1202009-07-23 13:22:09 -07001305 /* We need to preserve the new chain field, but copy the rest */
Bill Buzbee716f1202009-07-23 13:22:09 -07001306 chain = p->u.info.chain;
1307 p->u = pOldTable[i].u;
1308 p->u.info.chain = chain;
Bill Buzbee716f1202009-07-23 13:22:09 -07001309 }
1310 }
buzbee2e152ba2010-12-15 16:32:35 -08001311
Bill Buzbee964a7b02010-01-28 12:54:19 -08001312 dvmUnlockMutex(&gDvmJit.tableLock);
Bill Buzbee716f1202009-07-23 13:22:09 -07001313
1314 free(pOldTable);
1315
Bill Buzbee27176222009-06-09 09:20:16 -07001316 /* Restart the world */
Ben Chenga8e64a72009-10-20 13:01:36 -07001317 dvmResumeAllThreads(SUSPEND_FOR_TBL_RESIZE);
Bill Buzbee27176222009-06-09 09:20:16 -07001318
1319 return false;
1320}
1321
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001322/*
Ben Cheng60c24f42010-01-04 12:29:56 -08001323 * Reset the JitTable to the initial clean state.
1324 */
1325void dvmJitResetTable(void)
1326{
1327 JitEntry *jitEntry = gDvmJit.pJitEntryTable;
1328 unsigned int size = gDvmJit.jitTableSize;
1329 unsigned int i;
1330
1331 dvmLockMutex(&gDvmJit.tableLock);
buzbee2e152ba2010-12-15 16:32:35 -08001332
1333 /* Note: If need to preserve any existing counts. Do so here. */
buzbee38c41342011-01-11 15:45:49 -08001334 if (gDvmJit.pJitTraceProfCounters) {
1335 for (i=0; i < JIT_PROF_BLOCK_BUCKETS; i++) {
1336 if (gDvmJit.pJitTraceProfCounters->buckets[i])
1337 memset((void *) gDvmJit.pJitTraceProfCounters->buckets[i],
1338 0, sizeof(JitTraceCounter_t) * JIT_PROF_BLOCK_ENTRIES);
1339 }
1340 gDvmJit.pJitTraceProfCounters->next = 0;
buzbee2e152ba2010-12-15 16:32:35 -08001341 }
buzbee2e152ba2010-12-15 16:32:35 -08001342
Ben Cheng60c24f42010-01-04 12:29:56 -08001343 memset((void *) jitEntry, 0, sizeof(JitEntry) * size);
1344 for (i=0; i< size; i++) {
1345 jitEntry[i].u.info.chain = size; /* Initialize chain termination */
1346 }
1347 gDvmJit.jitTableEntriesUsed = 0;
1348 dvmUnlockMutex(&gDvmJit.tableLock);
1349}
1350
1351/*
buzbee2e152ba2010-12-15 16:32:35 -08001352 * Return the address of the next trace profile counter. This address
1353 * will be embedded in the generated code for the trace, and thus cannot
1354 * change while the trace exists.
1355 */
1356JitTraceCounter_t *dvmJitNextTraceCounter()
1357{
1358 int idx = gDvmJit.pJitTraceProfCounters->next / JIT_PROF_BLOCK_ENTRIES;
1359 int elem = gDvmJit.pJitTraceProfCounters->next % JIT_PROF_BLOCK_ENTRIES;
1360 JitTraceCounter_t *res;
1361 /* Lazily allocate blocks of counters */
1362 if (!gDvmJit.pJitTraceProfCounters->buckets[idx]) {
1363 JitTraceCounter_t *p =
1364 (JitTraceCounter_t*) calloc(JIT_PROF_BLOCK_ENTRIES, sizeof(*p));
1365 if (!p) {
1366 LOGE("Failed to allocate block of trace profile counters");
1367 dvmAbort();
1368 }
1369 gDvmJit.pJitTraceProfCounters->buckets[idx] = p;
1370 }
1371 res = &gDvmJit.pJitTraceProfCounters->buckets[idx][elem];
1372 gDvmJit.pJitTraceProfCounters->next++;
1373 return res;
1374}
1375
1376/*
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001377 * Float/double conversion requires clamping to min and max of integer form. If
1378 * target doesn't support this normally, use these.
1379 */
1380s8 dvmJitd2l(double d)
1381{
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001382 static const double kMaxLong = (double)(s8)0x7fffffffffffffffULL;
1383 static const double kMinLong = (double)(s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001384 if (d >= kMaxLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001385 return (s8)0x7fffffffffffffffULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001386 else if (d <= kMinLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001387 return (s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001388 else if (d != d) // NaN case
1389 return 0;
1390 else
1391 return (s8)d;
1392}
1393
1394s8 dvmJitf2l(float f)
1395{
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001396 static const float kMaxLong = (float)(s8)0x7fffffffffffffffULL;
1397 static const float kMinLong = (float)(s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001398 if (f >= kMaxLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001399 return (s8)0x7fffffffffffffffULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001400 else if (f <= kMinLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001401 return (s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001402 else if (f != f) // NaN case
1403 return 0;
1404 else
1405 return (s8)f;
1406}
1407
buzbee2e152ba2010-12-15 16:32:35 -08001408/* Should only be called by the compiler thread */
1409void dvmJitChangeProfileMode(TraceProfilingModes newState)
1410{
1411 if (gDvmJit.profileMode != newState) {
1412 gDvmJit.profileMode = newState;
1413 dvmJitUnchainAll();
1414 }
1415}
1416
1417void dvmJitTraceProfilingOn()
1418{
1419 if (gDvmJit.profileMode == kTraceProfilingPeriodicOff)
Bill Buzbee1b3da592011-02-03 07:38:22 -08001420 dvmCompilerForceWorkEnqueue(NULL, kWorkOrderProfileMode,
1421 (void*) kTraceProfilingPeriodicOn);
buzbee2e152ba2010-12-15 16:32:35 -08001422 else if (gDvmJit.profileMode == kTraceProfilingDisabled)
Bill Buzbee1b3da592011-02-03 07:38:22 -08001423 dvmCompilerForceWorkEnqueue(NULL, kWorkOrderProfileMode,
1424 (void*) kTraceProfilingContinuous);
buzbee2e152ba2010-12-15 16:32:35 -08001425}
1426
1427void dvmJitTraceProfilingOff()
1428{
1429 if (gDvmJit.profileMode == kTraceProfilingPeriodicOn)
Bill Buzbee1b3da592011-02-03 07:38:22 -08001430 dvmCompilerForceWorkEnqueue(NULL, kWorkOrderProfileMode,
1431 (void*) kTraceProfilingPeriodicOff);
buzbee2e152ba2010-12-15 16:32:35 -08001432 else if (gDvmJit.profileMode == kTraceProfilingContinuous)
Bill Buzbee1b3da592011-02-03 07:38:22 -08001433 dvmCompilerForceWorkEnqueue(NULL, kWorkOrderProfileMode,
1434 (void*) kTraceProfilingDisabled);
buzbee2e152ba2010-12-15 16:32:35 -08001435}
1436
Ben Chengba4fc8b2009-06-01 13:00:29 -07001437#endif /* WITH_JIT */