blob: 6f76a8607b6836b00860a0fa3b740eb9f8f76b12 [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
26#include "dexdump/OpCodeNames.h"
27#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/*
59 * Save out PC, FP, InterpState, and registers to shadow space.
60 * Return a pointer to the shadow space for JIT to use.
61 */
62void* dvmSelfVerificationSaveState(const u2* pc, const void* fp,
Bill Buzbee9a8c75a2009-11-08 14:31:20 -080063 InterpState* interpState, int targetTrace)
Jeff Hao97319a82009-08-12 16:57:15 -070064{
65 Thread *self = dvmThreadSelf();
66 ShadowSpace *shadowSpace = self->shadowSpace;
Ben Cheng11d8f142010-03-24 15:24:19 -070067 unsigned preBytes = interpState->method->outsSize*4 + sizeof(StackSaveArea);
68 unsigned postBytes = interpState->method->registersSize*4;
Jeff Hao97319a82009-08-12 16:57:15 -070069
70 //LOGD("### selfVerificationSaveState(%d) pc: 0x%x fp: 0x%x",
71 // self->threadId, (int)pc, (int)fp);
72
73 if (shadowSpace->selfVerificationState != kSVSIdle) {
74 LOGD("~~~ Save: INCORRECT PREVIOUS STATE(%d): %d",
75 self->threadId, shadowSpace->selfVerificationState);
76 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -070077 LOGD("PC: 0x%x FP: 0x%x", (int)pc, (int)fp);
Jeff Hao97319a82009-08-12 16:57:15 -070078 }
79 shadowSpace->selfVerificationState = kSVSStart;
80
Ben Chengd5adae12010-03-26 17:45:28 -070081 if (interpState->entryPoint == kInterpEntryResume) {
82 interpState->entryPoint = kInterpEntryInstr;
83#if 0
84 /* Tracking the success rate of resume after single-stepping */
85 if (interpState->jitResumeDPC == pc) {
86 LOGD("SV single step resumed at %p", pc);
87 }
88 else {
89 LOGD("real %p DPC %p NPC %p", pc, interpState->jitResumeDPC,
90 interpState->jitResumeNPC);
91 }
92#endif
93 }
94
Jeff Hao97319a82009-08-12 16:57:15 -070095 // Dynamically grow shadow register space if necessary
Ben Cheng11d8f142010-03-24 15:24:19 -070096 if (preBytes + postBytes > shadowSpace->registerSpaceSize * sizeof(u4)) {
Jeff Hao97319a82009-08-12 16:57:15 -070097 free(shadowSpace->registerSpace);
Ben Cheng11d8f142010-03-24 15:24:19 -070098 shadowSpace->registerSpaceSize = (preBytes + postBytes) / sizeof(u4);
Jeff Hao97319a82009-08-12 16:57:15 -070099 shadowSpace->registerSpace =
Ben Cheng11d8f142010-03-24 15:24:19 -0700100 (int*) calloc(shadowSpace->registerSpaceSize, sizeof(u4));
Jeff Hao97319a82009-08-12 16:57:15 -0700101 }
102
103 // Remember original state
104 shadowSpace->startPC = pc;
105 shadowSpace->fp = fp;
Ben Chengccd6c012009-10-15 14:52:45 -0700106 shadowSpace->glue = interpState;
107 /*
108 * Store the original method here in case the trace ends with a
109 * return/invoke, the last method.
110 */
111 shadowSpace->method = interpState->method;
Jeff Hao97319a82009-08-12 16:57:15 -0700112 shadowSpace->shadowFP = shadowSpace->registerSpace +
113 shadowSpace->registerSpaceSize - postBytes/4;
114
115 // Create a copy of the InterpState
Ben Chengccd6c012009-10-15 14:52:45 -0700116 memcpy(&(shadowSpace->interpState), interpState, sizeof(InterpState));
Jeff Hao97319a82009-08-12 16:57:15 -0700117 shadowSpace->interpState.fp = shadowSpace->shadowFP;
118 shadowSpace->interpState.interpStackEnd = (u1*)shadowSpace->registerSpace;
119
120 // Create a copy of the stack
121 memcpy(((char*)shadowSpace->shadowFP)-preBytes, ((char*)fp)-preBytes,
122 preBytes+postBytes);
123
124 // Setup the shadowed heap space
125 shadowSpace->heapSpaceTail = shadowSpace->heapSpace;
126
127 // Reset trace length
128 shadowSpace->traceLength = 0;
129
130 return shadowSpace;
131}
132
133/*
134 * Save ending PC, FP and compiled code exit point to shadow space.
135 * Return a pointer to the shadow space for JIT to restore state.
136 */
137void* dvmSelfVerificationRestoreState(const u2* pc, const void* fp,
138 SelfVerificationState exitPoint)
139{
140 Thread *self = dvmThreadSelf();
141 ShadowSpace *shadowSpace = self->shadowSpace;
Ben Chengd5adae12010-03-26 17:45:28 -0700142 // Official InterpState structure
143 InterpState *realGlue = shadowSpace->glue;
Jeff Hao97319a82009-08-12 16:57:15 -0700144 shadowSpace->endPC = pc;
145 shadowSpace->endShadowFP = fp;
146
147 //LOGD("### selfVerificationRestoreState(%d) pc: 0x%x fp: 0x%x endPC: 0x%x",
148 // self->threadId, (int)shadowSpace->startPC, (int)shadowSpace->fp,
149 // (int)pc);
150
151 if (shadowSpace->selfVerificationState != kSVSStart) {
152 LOGD("~~~ Restore: INCORRECT PREVIOUS STATE(%d): %d",
153 self->threadId, shadowSpace->selfVerificationState);
154 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -0700155 LOGD("Dalvik PC: 0x%x endPC: 0x%x", (int)shadowSpace->startPC,
Jeff Hao97319a82009-08-12 16:57:15 -0700156 (int)shadowSpace->endPC);
Ben Chengccd6c012009-10-15 14:52:45 -0700157 LOGD("Interp FP: 0x%x", (int)shadowSpace->fp);
158 LOGD("Shadow FP: 0x%x endFP: 0x%x", (int)shadowSpace->shadowFP,
Jeff Hao97319a82009-08-12 16:57:15 -0700159 (int)shadowSpace->endShadowFP);
160 }
161
Ben Chengd5adae12010-03-26 17:45:28 -0700162 // Move the resume [ND]PC from the shadow space to the real space so that
163 // the debug interpreter can return to the translation
164 if (exitPoint == kSVSSingleStep) {
165 realGlue->jitResumeNPC = shadowSpace->interpState.jitResumeNPC;
166 realGlue->jitResumeDPC = shadowSpace->interpState.jitResumeDPC;
167 } else {
168 realGlue->jitResumeNPC = NULL;
169 realGlue->jitResumeDPC = NULL;
170 }
171
Jeff Hao97319a82009-08-12 16:57:15 -0700172 // Special case when punting after a single instruction
Ben Chengd5adae12010-03-26 17:45:28 -0700173 if (exitPoint == kSVSPunt && pc == shadowSpace->startPC) {
Jeff Hao97319a82009-08-12 16:57:15 -0700174 shadowSpace->selfVerificationState = kSVSIdle;
175 } else {
176 shadowSpace->selfVerificationState = exitPoint;
177 }
178
179 return shadowSpace;
180}
181
182/* Print contents of virtual registers */
Ben Chengccd6c012009-10-15 14:52:45 -0700183static void selfVerificationPrintRegisters(int* addr, int* addrRef,
184 int numWords)
Jeff Hao97319a82009-08-12 16:57:15 -0700185{
186 int i;
187 for (i = 0; i < numWords; i++) {
Ben Chengccd6c012009-10-15 14:52:45 -0700188 LOGD("(v%d) 0x%8x%s", i, addr[i], addr[i] != addrRef[i] ? " X" : "");
Jeff Hao97319a82009-08-12 16:57:15 -0700189 }
190}
191
192/* Print values maintained in shadowSpace */
193static void selfVerificationDumpState(const u2* pc, Thread* self)
194{
195 ShadowSpace* shadowSpace = self->shadowSpace;
196 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
197 int frameBytes = (int) shadowSpace->registerSpace +
198 shadowSpace->registerSpaceSize*4 -
199 (int) shadowSpace->shadowFP;
200 int localRegs = 0;
201 int frameBytes2 = 0;
202 if (self->curFrame < shadowSpace->fp) {
203 localRegs = (stackSave->method->registersSize -
204 stackSave->method->insSize)*4;
205 frameBytes2 = (int) shadowSpace->fp - (int) self->curFrame - localRegs;
206 }
207 LOGD("********** SHADOW STATE DUMP **********");
Ben Chengccd6c012009-10-15 14:52:45 -0700208 LOGD("CurrentPC: 0x%x, Offset: 0x%04x", (int)pc,
Jeff Hao97319a82009-08-12 16:57:15 -0700209 (int)(pc - stackSave->method->insns));
Ben Chengccd6c012009-10-15 14:52:45 -0700210 LOGD("Class: %s", shadowSpace->method->clazz->descriptor);
211 LOGD("Method: %s", shadowSpace->method->name);
212 LOGD("Dalvik PC: 0x%x endPC: 0x%x", (int)shadowSpace->startPC,
Jeff Hao97319a82009-08-12 16:57:15 -0700213 (int)shadowSpace->endPC);
Ben Chengccd6c012009-10-15 14:52:45 -0700214 LOGD("Interp FP: 0x%x endFP: 0x%x", (int)shadowSpace->fp,
Jeff Hao97319a82009-08-12 16:57:15 -0700215 (int)self->curFrame);
Ben Chengccd6c012009-10-15 14:52:45 -0700216 LOGD("Shadow FP: 0x%x endFP: 0x%x", (int)shadowSpace->shadowFP,
Jeff Hao97319a82009-08-12 16:57:15 -0700217 (int)shadowSpace->endShadowFP);
Ben Chengccd6c012009-10-15 14:52:45 -0700218 LOGD("Frame1 Bytes: %d Frame2 Local: %d Bytes: %d", frameBytes,
Jeff Hao97319a82009-08-12 16:57:15 -0700219 localRegs, frameBytes2);
Ben Chengccd6c012009-10-15 14:52:45 -0700220 LOGD("Trace length: %d State: %d", shadowSpace->traceLength,
Jeff Hao97319a82009-08-12 16:57:15 -0700221 shadowSpace->selfVerificationState);
222}
223
224/* Print decoded instructions in the current trace */
225static void selfVerificationDumpTrace(const u2* pc, Thread* self)
226{
227 ShadowSpace* shadowSpace = self->shadowSpace;
228 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700229 int i, addr, offset;
230 DecodedInstruction *decInsn;
Jeff Hao97319a82009-08-12 16:57:15 -0700231
232 LOGD("********** SHADOW TRACE DUMP **********");
233 for (i = 0; i < shadowSpace->traceLength; i++) {
Ben Chengbcdc1de2009-08-21 16:18:46 -0700234 addr = shadowSpace->trace[i].addr;
235 offset = (int)((u2*)addr - stackSave->method->insns);
236 decInsn = &(shadowSpace->trace[i].decInsn);
237 /* Not properly decoding instruction, some registers may be garbage */
Ben Chengccd6c012009-10-15 14:52:45 -0700238 LOGD("0x%x: (0x%04x) %s", addr, offset, getOpcodeName(decInsn->opCode));
Jeff Hao97319a82009-08-12 16:57:15 -0700239 }
240}
241
Ben Chengbcdc1de2009-08-21 16:18:46 -0700242/* Code is forced into this spin loop when a divergence is detected */
Ben Chengccd6c012009-10-15 14:52:45 -0700243static void selfVerificationSpinLoop(ShadowSpace *shadowSpace)
Ben Chengbcdc1de2009-08-21 16:18:46 -0700244{
Ben Chengccd6c012009-10-15 14:52:45 -0700245 const u2 *startPC = shadowSpace->startPC;
Ben Cheng88a0f972010-02-24 15:00:40 -0800246 JitTraceDescription* desc = dvmCopyTraceDescriptor(startPC, NULL);
Ben Chengccd6c012009-10-15 14:52:45 -0700247 if (desc) {
248 dvmCompilerWorkEnqueue(startPC, kWorkOrderTraceDebug, desc);
Ben Cheng1357e942010-02-10 17:21:39 -0800249 /*
250 * This function effectively terminates the VM right here, so not
251 * freeing the desc pointer when the enqueuing fails is acceptable.
252 */
Ben Chengccd6c012009-10-15 14:52:45 -0700253 }
Ben Chengbcdc1de2009-08-21 16:18:46 -0700254 gDvmJit.selfVerificationSpin = true;
255 while(gDvmJit.selfVerificationSpin) sleep(10);
256}
257
Jeff Hao97319a82009-08-12 16:57:15 -0700258/* Manage self verification while in the debug interpreter */
Ben Chengd5adae12010-03-26 17:45:28 -0700259static bool selfVerificationDebugInterp(const u2* pc, Thread* self,
260 InterpState *interpState)
Jeff Hao97319a82009-08-12 16:57:15 -0700261{
262 ShadowSpace *shadowSpace = self->shadowSpace;
Jeff Hao97319a82009-08-12 16:57:15 -0700263 SelfVerificationState state = shadowSpace->selfVerificationState;
Ben Chengbcdc1de2009-08-21 16:18:46 -0700264
265 DecodedInstruction decInsn;
266 dexDecodeInstruction(gDvm.instrFormat, pc, &decInsn);
267
Jeff Hao97319a82009-08-12 16:57:15 -0700268 //LOGD("### DbgIntp(%d): PC: 0x%x endPC: 0x%x state: %d len: %d %s",
269 // self->threadId, (int)pc, (int)shadowSpace->endPC, state,
Ben Chengbcdc1de2009-08-21 16:18:46 -0700270 // shadowSpace->traceLength, getOpcodeName(decInsn.opCode));
Jeff Hao97319a82009-08-12 16:57:15 -0700271
272 if (state == kSVSIdle || state == kSVSStart) {
273 LOGD("~~~ DbgIntrp: INCORRECT PREVIOUS STATE(%d): %d",
274 self->threadId, state);
275 selfVerificationDumpState(pc, self);
276 selfVerificationDumpTrace(pc, self);
277 }
278
Ben Chengd5adae12010-03-26 17:45:28 -0700279 /*
280 * Skip endPC once when trace has a backward branch. If the SV state is
281 * single step, keep it that way.
282 */
Jeff Hao97319a82009-08-12 16:57:15 -0700283 if ((state == kSVSBackwardBranch && pc == shadowSpace->endPC) ||
Ben Chengd5adae12010-03-26 17:45:28 -0700284 (state != kSVSBackwardBranch && state != kSVSSingleStep)) {
Jeff Hao97319a82009-08-12 16:57:15 -0700285 shadowSpace->selfVerificationState = kSVSDebugInterp;
286 }
287
288 /* Check that the current pc is the end of the trace */
Ben Chengd5adae12010-03-26 17:45:28 -0700289 if ((state == kSVSDebugInterp || state == kSVSSingleStep) &&
290 pc == shadowSpace->endPC) {
Jeff Hao97319a82009-08-12 16:57:15 -0700291
292 shadowSpace->selfVerificationState = kSVSIdle;
293
294 /* Check register space */
295 int frameBytes = (int) shadowSpace->registerSpace +
296 shadowSpace->registerSpaceSize*4 -
297 (int) shadowSpace->shadowFP;
298 if (memcmp(shadowSpace->fp, shadowSpace->shadowFP, frameBytes)) {
Ben Chengccd6c012009-10-15 14:52:45 -0700299 LOGD("~~~ DbgIntp(%d): REGISTERS DIVERGENCE!", self->threadId);
Jeff Hao97319a82009-08-12 16:57:15 -0700300 selfVerificationDumpState(pc, self);
301 selfVerificationDumpTrace(pc, self);
302 LOGD("*** Interp Registers: addr: 0x%x bytes: %d",
303 (int)shadowSpace->fp, frameBytes);
Ben Chengccd6c012009-10-15 14:52:45 -0700304 selfVerificationPrintRegisters((int*)shadowSpace->fp,
305 (int*)shadowSpace->shadowFP,
306 frameBytes/4);
Jeff Hao97319a82009-08-12 16:57:15 -0700307 LOGD("*** Shadow Registers: addr: 0x%x bytes: %d",
308 (int)shadowSpace->shadowFP, frameBytes);
309 selfVerificationPrintRegisters((int*)shadowSpace->shadowFP,
Ben Chengccd6c012009-10-15 14:52:45 -0700310 (int*)shadowSpace->fp,
311 frameBytes/4);
312 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700313 }
314 /* Check new frame if it exists (invokes only) */
315 if (self->curFrame < shadowSpace->fp) {
316 StackSaveArea* stackSave = SAVEAREA_FROM_FP(self->curFrame);
317 int localRegs = (stackSave->method->registersSize -
318 stackSave->method->insSize)*4;
319 int frameBytes2 = (int) shadowSpace->fp -
320 (int) self->curFrame - localRegs;
321 if (memcmp(((char*)self->curFrame)+localRegs,
322 ((char*)shadowSpace->endShadowFP)+localRegs, frameBytes2)) {
Ben Chengccd6c012009-10-15 14:52:45 -0700323 LOGD("~~~ DbgIntp(%d): REGISTERS (FRAME2) DIVERGENCE!",
Jeff Hao97319a82009-08-12 16:57:15 -0700324 self->threadId);
325 selfVerificationDumpState(pc, self);
326 selfVerificationDumpTrace(pc, self);
327 LOGD("*** Interp Registers: addr: 0x%x l: %d bytes: %d",
328 (int)self->curFrame, localRegs, frameBytes2);
329 selfVerificationPrintRegisters((int*)self->curFrame,
Ben Chengccd6c012009-10-15 14:52:45 -0700330 (int*)shadowSpace->endShadowFP,
331 (frameBytes2+localRegs)/4);
Jeff Hao97319a82009-08-12 16:57:15 -0700332 LOGD("*** Shadow Registers: addr: 0x%x l: %d bytes: %d",
333 (int)shadowSpace->endShadowFP, localRegs, frameBytes2);
334 selfVerificationPrintRegisters((int*)shadowSpace->endShadowFP,
Ben Chengccd6c012009-10-15 14:52:45 -0700335 (int*)self->curFrame,
336 (frameBytes2+localRegs)/4);
337 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700338 }
339 }
340
341 /* Check memory space */
Ben Chengbcdc1de2009-08-21 16:18:46 -0700342 bool memDiff = false;
Jeff Hao97319a82009-08-12 16:57:15 -0700343 ShadowHeap* heapSpacePtr;
344 for (heapSpacePtr = shadowSpace->heapSpace;
345 heapSpacePtr != shadowSpace->heapSpaceTail; heapSpacePtr++) {
Ben Chengbcdc1de2009-08-21 16:18:46 -0700346 int memData = *((unsigned int*) heapSpacePtr->addr);
347 if (heapSpacePtr->data != memData) {
Ben Chengccd6c012009-10-15 14:52:45 -0700348 LOGD("~~~ DbgIntp(%d): MEMORY DIVERGENCE!", self->threadId);
349 LOGD("Addr: 0x%x Intrp Data: 0x%x Jit Data: 0x%x",
Ben Chengbcdc1de2009-08-21 16:18:46 -0700350 heapSpacePtr->addr, memData, heapSpacePtr->data);
Jeff Hao97319a82009-08-12 16:57:15 -0700351 selfVerificationDumpState(pc, self);
352 selfVerificationDumpTrace(pc, self);
Ben Chengbcdc1de2009-08-21 16:18:46 -0700353 memDiff = true;
Jeff Hao97319a82009-08-12 16:57:15 -0700354 }
355 }
Ben Chengccd6c012009-10-15 14:52:45 -0700356 if (memDiff) selfVerificationSpinLoop(shadowSpace);
Ben Chengd5adae12010-03-26 17:45:28 -0700357
358 /*
359 * Switch to JIT single step mode to stay in the debug interpreter for
360 * one more instruction
361 */
362 if (state == kSVSSingleStep) {
363 interpState->jitState = kJitSingleStepEnd;
364 }
Jeff Hao97319a82009-08-12 16:57:15 -0700365 return true;
366
367 /* If end not been reached, make sure max length not exceeded */
368 } else if (shadowSpace->traceLength >= JIT_MAX_TRACE_LEN) {
369 LOGD("~~~ DbgIntp(%d): CONTROL DIVERGENCE!", self->threadId);
Ben Chengccd6c012009-10-15 14:52:45 -0700370 LOGD("startPC: 0x%x endPC: 0x%x currPC: 0x%x",
Jeff Hao97319a82009-08-12 16:57:15 -0700371 (int)shadowSpace->startPC, (int)shadowSpace->endPC, (int)pc);
372 selfVerificationDumpState(pc, self);
373 selfVerificationDumpTrace(pc, self);
Ben Chengccd6c012009-10-15 14:52:45 -0700374 selfVerificationSpinLoop(shadowSpace);
Jeff Hao97319a82009-08-12 16:57:15 -0700375
376 return true;
377 }
Ben Chengbcdc1de2009-08-21 16:18:46 -0700378 /* Log the instruction address and decoded instruction for debug */
Jeff Hao97319a82009-08-12 16:57:15 -0700379 shadowSpace->trace[shadowSpace->traceLength].addr = (int)pc;
Ben Chengbcdc1de2009-08-21 16:18:46 -0700380 shadowSpace->trace[shadowSpace->traceLength].decInsn = decInsn;
Jeff Hao97319a82009-08-12 16:57:15 -0700381 shadowSpace->traceLength++;
382
383 return false;
384}
385#endif
386
Ben Chengba4fc8b2009-06-01 13:00:29 -0700387/*
388 * If one of our fixed tables or the translation buffer fills up,
389 * call this routine to avoid wasting cycles on future translation requests.
390 */
391void dvmJitStopTranslationRequests()
392{
393 /*
394 * Note 1: This won't necessarily stop all translation requests, and
395 * operates on a delayed mechanism. Running threads look to the copy
396 * of this value in their private InterpState structures and won't see
397 * this change until it is refreshed (which happens on interpreter
398 * entry).
399 * Note 2: This is a one-shot memory leak on this table. Because this is a
400 * permanent off switch for Jit profiling, it is a one-time leak of 1K
401 * bytes, and no further attempt will be made to re-allocate it. Can't
402 * free it because some thread may be holding a reference.
403 */
Bill Buzbeeb1d80442009-12-17 14:55:21 -0800404 gDvmJit.pProfTable = NULL;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700405}
406
Ben Cheng978738d2010-05-13 13:45:57 -0700407#if defined(WITH_JIT_TUNING)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700408/* Convenience function to increment counter from assembly code */
Ben Cheng6c10a972009-10-29 14:39:18 -0700409void dvmBumpNoChain(int from)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700410{
Ben Cheng6c10a972009-10-29 14:39:18 -0700411 gDvmJit.noChainExit[from]++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700412}
413
414/* Convenience function to increment counter from assembly code */
415void dvmBumpNormal()
416{
Ben Cheng6c10a972009-10-29 14:39:18 -0700417 gDvmJit.normalExit++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700418}
419
420/* Convenience function to increment counter from assembly code */
421void dvmBumpPunt(int from)
422{
Ben Cheng6c10a972009-10-29 14:39:18 -0700423 gDvmJit.puntExit++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700424}
425#endif
426
427/* Dumps debugging & tuning stats to the log */
428void dvmJitStats()
429{
430 int i;
431 int hit;
432 int not_hit;
433 int chains;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800434 int stubs;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700435 if (gDvmJit.pJitEntryTable) {
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800436 for (i=0, stubs=chains=hit=not_hit=0;
Bill Buzbee27176222009-06-09 09:20:16 -0700437 i < (int) gDvmJit.jitTableSize;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700438 i++) {
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800439 if (gDvmJit.pJitEntryTable[i].dPC != 0) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700440 hit++;
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800441 if (gDvmJit.pJitEntryTable[i].codeAddress ==
Bill Buzbeebd047242010-05-13 13:02:53 -0700442 dvmCompilerGetInterpretTemplate())
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800443 stubs++;
444 } else
Ben Chengba4fc8b2009-06-01 13:00:29 -0700445 not_hit++;
Bill Buzbee716f1202009-07-23 13:22:09 -0700446 if (gDvmJit.pJitEntryTable[i].u.info.chain != gDvmJit.jitTableSize)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700447 chains++;
448 }
Ben Cheng72621c92010-03-10 13:12:55 -0800449 LOGD("JIT: table size is %d, entries used is %d",
Ben Cheng86717f72010-03-05 15:27:21 -0800450 gDvmJit.jitTableSize, gDvmJit.jitTableEntriesUsed);
Ben Cheng72621c92010-03-10 13:12:55 -0800451 LOGD("JIT: %d traces, %d slots, %d chains, %d thresh, %s",
452 hit, not_hit + hit, chains, gDvmJit.threshold,
453 gDvmJit.blockingMode ? "Blocking" : "Non-blocking");
Ben Cheng86717f72010-03-05 15:27:21 -0800454
Ben Cheng978738d2010-05-13 13:45:57 -0700455#if defined(WITH_JIT_TUNING)
456 LOGD("JIT: Code cache patches: %d", gDvmJit.codeCachePatches);
457
Ben Cheng72621c92010-03-10 13:12:55 -0800458 LOGD("JIT: Lookups: %d hits, %d misses; %d normal, %d punt",
459 gDvmJit.addrLookupsFound, gDvmJit.addrLookupsNotFound,
460 gDvmJit.normalExit, gDvmJit.puntExit);
Ben Cheng452efba2010-04-30 15:14:00 -0700461
Ben Cheng978738d2010-05-13 13:45:57 -0700462 LOGD("JIT: ICHits: %d", gDvmICHitCount);
463
Ben Cheng72621c92010-03-10 13:12:55 -0800464 LOGD("JIT: noChainExit: %d IC miss, %d interp callsite, "
465 "%d switch overflow",
466 gDvmJit.noChainExit[kInlineCacheMiss],
467 gDvmJit.noChainExit[kCallsiteInterpreted],
468 gDvmJit.noChainExit[kSwitchOverflow]);
Ben Cheng86717f72010-03-05 15:27:21 -0800469
Ben Chengb88ec3c2010-05-17 12:50:33 -0700470 LOGD("JIT: ICPatch: %d init, %d rejected, %d lock-free, %d queued, "
471 "%d dropped",
472 gDvmJit.icPatchInit, gDvmJit.icPatchRejected,
473 gDvmJit.icPatchLockFree, gDvmJit.icPatchQueued,
Ben Cheng452efba2010-04-30 15:14:00 -0700474 gDvmJit.icPatchDropped);
475
Ben Cheng86717f72010-03-05 15:27:21 -0800476 LOGD("JIT: Invoke: %d mono, %d poly, %d native, %d return",
477 gDvmJit.invokeMonomorphic, gDvmJit.invokePolymorphic,
478 gDvmJit.invokeNative, gDvmJit.returnOp);
479 LOGD("JIT: Total compilation time: %llu ms", gDvmJit.jitTime / 1000);
480 LOGD("JIT: Avg unit compilation time: %llu us",
481 gDvmJit.jitTime / gDvmJit.numCompilations);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700482#endif
Ben Cheng86717f72010-03-05 15:27:21 -0800483
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800484 LOGD("JIT: %d Translation chains, %d interp stubs",
485 gDvmJit.translationChains, stubs);
Ben Chenge80cd942009-07-17 15:54:23 -0700486 if (gDvmJit.profile) {
Bill Buzbee716f1202009-07-23 13:22:09 -0700487 dvmCompilerSortAndPrintTraceProfiles();
Bill Buzbee6e963e12009-06-17 16:56:19 -0700488 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700489 }
490}
491
Bill Buzbee716f1202009-07-23 13:22:09 -0700492
Bill Buzbeed7269912009-11-10 14:31:32 -0800493void setTraceConstruction(JitEntry *slot, bool value)
494{
495
496 JitEntryInfoUnion oldValue;
497 JitEntryInfoUnion newValue;
498 do {
499 oldValue = slot->u;
500 newValue = oldValue;
501 newValue.info.traceConstruction = value;
502 } while (!ATOMIC_CMP_SWAP( &slot->u.infoWord,
503 oldValue.infoWord, newValue.infoWord));
504}
505
506void resetTracehead(InterpState* interpState, JitEntry *slot)
507{
Bill Buzbeebd047242010-05-13 13:02:53 -0700508 slot->codeAddress = dvmCompilerGetInterpretTemplate();
Bill Buzbeed7269912009-11-10 14:31:32 -0800509 setTraceConstruction(slot, false);
510}
511
512/* Clean up any pending trace builds */
513void dvmJitAbortTraceSelect(InterpState* interpState)
514{
515 if (interpState->jitState == kJitTSelect)
Ben Chenga4973592010-03-31 11:59:18 -0700516 interpState->jitState = kJitDone;
Bill Buzbeed7269912009-11-10 14:31:32 -0800517}
518
Ben Chengba4fc8b2009-06-01 13:00:29 -0700519/*
Bill Buzbee964a7b02010-01-28 12:54:19 -0800520 * Find an entry in the JitTable, creating if necessary.
521 * Returns null if table is full.
522 */
523static JitEntry *lookupAndAdd(const u2* dPC, bool callerLocked)
524{
525 u4 chainEndMarker = gDvmJit.jitTableSize;
526 u4 idx = dvmJitHash(dPC);
527
528 /* Walk the bucket chain to find an exact match for our PC */
529 while ((gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) &&
530 (gDvmJit.pJitEntryTable[idx].dPC != dPC)) {
531 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
532 }
533
534 if (gDvmJit.pJitEntryTable[idx].dPC != dPC) {
535 /*
536 * No match. Aquire jitTableLock and find the last
537 * slot in the chain. Possibly continue the chain walk in case
538 * some other thread allocated the slot we were looking
539 * at previuosly (perhaps even the dPC we're trying to enter).
540 */
541 if (!callerLocked)
542 dvmLockMutex(&gDvmJit.tableLock);
543 /*
544 * At this point, if .dPC is NULL, then the slot we're
545 * looking at is the target slot from the primary hash
546 * (the simple, and common case). Otherwise we're going
547 * to have to find a free slot and chain it.
548 */
549 MEM_BARRIER(); /* Make sure we reload [].dPC after lock */
550 if (gDvmJit.pJitEntryTable[idx].dPC != NULL) {
551 u4 prev;
552 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
553 if (gDvmJit.pJitEntryTable[idx].dPC == dPC) {
554 /* Another thread got there first for this dPC */
555 if (!callerLocked)
556 dvmUnlockMutex(&gDvmJit.tableLock);
557 return &gDvmJit.pJitEntryTable[idx];
558 }
559 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
560 }
561 /* Here, idx should be pointing to the last cell of an
562 * active chain whose last member contains a valid dPC */
563 assert(gDvmJit.pJitEntryTable[idx].dPC != NULL);
564 /* Linear walk to find a free cell and add it to the end */
565 prev = idx;
566 while (true) {
567 idx++;
568 if (idx == chainEndMarker)
569 idx = 0; /* Wraparound */
570 if ((gDvmJit.pJitEntryTable[idx].dPC == NULL) ||
571 (idx == prev))
572 break;
573 }
574 if (idx != prev) {
575 JitEntryInfoUnion oldValue;
576 JitEntryInfoUnion newValue;
577 /*
578 * Although we hold the lock so that noone else will
579 * be trying to update a chain field, the other fields
580 * packed into the word may be in use by other threads.
581 */
582 do {
583 oldValue = gDvmJit.pJitEntryTable[prev].u;
584 newValue = oldValue;
585 newValue.info.chain = idx;
586 } while (!ATOMIC_CMP_SWAP(
587 &gDvmJit.pJitEntryTable[prev].u.infoWord,
588 oldValue.infoWord, newValue.infoWord));
589 }
590 }
591 if (gDvmJit.pJitEntryTable[idx].dPC == NULL) {
592 /*
593 * Initialize codeAddress and allocate the slot. Must
594 * happen in this order (since dPC is set, the entry is live.
595 */
596 gDvmJit.pJitEntryTable[idx].dPC = dPC;
597 gDvmJit.jitTableEntriesUsed++;
598 } else {
599 /* Table is full */
600 idx = chainEndMarker;
601 }
602 if (!callerLocked)
603 dvmUnlockMutex(&gDvmJit.tableLock);
604 }
605 return (idx == chainEndMarker) ? NULL : &gDvmJit.pJitEntryTable[idx];
606}
Ben Chenga4973592010-03-31 11:59:18 -0700607
Bill Buzbee964a7b02010-01-28 12:54:19 -0800608/*
Ben Chengd44faf52010-06-02 15:33:51 -0700609 * Check if the next instruction following the invoke is a move-result and if
610 * so add it to the trace.
611 *
612 * lastPC, len, offset are all from the preceding invoke instruction
613 */
614static void insertMoveResult(const u2 *lastPC, int len, int offset,
615 InterpState *interpState)
616{
617 DecodedInstruction nextDecInsn;
618 const u2 *moveResultPC = lastPC + len;
619
620 dexDecodeInstruction(gDvm.instrFormat, moveResultPC, &nextDecInsn);
621 if ((nextDecInsn.opCode != OP_MOVE_RESULT) &&
622 (nextDecInsn.opCode != OP_MOVE_RESULT_WIDE) &&
623 (nextDecInsn.opCode != OP_MOVE_RESULT_OBJECT))
624 return;
625
626 /* We need to start a new trace run */
627 int currTraceRun = ++interpState->currTraceRun;
628 interpState->currRunHead = moveResultPC;
629 interpState->trace[currTraceRun].frag.startOffset = offset + len;
630 interpState->trace[currTraceRun].frag.numInsts = 1;
631 interpState->trace[currTraceRun].frag.runEnd = false;
632 interpState->trace[currTraceRun].frag.hint = kJitHintNone;
633 interpState->totalTraceLen++;
634
635 interpState->currRunLen = dexGetInstrOrTableWidthAbs(gDvm.instrWidth,
636 moveResultPC);
637}
638
639/*
Ben Chengba4fc8b2009-06-01 13:00:29 -0700640 * Adds to the current trace request one instruction at a time, just
641 * before that instruction is interpreted. This is the primary trace
642 * selection function. NOTE: return instruction are handled a little
643 * differently. In general, instructions are "proposed" to be added
644 * to the current trace prior to interpretation. If the interpreter
645 * then successfully completes the instruction, is will be considered
646 * part of the request. This allows us to examine machine state prior
647 * to interpretation, and also abort the trace request if the instruction
648 * throws or does something unexpected. However, return instructions
649 * will cause an immediate end to the translation request - which will
650 * be passed to the compiler before the return completes. This is done
651 * in response to special handling of returns by the interpreter (and
652 * because returns cannot throw in a way that causes problems for the
653 * translated code.
654 */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700655int dvmCheckJit(const u2* pc, Thread* self, InterpState* interpState)
656{
Carl Shapiroe3c01da2010-05-20 22:54:18 -0700657 int flags, len;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700658 int switchInterp = false;
Ben Chenga4973592010-03-31 11:59:18 -0700659 bool debugOrProfile = dvmDebuggerOrProfilerActive();
Bill Buzbeed7269912009-11-10 14:31:32 -0800660
Ben Cheng79d173c2009-09-29 16:12:51 -0700661 /* Prepare to handle last PC and stage the current PC */
662 const u2 *lastPC = interpState->lastPC;
663 interpState->lastPC = pc;
664
Ben Chengba4fc8b2009-06-01 13:00:29 -0700665 switch (interpState->jitState) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700666 int offset;
667 DecodedInstruction decInsn;
668 case kJitTSelect:
Ben Chengdc84bb22009-10-02 12:58:52 -0700669 /* First instruction - just remember the PC and exit */
670 if (lastPC == NULL) break;
Ben Cheng79d173c2009-09-29 16:12:51 -0700671 /* Grow the trace around the last PC if jitState is kJitTSelect */
672 dexDecodeInstruction(gDvm.instrFormat, lastPC, &decInsn);
Ben Cheng6c10a972009-10-29 14:39:18 -0700673
674 /*
675 * Treat {PACKED,SPARSE}_SWITCH as trace-ending instructions due
676 * to the amount of space it takes to generate the chaining
677 * cells.
678 */
679 if (interpState->totalTraceLen != 0 &&
680 (decInsn.opCode == OP_PACKED_SWITCH ||
681 decInsn.opCode == OP_SPARSE_SWITCH)) {
682 interpState->jitState = kJitTSelectEnd;
683 break;
684 }
685
Bill Buzbeef9f33282009-11-22 12:45:30 -0800686
Ben Chengba4fc8b2009-06-01 13:00:29 -0700687#if defined(SHOW_TRACE)
688 LOGD("TraceGen: adding %s",getOpcodeName(decInsn.opCode));
689#endif
690 flags = dexGetInstrFlags(gDvm.instrFlags, decInsn.opCode);
Ben Cheng79d173c2009-09-29 16:12:51 -0700691 len = dexGetInstrOrTableWidthAbs(gDvm.instrWidth, lastPC);
692 offset = lastPC - interpState->method->insns;
693 assert((unsigned) offset <
694 dvmGetMethodInsnsSize(interpState->method));
695 if (lastPC != interpState->currRunHead + interpState->currRunLen) {
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700696 int currTraceRun;
697 /* We need to start a new trace run */
698 currTraceRun = ++interpState->currTraceRun;
699 interpState->currRunLen = 0;
Ben Cheng79d173c2009-09-29 16:12:51 -0700700 interpState->currRunHead = (u2*)lastPC;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700701 interpState->trace[currTraceRun].frag.startOffset = offset;
702 interpState->trace[currTraceRun].frag.numInsts = 0;
703 interpState->trace[currTraceRun].frag.runEnd = false;
704 interpState->trace[currTraceRun].frag.hint = kJitHintNone;
705 }
706 interpState->trace[interpState->currTraceRun].frag.numInsts++;
707 interpState->totalTraceLen++;
708 interpState->currRunLen += len;
Ben Cheng79d173c2009-09-29 16:12:51 -0700709
Ben Chengd44faf52010-06-02 15:33:51 -0700710 /*
711 * If the last instruction is an invoke, we will try to sneak in
712 * the move-result* (if existent) into a separate trace run.
713 */
714 int needReservedRun = (flags & kInstrInvoke) ? 1 : 0;
715
Ben Cheng79d173c2009-09-29 16:12:51 -0700716 /* Will probably never hit this with the current trace buildier */
Ben Chengd44faf52010-06-02 15:33:51 -0700717 if (interpState->currTraceRun ==
718 (MAX_JIT_RUN_LEN - 1 - needReservedRun)) {
Ben Cheng79d173c2009-09-29 16:12:51 -0700719 interpState->jitState = kJitTSelectEnd;
720 }
721
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700722 if ( ((flags & kInstrUnconditional) == 0) &&
Bill Buzbeef4ce16f2009-07-28 13:28:25 -0700723 /* don't end trace on INVOKE_DIRECT_EMPTY */
724 (decInsn.opCode != OP_INVOKE_DIRECT_EMPTY) &&
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700725 ((flags & (kInstrCanBranch |
726 kInstrCanSwitch |
727 kInstrCanReturn |
728 kInstrInvoke)) != 0)) {
729 interpState->jitState = kJitTSelectEnd;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700730#if defined(SHOW_TRACE)
Ben Chengd44faf52010-06-02 15:33:51 -0700731 LOGD("TraceGen: ending on %s, basic block end",
732 getOpcodeName(decInsn.opCode));
Ben Chengba4fc8b2009-06-01 13:00:29 -0700733#endif
Ben Chengd44faf52010-06-02 15:33:51 -0700734
735 /*
736 * If the next instruction is a variant of move-result, insert
737 * it to the trace as well.
738 */
739 if (flags & kInstrInvoke) {
740 insertMoveResult(lastPC, len, offset, interpState);
741 }
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700742 }
Bill Buzbee2ce8a6c2009-12-03 15:09:32 -0800743 /* Break on throw or self-loop */
Bill Buzbee324b3ac2009-12-04 13:17:36 -0800744 if ((decInsn.opCode == OP_THROW) || (lastPC == pc)){
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700745 interpState->jitState = kJitTSelectEnd;
746 }
747 if (interpState->totalTraceLen >= JIT_MAX_TRACE_LEN) {
748 interpState->jitState = kJitTSelectEnd;
749 }
Ben Chenga4973592010-03-31 11:59:18 -0700750 /* Abandon the trace request if debugger/profiler is attached */
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700751 if (debugOrProfile) {
Ben Chenga4973592010-03-31 11:59:18 -0700752 interpState->jitState = kJitDone;
Bill Buzbee50a6bf22009-07-08 13:08:04 -0700753 break;
754 }
755 if ((flags & kInstrCanReturn) != kInstrCanReturn) {
756 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700757 }
758 /* NOTE: intentional fallthrough for returns */
759 case kJitTSelectEnd:
760 {
Ben Chenga4973592010-03-31 11:59:18 -0700761 /* Bad trace */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700762 if (interpState->totalTraceLen == 0) {
Bill Buzbeed7269912009-11-10 14:31:32 -0800763 /* Bad trace - mark as untranslatable */
Ben Chenga4973592010-03-31 11:59:18 -0700764 interpState->jitState = kJitDone;
765 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700766 break;
767 }
768 JitTraceDescription* desc =
769 (JitTraceDescription*)malloc(sizeof(JitTraceDescription) +
770 sizeof(JitTraceRun) * (interpState->currTraceRun+1));
771 if (desc == NULL) {
772 LOGE("Out of memory in trace selection");
773 dvmJitStopTranslationRequests();
Ben Chenga4973592010-03-31 11:59:18 -0700774 interpState->jitState = kJitDone;
775 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700776 break;
777 }
778 interpState->trace[interpState->currTraceRun].frag.runEnd =
779 true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700780 desc->method = interpState->method;
781 memcpy((char*)&(desc->trace[0]),
782 (char*)&(interpState->trace[0]),
783 sizeof(JitTraceRun) * (interpState->currTraceRun+1));
784#if defined(SHOW_TRACE)
785 LOGD("TraceGen: trace done, adding to queue");
786#endif
Bill Buzbee964a7b02010-01-28 12:54:19 -0800787 if (dvmCompilerWorkEnqueue(
788 interpState->currTraceHead,kWorkOrderTrace,desc)) {
789 /* Work order successfully enqueued */
790 if (gDvmJit.blockingMode) {
791 dvmCompilerDrainQueue();
792 }
Ben Cheng1357e942010-02-10 17:21:39 -0800793 } else {
794 /*
795 * Make sure the descriptor for the abandoned work order is
796 * freed.
797 */
798 free(desc);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700799 }
Bill Buzbee964a7b02010-01-28 12:54:19 -0800800 /*
801 * Reset "trace in progress" flag whether or not we
802 * successfully entered a work order.
803 */
Ben Cheng6999d842010-01-26 16:46:15 -0800804 JitEntry *jitEntry =
805 lookupAndAdd(interpState->currTraceHead, false);
806 if (jitEntry) {
807 setTraceConstruction(jitEntry, false);
808 }
Ben Chenga4973592010-03-31 11:59:18 -0700809 interpState->jitState = kJitDone;
810 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700811 }
812 break;
813 case kJitSingleStep:
814 interpState->jitState = kJitSingleStepEnd;
815 break;
816 case kJitSingleStepEnd:
817 interpState->entryPoint = kInterpEntryResume;
Ben Chenga4973592010-03-31 11:59:18 -0700818 interpState->jitState = kJitDone;
819 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700820 break;
Ben Chenga4973592010-03-31 11:59:18 -0700821 case kJitDone:
822 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700823 break;
Jeff Hao97319a82009-08-12 16:57:15 -0700824#if defined(WITH_SELF_VERIFICATION)
825 case kJitSelfVerification:
Ben Chengd5adae12010-03-26 17:45:28 -0700826 if (selfVerificationDebugInterp(pc, self, interpState)) {
827 /*
828 * If the next state is not single-step end, we can switch
829 * interpreter now.
830 */
831 if (interpState->jitState != kJitSingleStepEnd) {
Ben Chenga4973592010-03-31 11:59:18 -0700832 interpState->jitState = kJitDone;
833 switchInterp = true;
Ben Chengd5adae12010-03-26 17:45:28 -0700834 }
Jeff Hao97319a82009-08-12 16:57:15 -0700835 }
836 break;
837#endif
Ben Chenga4973592010-03-31 11:59:18 -0700838 /*
839 * If the debug interpreter was entered for non-JIT reasons, check if
840 * the original reason still holds. If not, we have to force the
841 * interpreter switch here and use dvmDebuggerOrProfilerActive instead
842 * of dvmJitDebuggerOrProfilerActive since the latter will alwasy
843 * return true when the debugger/profiler is already detached and the
844 * JIT profiling table is restored.
845 */
846 case kJitNot:
847 switchInterp = !dvmDebuggerOrProfilerActive();
Ben Chenged79ff02009-10-13 13:26:40 -0700848 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700849 default:
Ben Chenga4973592010-03-31 11:59:18 -0700850 LOGE("Unexpected JIT state: %d entry point: %d",
851 interpState->jitState, interpState->entryPoint);
852 dvmAbort();
Ben Cheng9c147b82009-10-07 16:41:46 -0700853 break;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700854 }
Ben Chenga4973592010-03-31 11:59:18 -0700855 /*
856 * Final check to see if we can really switch the interpreter. Make sure
857 * the jitState is kJitDone or kJitNot when switchInterp is set to true.
858 */
859 assert(switchInterp == false || interpState->jitState == kJitDone ||
860 interpState->jitState == kJitNot);
861 return switchInterp && !debugOrProfile;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700862}
863
Ben Chengccd6c012009-10-15 14:52:45 -0700864JitEntry *dvmFindJitEntry(const u2* pc)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700865{
866 int idx = dvmJitHash(pc);
867
868 /* Expect a high hit rate on 1st shot */
869 if (gDvmJit.pJitEntryTable[idx].dPC == pc)
870 return &gDvmJit.pJitEntryTable[idx];
871 else {
Bill Buzbee27176222009-06-09 09:20:16 -0700872 int chainEndMarker = gDvmJit.jitTableSize;
Bill Buzbee716f1202009-07-23 13:22:09 -0700873 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
874 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700875 if (gDvmJit.pJitEntryTable[idx].dPC == pc)
876 return &gDvmJit.pJitEntryTable[idx];
877 }
878 }
879 return NULL;
880}
881
Bill Buzbee27176222009-06-09 09:20:16 -0700882/*
Ben Chengba4fc8b2009-06-01 13:00:29 -0700883 * If a translated code address exists for the davik byte code
884 * pointer return it. This routine needs to be fast.
885 */
886void* dvmJitGetCodeAddr(const u2* dPC)
887{
888 int idx = dvmJitHash(dPC);
Ben Cheng6999d842010-01-26 16:46:15 -0800889 const u2* npc = gDvmJit.pJitEntryTable[idx].dPC;
Bill Buzbee9797a232010-01-12 12:20:13 -0800890 if (npc != NULL) {
Ben Cheng6999d842010-01-26 16:46:15 -0800891 bool hideTranslation = (gDvm.sumThreadSuspendCount != 0) ||
892 (gDvmJit.codeCacheFull == true) ||
893 (gDvmJit.pProfTable == NULL);
894
Bill Buzbee9797a232010-01-12 12:20:13 -0800895 if (npc == dPC) {
Ben Cheng978738d2010-05-13 13:45:57 -0700896#if defined(WITH_JIT_TUNING)
Bill Buzbee9797a232010-01-12 12:20:13 -0800897 gDvmJit.addrLookupsFound++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700898#endif
Ben Cheng6999d842010-01-26 16:46:15 -0800899 return hideTranslation ?
900 NULL : gDvmJit.pJitEntryTable[idx].codeAddress;
Bill Buzbee9797a232010-01-12 12:20:13 -0800901 } else {
902 int chainEndMarker = gDvmJit.jitTableSize;
903 while (gDvmJit.pJitEntryTable[idx].u.info.chain != chainEndMarker) {
904 idx = gDvmJit.pJitEntryTable[idx].u.info.chain;
905 if (gDvmJit.pJitEntryTable[idx].dPC == dPC) {
Ben Cheng978738d2010-05-13 13:45:57 -0700906#if defined(WITH_JIT_TUNING)
Bill Buzbee9797a232010-01-12 12:20:13 -0800907 gDvmJit.addrLookupsFound++;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700908#endif
Ben Cheng6999d842010-01-26 16:46:15 -0800909 return hideTranslation ?
910 NULL : gDvmJit.pJitEntryTable[idx].codeAddress;
Bill Buzbee9797a232010-01-12 12:20:13 -0800911 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700912 }
913 }
914 }
Ben Cheng978738d2010-05-13 13:45:57 -0700915#if defined(WITH_JIT_TUNING)
Ben Chengba4fc8b2009-06-01 13:00:29 -0700916 gDvmJit.addrLookupsNotFound++;
917#endif
918 return NULL;
919}
920
921/*
922 * Register the translated code pointer into the JitTable.
Bill Buzbee9a8c75a2009-11-08 14:31:20 -0800923 * NOTE: Once a codeAddress field transitions from initial state to
Ben Chengba4fc8b2009-06-01 13:00:29 -0700924 * JIT'd code, it must not be altered without first halting all
Bill Buzbee716f1202009-07-23 13:22:09 -0700925 * threads. This routine should only be called by the compiler
926 * thread.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700927 */
Bill Buzbee716f1202009-07-23 13:22:09 -0700928void dvmJitSetCodeAddr(const u2* dPC, void *nPC, JitInstructionSetType set) {
929 JitEntryInfoUnion oldValue;
930 JitEntryInfoUnion newValue;
Bill Buzbee964a7b02010-01-28 12:54:19 -0800931 JitEntry *jitEntry = lookupAndAdd(dPC, false);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700932 assert(jitEntry);
Bill Buzbee716f1202009-07-23 13:22:09 -0700933 /* Note: order of update is important */
934 do {
935 oldValue = jitEntry->u;
936 newValue = oldValue;
937 newValue.info.instructionSet = set;
938 } while (!ATOMIC_CMP_SWAP(
939 &jitEntry->u.infoWord,
940 oldValue.infoWord, newValue.infoWord));
941 jitEntry->codeAddress = nPC;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700942}
943
944/*
945 * Determine if valid trace-bulding request is active. Return true
946 * if we need to abort and switch back to the fast interpreter, false
Ben Chenga4973592010-03-31 11:59:18 -0700947 * otherwise.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700948 */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700949bool dvmJitCheckTraceRequest(Thread* self, InterpState* interpState)
950{
Ben Chenga4973592010-03-31 11:59:18 -0700951 bool switchInterp = false; /* Assume success */
Bill Buzbee48f18242009-06-19 16:02:27 -0700952 int i;
Ben Cheng40094c12010-02-24 20:58:44 -0800953 intptr_t filterKey = ((intptr_t) interpState->pc) >>
954 JIT_TRACE_THRESH_FILTER_GRAN_LOG2;
Ben Chenga4973592010-03-31 11:59:18 -0700955 bool debugOrProfile = dvmDebuggerOrProfilerActive();
Ben Cheng40094c12010-02-24 20:58:44 -0800956
Ben Chenga4973592010-03-31 11:59:18 -0700957 /* Check if the JIT request can be handled now */
958 if (gDvmJit.pJitEntryTable != NULL && debugOrProfile == false) {
959 /* Bypass the filter for hot trace requests or during stress mode */
960 if (interpState->jitState == kJitTSelectRequest &&
961 gDvmJit.threshold > 6) {
Ben Cheng40094c12010-02-24 20:58:44 -0800962 /* Two-level filtering scheme */
963 for (i=0; i< JIT_TRACE_THRESH_FILTER_SIZE; i++) {
964 if (filterKey == interpState->threshFilter[i]) {
965 break;
966 }
Bill Buzbee48f18242009-06-19 16:02:27 -0700967 }
Ben Cheng40094c12010-02-24 20:58:44 -0800968 if (i == JIT_TRACE_THRESH_FILTER_SIZE) {
969 /*
970 * Use random replacement policy - otherwise we could miss a
971 * large loop that contains more traces than the size of our
972 * filter array.
973 */
974 i = rand() % JIT_TRACE_THRESH_FILTER_SIZE;
975 interpState->threshFilter[i] = filterKey;
Ben Chenga4973592010-03-31 11:59:18 -0700976 interpState->jitState = kJitDone;
Ben Cheng40094c12010-02-24 20:58:44 -0800977 }
Ben Chenga4973592010-03-31 11:59:18 -0700978 }
Bill Buzbeed7269912009-11-10 14:31:32 -0800979
Ben Chenga4973592010-03-31 11:59:18 -0700980 /* If the compiler is backlogged, cancel any JIT actions */
981 if (gDvmJit.compilerQueueLength >= gDvmJit.compilerHighWater) {
982 interpState->jitState = kJitDone;
Ben Cheng40094c12010-02-24 20:58:44 -0800983 }
Bill Buzbeed7269912009-11-10 14:31:32 -0800984
Ben Chengba4fc8b2009-06-01 13:00:29 -0700985 /*
Ben Chenga4973592010-03-31 11:59:18 -0700986 * Check for additional reasons that might force the trace select
987 * request to be dropped
Ben Chengba4fc8b2009-06-01 13:00:29 -0700988 */
Ben Chenga4973592010-03-31 11:59:18 -0700989 if (interpState->jitState == kJitTSelectRequest ||
990 interpState->jitState == kJitTSelectRequestHot) {
Bill Buzbee964a7b02010-01-28 12:54:19 -0800991 JitEntry *slot = lookupAndAdd(interpState->pc, false);
Bill Buzbee716f1202009-07-23 13:22:09 -0700992 if (slot == NULL) {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700993 /*
Bill Buzbee716f1202009-07-23 13:22:09 -0700994 * Table is full. This should have been
995 * detected by the compiler thread and the table
996 * resized before we run into it here. Assume bad things
997 * are afoot and disable profiling.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700998 */
Ben Chenga4973592010-03-31 11:59:18 -0700999 interpState->jitState = kJitDone;
Bill Buzbee716f1202009-07-23 13:22:09 -07001000 LOGD("JIT: JitTable full, disabling profiling");
1001 dvmJitStopTranslationRequests();
Bill Buzbeed7269912009-11-10 14:31:32 -08001002 } else if (slot->u.info.traceConstruction) {
1003 /*
Ben Cheng60c24f42010-01-04 12:29:56 -08001004 * Trace request already in progress, but most likely it
Bill Buzbeed7269912009-11-10 14:31:32 -08001005 * aborted without cleaning up. Assume the worst and
1006 * mark trace head as untranslatable. If we're wrong,
1007 * the compiler thread will correct the entry when the
1008 * translation is completed. The downside here is that
1009 * some existing translation may chain to the interpret-only
1010 * template instead of the real translation during this
1011 * window. Performance, but not correctness, issue.
1012 */
Ben Chenga4973592010-03-31 11:59:18 -07001013 interpState->jitState = kJitDone;
Bill Buzbeed7269912009-11-10 14:31:32 -08001014 resetTracehead(interpState, slot);
1015 } else if (slot->codeAddress) {
1016 /* Nothing to do here - just return */
Ben Chenga4973592010-03-31 11:59:18 -07001017 interpState->jitState = kJitDone;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001018 } else {
Bill Buzbeed7269912009-11-10 14:31:32 -08001019 /*
1020 * Mark request. Note, we are not guaranteed exclusivity
1021 * here. A window exists for another thread to be
1022 * attempting to build this same trace. Rather than
1023 * bear the cost of locking, we'll just allow that to
1024 * happen. The compiler thread, if it chooses, can
1025 * discard redundant requests.
1026 */
1027 setTraceConstruction(slot, true);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001028 }
1029 }
Ben Chenga4973592010-03-31 11:59:18 -07001030
Ben Chengba4fc8b2009-06-01 13:00:29 -07001031 switch (interpState->jitState) {
1032 case kJitTSelectRequest:
Ben Cheng40094c12010-02-24 20:58:44 -08001033 case kJitTSelectRequestHot:
Ben Chenga4973592010-03-31 11:59:18 -07001034 interpState->jitState = kJitTSelect;
1035 interpState->currTraceHead = interpState->pc;
1036 interpState->currTraceRun = 0;
1037 interpState->totalTraceLen = 0;
1038 interpState->currRunHead = interpState->pc;
1039 interpState->currRunLen = 0;
1040 interpState->trace[0].frag.startOffset =
1041 interpState->pc - interpState->method->insns;
1042 interpState->trace[0].frag.numInsts = 0;
1043 interpState->trace[0].frag.runEnd = false;
1044 interpState->trace[0].frag.hint = kJitHintNone;
1045 interpState->lastPC = 0;
1046 break;
1047 /*
1048 * For JIT's perspective there is no need to stay in the debug
1049 * interpreter unless debugger/profiler is attached.
1050 */
1051 case kJitDone:
1052 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001053 break;
1054 default:
Ben Chenga4973592010-03-31 11:59:18 -07001055 LOGE("Unexpected JIT state: %d entry point: %d",
1056 interpState->jitState, interpState->entryPoint);
Ben Chengba4fc8b2009-06-01 13:00:29 -07001057 dvmAbort();
1058 }
Ben Chenga4973592010-03-31 11:59:18 -07001059 } else {
1060 /*
1061 * Cannot build trace this time - ready to leave the dbg interpreter
1062 */
1063 interpState->jitState = kJitDone;
1064 switchInterp = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001065 }
Ben Chenga4973592010-03-31 11:59:18 -07001066
1067 /*
1068 * Final check to see if we can really switch the interpreter. Make sure
1069 * the jitState is kJitDone when switchInterp is set to true.
1070 */
1071 assert(switchInterp == false || interpState->jitState == kJitDone);
1072 return switchInterp && !debugOrProfile;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001073}
1074
Bill Buzbee27176222009-06-09 09:20:16 -07001075/*
1076 * Resizes the JitTable. Must be a power of 2, and returns true on failure.
Bill Buzbee964a7b02010-01-28 12:54:19 -08001077 * Stops all threads, and thus is a heavyweight operation. May only be called
1078 * by the compiler thread.
Bill Buzbee27176222009-06-09 09:20:16 -07001079 */
1080bool dvmJitResizeJitTable( unsigned int size )
1081{
Bill Buzbee716f1202009-07-23 13:22:09 -07001082 JitEntry *pNewTable;
1083 JitEntry *pOldTable;
Bill Buzbee964a7b02010-01-28 12:54:19 -08001084 JitEntry tempEntry;
Bill Buzbee27176222009-06-09 09:20:16 -07001085 u4 newMask;
Bill Buzbee716f1202009-07-23 13:22:09 -07001086 unsigned int oldSize;
Bill Buzbee27176222009-06-09 09:20:16 -07001087 unsigned int i;
1088
Ben Cheng3f02aa42009-08-14 13:52:09 -07001089 assert(gDvmJit.pJitEntryTable != NULL);
Bill Buzbee27176222009-06-09 09:20:16 -07001090 assert(size && !(size & (size - 1))); /* Is power of 2? */
1091
Ben Chenga4973592010-03-31 11:59:18 -07001092 LOGI("Jit: resizing JitTable from %d to %d", gDvmJit.jitTableSize, size);
Bill Buzbee27176222009-06-09 09:20:16 -07001093
1094 newMask = size - 1;
1095
1096 if (size <= gDvmJit.jitTableSize) {
1097 return true;
1098 }
1099
Bill Buzbee964a7b02010-01-28 12:54:19 -08001100 /* Make sure requested size is compatible with chain field width */
1101 tempEntry.u.info.chain = size;
1102 if (tempEntry.u.info.chain != size) {
1103 LOGD("Jit: JitTable request of %d too big", size);
1104 return true;
1105 }
1106
Bill Buzbee716f1202009-07-23 13:22:09 -07001107 pNewTable = (JitEntry*)calloc(size, sizeof(*pNewTable));
Bill Buzbee27176222009-06-09 09:20:16 -07001108 if (pNewTable == NULL) {
1109 return true;
1110 }
1111 for (i=0; i< size; i++) {
Bill Buzbee716f1202009-07-23 13:22:09 -07001112 pNewTable[i].u.info.chain = size; /* Initialize chain termination */
Bill Buzbee27176222009-06-09 09:20:16 -07001113 }
1114
1115 /* Stop all other interpreting/jit'ng threads */
Ben Chenga8e64a72009-10-20 13:01:36 -07001116 dvmSuspendAllThreads(SUSPEND_FOR_TBL_RESIZE);
Bill Buzbee27176222009-06-09 09:20:16 -07001117
Bill Buzbee716f1202009-07-23 13:22:09 -07001118 pOldTable = gDvmJit.pJitEntryTable;
1119 oldSize = gDvmJit.jitTableSize;
Bill Buzbee27176222009-06-09 09:20:16 -07001120
1121 dvmLockMutex(&gDvmJit.tableLock);
Bill Buzbee27176222009-06-09 09:20:16 -07001122 gDvmJit.pJitEntryTable = pNewTable;
1123 gDvmJit.jitTableSize = size;
1124 gDvmJit.jitTableMask = size - 1;
Bill Buzbee716f1202009-07-23 13:22:09 -07001125 gDvmJit.jitTableEntriesUsed = 0;
Bill Buzbee27176222009-06-09 09:20:16 -07001126
Bill Buzbee716f1202009-07-23 13:22:09 -07001127 for (i=0; i < oldSize; i++) {
1128 if (pOldTable[i].dPC) {
1129 JitEntry *p;
1130 u2 chain;
Bill Buzbee964a7b02010-01-28 12:54:19 -08001131 p = lookupAndAdd(pOldTable[i].dPC, true /* holds tableLock*/ );
1132 p->codeAddress = pOldTable[i].codeAddress;
Bill Buzbee716f1202009-07-23 13:22:09 -07001133 /* We need to preserve the new chain field, but copy the rest */
Bill Buzbee716f1202009-07-23 13:22:09 -07001134 chain = p->u.info.chain;
1135 p->u = pOldTable[i].u;
1136 p->u.info.chain = chain;
Bill Buzbee716f1202009-07-23 13:22:09 -07001137 }
1138 }
Bill Buzbee964a7b02010-01-28 12:54:19 -08001139 dvmUnlockMutex(&gDvmJit.tableLock);
Bill Buzbee716f1202009-07-23 13:22:09 -07001140
1141 free(pOldTable);
1142
Bill Buzbee27176222009-06-09 09:20:16 -07001143 /* Restart the world */
Ben Chenga8e64a72009-10-20 13:01:36 -07001144 dvmResumeAllThreads(SUSPEND_FOR_TBL_RESIZE);
Bill Buzbee27176222009-06-09 09:20:16 -07001145
1146 return false;
1147}
1148
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001149/*
Ben Cheng60c24f42010-01-04 12:29:56 -08001150 * Reset the JitTable to the initial clean state.
1151 */
1152void dvmJitResetTable(void)
1153{
1154 JitEntry *jitEntry = gDvmJit.pJitEntryTable;
1155 unsigned int size = gDvmJit.jitTableSize;
1156 unsigned int i;
1157
1158 dvmLockMutex(&gDvmJit.tableLock);
1159 memset((void *) jitEntry, 0, sizeof(JitEntry) * size);
1160 for (i=0; i< size; i++) {
1161 jitEntry[i].u.info.chain = size; /* Initialize chain termination */
1162 }
1163 gDvmJit.jitTableEntriesUsed = 0;
1164 dvmUnlockMutex(&gDvmJit.tableLock);
1165}
1166
1167/*
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001168 * Float/double conversion requires clamping to min and max of integer form. If
1169 * target doesn't support this normally, use these.
1170 */
1171s8 dvmJitd2l(double d)
1172{
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001173 static const double kMaxLong = (double)(s8)0x7fffffffffffffffULL;
1174 static const double kMinLong = (double)(s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001175 if (d >= kMaxLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001176 return (s8)0x7fffffffffffffffULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001177 else if (d <= kMinLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001178 return (s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001179 else if (d != d) // NaN case
1180 return 0;
1181 else
1182 return (s8)d;
1183}
1184
1185s8 dvmJitf2l(float f)
1186{
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001187 static const float kMaxLong = (float)(s8)0x7fffffffffffffffULL;
1188 static const float kMinLong = (float)(s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001189 if (f >= kMaxLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001190 return (s8)0x7fffffffffffffffULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001191 else if (f <= kMinLong)
Bill Buzbee9727c3d2009-08-01 11:32:36 -07001192 return (s8)0x8000000000000000ULL;
Bill Buzbee50a6bf22009-07-08 13:08:04 -07001193 else if (f != f) // NaN case
1194 return 0;
1195 else
1196 return (s8)f;
1197}
1198
Ben Chengba4fc8b2009-06-01 13:00:29 -07001199#endif /* WITH_JIT */