SamplingTool.cpp 15.3 KB
Newer Older
1
/*
2
 * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "SamplingTool.h"

#include "CodeBlock.h"
ggaren@apple.com's avatar
ggaren@apple.com committed
33
#include "Interpreter.h"
34 35
#include "Opcode.h"

36
#if !OS(WINDOWS)
37 38 39
#include <unistd.h>
#endif

40
namespace JSC {
41

42 43 44
#if ENABLE(SAMPLING_FLAGS)

void SamplingFlags::sample()
45
{
ggaren@apple.com's avatar
ggaren@apple.com committed
46
    uint32_t mask = static_cast<uint32_t>(1 << 31);
47 48 49 50 51 52
    unsigned index;

    for (index = 0; index < 32; ++index) {
        if (mask & s_flags)
            break;
        mask >>= 1;
53 54
    }

55 56
    s_flagCounts[32 - index]++;
}
57

58 59 60 61 62 63 64 65 66 67 68
void SamplingFlags::start()
{
    for (unsigned i = 0; i <= 32; ++i)
        s_flagCounts[i] = 0;
}
void SamplingFlags::stop()
{
    uint64_t total = 0;
    for (unsigned i = 0; i <= 32; ++i)
        total += s_flagCounts[i];

69
    if (total) {
70
        dataLogF("\nSamplingFlags: sample counts with flags set: (%lld total)\n", total);
71 72
        for (unsigned i = 0; i <= 32; ++i) {
            if (s_flagCounts[i])
73
                dataLogF("  [ %02d ] : %lld\t\t(%03.2f%%)\n", i, s_flagCounts[i], (100.0 * s_flagCounts[i]) / total);
74
        }
75
        dataLogF("\n");
76
    } else
77
    dataLogF("\nSamplingFlags: no samples.\n\n");
78
}
79 80 81 82 83 84 85
uint64_t SamplingFlags::s_flagCounts[33];

#else
void SamplingFlags::start() {}
void SamplingFlags::stop() {}
#endif

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#if ENABLE(SAMPLING_REGIONS)
volatile uintptr_t SamplingRegion::s_currentOrReserved;
Spectrum<const char*>* SamplingRegion::s_spectrum;
unsigned long SamplingRegion::s_noneOfTheAbove;
unsigned SamplingRegion::s_numberOfSamplesSinceDump;

SamplingRegion::Locker::Locker()
{
    uintptr_t previous;
    while (true) {
        previous = s_currentOrReserved;
        if (previous & 1) {
#if OS(UNIX)
            sched_yield();
#endif
            continue;
        }
103
        if (WTF::weakCompareAndSwapUIntPtr(&s_currentOrReserved, previous, previous | 1))
104 105 106 107 108 109 110 111 112 113 114 115
            break;
    }
}

SamplingRegion::Locker::~Locker()
{
    // We don't need the CAS, but we do it out of an
    // abundance of caution (and because it gives us a memory fence, which is
    // never bad).
    uintptr_t previous;
    do {
        previous = s_currentOrReserved;
116
    } while (!WTF::weakCompareAndSwapUIntPtr(&s_currentOrReserved, previous, previous & ~1));
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
}

void SamplingRegion::sample()
{
    // Make sure we lock s_current.
    Locker locker;
    
    // Create a spectrum if we don't have one already.
    if (!s_spectrum)
        s_spectrum = new Spectrum<const char*>();
    
    ASSERT(s_currentOrReserved & 1);
    
    // Walk the region stack, and record each region we see.
    SamplingRegion* region = bitwise_cast<SamplingRegion*>(s_currentOrReserved & ~1);
    if (region) {
        for (; region; region = region->m_previous)
            s_spectrum->add(region->m_name);
    } else
        s_noneOfTheAbove++;
    
    if (s_numberOfSamplesSinceDump++ == SamplingThread::s_hertz) {
        s_numberOfSamplesSinceDump = 0;
        dumpInternal();
    }
}

void SamplingRegion::dump()
{
    Locker locker;
    
    dumpInternal();
}

void SamplingRegion::dumpInternal()
{
    if (!s_spectrum) {
154
        dataLogF("\nSamplingRegion: was never sampled.\n\n");
155 156 157 158 159 160 161 162 163
        return;
    }
    
    Vector<Spectrum<const char*>::KeyAndCount> list = s_spectrum->buildList();
    
    unsigned long total = s_noneOfTheAbove;
    for (unsigned i = list.size(); i--;)
        total += list[i].count;
    
164
    dataLogF("\nSamplingRegion: sample counts for regions: (%lu samples)\n", total);
165 166

    for (unsigned i = list.size(); i--;)
167
        dataLogF("    %3.2lf%%  %s\n", (100.0 * list[i].count) / total, list[i].key);
168 169 170 171 172
}
#else // ENABLE(SAMPLING_REGIONS)
void SamplingRegion::dump() { }
#endif // ENABLE(SAMPLING_REGIONS)

173 174 175 176 177 178 179
/*
  Start with flag 16 set.
  By doing this the monitoring of lower valued flags will be masked out
  until flag 16 is explictly cleared.
*/
uint32_t SamplingFlags::s_flags = 1 << 15;

180

181
#if OS(WINDOWS)
182 183 184

static void sleepForMicroseconds(unsigned us)
{
185
    unsigned ms = us / 1000;
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    if (us && !ms)
        ms = 1;
    Sleep(ms);
}

#else 

static void sleepForMicroseconds(unsigned us)
{
    usleep(us);
}

#endif

static inline unsigned hertz2us(unsigned hertz)
{
    return 1000000 / hertz;
}

205

206
SamplingTool* SamplingTool::s_samplingTool = 0;
207

208

209 210
bool SamplingThread::s_running = false;
unsigned SamplingThread::s_hertz = 10000;
dimich@chromium.org's avatar
dimich@chromium.org committed
211
ThreadIdentifier SamplingThread::s_samplingThread;
212

213
void SamplingThread::threadStartFunc(void*)
214 215 216
{
    while (s_running) {
        sleepForMicroseconds(hertz2us(s_hertz));
217

218 219 220
#if ENABLE(SAMPLING_FLAGS)
        SamplingFlags::sample();
#endif
221 222 223
#if ENABLE(SAMPLING_REGIONS)
        SamplingRegion::sample();
#endif
224 225
#if ENABLE(OPCODE_SAMPLING)
        SamplingTool::sample();
226
#endif
227 228 229
    }
}

230 231

void SamplingThread::start(unsigned hertz)
232
{
233 234 235 236
    ASSERT(!s_running);
    s_running = true;
    s_hertz = hertz;

dimich@chromium.org's avatar
dimich@chromium.org committed
237
    s_samplingThread = createThread(threadStartFunc, 0, "JavaScriptCore::Sampler");
238 239
}

240 241 242 243
void SamplingThread::stop()
{
    ASSERT(s_running);
    s_running = false;
244
    waitForThreadCompletion(s_samplingThread);
245 246 247
}


248
void ScriptSampleRecord::sample(CodeBlock* codeBlock, Instruction* vPC)
249
{
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    if (!m_samples) {
        m_size = codeBlock->instructions().size();
        m_samples = static_cast<int*>(calloc(m_size, sizeof(int)));
        m_codeBlock = codeBlock;
    }

    ++m_sampleCount;

    unsigned offest = vPC - codeBlock->instructions().begin();
    // Since we don't read and write codeBlock and vPC atomically, this check
    // can fail if we sample mid op_call / op_ret.
    if (offest < m_size) {
        m_samples[offest]++;
        m_opcodeSampleCount++;
    }
}

void SamplingTool::doRun()
{
    Sample sample(m_sample, m_codeBlock);
    ++m_sampleCount;

    if (sample.isNull())
        return;

    if (!sample.inHostFunction()) {
        unsigned opcodeID = m_interpreter->getOpcodeID(sample.vPC()[0].u.opcode);

        ++m_opcodeSampleCount;
        ++m_opcodeSamples[opcodeID];

        if (sample.inCTIFunction())
            m_opcodeSamplesInCTIFunctions[opcodeID]++;
    }

#if ENABLE(CODEBLOCK_SAMPLING)
286
    if (CodeBlock* codeBlock = sample.codeBlock()) {
287 288
        MutexLocker locker(m_scriptSampleMapMutex);
        ScriptSampleRecord* record = m_scopeSampleMap->get(codeBlock->ownerExecutable());
289 290 291
        ASSERT(record);
        record->sample(codeBlock, sample.vPC());
    }
292
#endif
293 294
}

295
void SamplingTool::sample()
296
{
297 298
    s_samplingTool->doRun();
}
299

300
void SamplingTool::notifyOfScope(VM& vm, ScriptExecutable* script)
301
{
302
#if ENABLE(CODEBLOCK_SAMPLING)
303
    MutexLocker locker(m_scriptSampleMapMutex);
304
    m_scopeSampleMap->set(script, adoptPtr(new ScriptSampleRecord(vm, script)));
305
#else
306
    UNUSED_PARAM(vm);
307
    UNUSED_PARAM(script);
308
#endif
309
}
310

311
void SamplingTool::setup()
312
{
313
    s_samplingTool = this;
314 315
}

316
#if ENABLE(OPCODE_SAMPLING)
317

318 319
struct OpcodeSampleInfo {
    OpcodeID opcode;
320
    long long count;
321
    long long countInCTIFunctions;
322 323
};

324
struct LineCountInfo {
325 326 327 328
    unsigned line;
    unsigned count;
};

329
static int compareOpcodeIndicesSampling(const void* left, const void* right)
330
{
331 332
    const OpcodeSampleInfo* leftSampleInfo = reinterpret_cast<const OpcodeSampleInfo*>(left);
    const OpcodeSampleInfo* rightSampleInfo = reinterpret_cast<const OpcodeSampleInfo*>(right);
333 334 335 336

    return (leftSampleInfo->count < rightSampleInfo->count) ? 1 : (leftSampleInfo->count > rightSampleInfo->count) ? -1 : 0;
}

337 338 339 340 341 342 343 344 345
#if ENABLE(CODEBLOCK_SAMPLING)
static int compareLineCountInfoSampling(const void* left, const void* right)
{
    const LineCountInfo* leftLineCount = reinterpret_cast<const LineCountInfo*>(left);
    const LineCountInfo* rightLineCount = reinterpret_cast<const LineCountInfo*>(right);

    return (leftLineCount->line > rightLineCount->line) ? 1 : (leftLineCount->line < rightLineCount->line) ? -1 : 0;
}

346
static int compareScriptSampleRecords(const void* left, const void* right)
347
{
348 349
    const ScriptSampleRecord* const leftValue = *static_cast<const ScriptSampleRecord* const *>(left);
    const ScriptSampleRecord* const rightValue = *static_cast<const ScriptSampleRecord* const *>(right);
350

351
    return (leftValue->m_sampleCount < rightValue->m_sampleCount) ? 1 : (leftValue->m_sampleCount > rightValue->m_sampleCount) ? -1 : 0;
352
}
353
#endif
354 355 356 357

void SamplingTool::dump(ExecState* exec)
{
    // Tidies up SunSpider output by removing short scripts - such a small number of samples would likely not be useful anyhow.
358
    if (m_sampleCount < 10)
359 360
        return;
    
361
    // (1) Build and sort 'opcodeSampleInfo' array.
362

363 364 365 366 367
    OpcodeSampleInfo opcodeSampleInfo[numOpcodeIDs];
    for (int i = 0; i < numOpcodeIDs; ++i) {
        opcodeSampleInfo[i].opcode = static_cast<OpcodeID>(i);
        opcodeSampleInfo[i].count = m_opcodeSamples[i];
        opcodeSampleInfo[i].countInCTIFunctions = m_opcodeSamplesInCTIFunctions[i];
368 369
    }

370
    qsort(opcodeSampleInfo, numOpcodeIDs, sizeof(OpcodeSampleInfo), compareOpcodeIndicesSampling);
371

372
    // (2) Print Opcode sampling results.
373

374 375 376 377
    dataLogF("\nBytecode samples [*]\n");
    dataLogF("                             sample   %% of       %% of     |   cti     cti %%\n");
    dataLogF("opcode                       count     VM        total    |  count   of self\n");
    dataLogF("-------------------------------------------------------   |  ----------------\n");
378

379 380
    for (int i = 0; i < numOpcodeIDs; ++i) {
        long long count = opcodeSampleInfo[i].count;
381 382 383
        if (!count)
            continue;

384
        OpcodeID opcodeID = opcodeSampleInfo[i].opcode;
385
        
386 387 388
        const char* opcodeName = opcodeNames[opcodeID];
        const char* opcodePadding = padOpcodeName(opcodeID, 28);
        double percentOfVM = (static_cast<double>(count) * 100) / m_opcodeSampleCount;
389
        double percentOfTotal = (static_cast<double>(count) * 100) / m_sampleCount;
390
        long long countInCTIFunctions = opcodeSampleInfo[i].countInCTIFunctions;
391
        double percentInCTIFunctions = (static_cast<double>(countInCTIFunctions) * 100) / count;
392
        debugDebugPrintf("%s:%s%-6lld %.3f%%\t%.3f%%\t  |   %-6lld %.3f%%\n", opcodeName, opcodePadding, count, percentOfVM, percentOfTotal, countInCTIFunctions, percentInCTIFunctions);
393 394
    }
    
395 396 397 398 399 400 401 402 403
    dataLogF("\n[*] Samples inside host code are not charged to any Bytecode.\n\n");
    dataLogF("\tSamples inside VM:\t\t%lld / %lld (%.3f%%)\n", m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_opcodeSampleCount) * 100) / m_sampleCount);
    dataLogF("\tSamples inside host code:\t%lld / %lld (%.3f%%)\n\n", m_sampleCount - m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_sampleCount - m_opcodeSampleCount) * 100) / m_sampleCount);
    dataLogF("\tsample count:\tsamples inside this opcode\n");
    dataLogF("\t%% of VM:\tsample count / all opcode samples\n");
    dataLogF("\t%% of total:\tsample count / all samples\n");
    dataLogF("\t--------------\n");
    dataLogF("\tcti count:\tsamples inside a CTI function called by this opcode\n");
    dataLogF("\tcti %% of self:\tcti count / sample count\n");
404
    
405 406
#if ENABLE(CODEBLOCK_SAMPLING)

407
    // (3) Build and sort 'codeBlockSamples' array.
408 409

    int scopeCount = m_scopeSampleMap->size();
410 411
    Vector<ScriptSampleRecord*> codeBlockSamples(scopeCount);
    ScriptSampleRecordMap::iterator iter = m_scopeSampleMap->begin();
412
    for (int i = 0; i < scopeCount; ++i, ++iter)
413
        codeBlockSamples[i] = iter->value.get();
414

415
    qsort(codeBlockSamples.begin(), scopeCount, sizeof(ScriptSampleRecord*), compareScriptSampleRecords);
416

417
    // (4) Print data from 'codeBlockSamples' array.
418

419
    dataLogF("\nCodeBlock samples\n\n"); 
420

421
    for (int i = 0; i < scopeCount; ++i) {
422
        ScriptSampleRecord* record = codeBlockSamples[i];
423 424
        CodeBlock* codeBlock = record->m_codeBlock;

425
        double blockPercent = (record->m_sampleCount * 100.0) / m_sampleCount;
426

427
        if (blockPercent >= 1) {
428
            //Instruction* code = codeBlock->instructions().begin();
429
            dataLogF("#%d: %s:%d: %d / %lld (%.3f%%)\n", i + 1, record->m_executable->sourceURL().utf8().data(), codeBlock->lineNumberForBytecodeOffset(0), record->m_sampleCount, m_sampleCount, blockPercent);
430 431 432
            if (i < 10) {
                HashMap<unsigned,unsigned> lineCounts;
                codeBlock->dump(exec);
433

434
                dataLogF("    Opcode and line number samples [*]\n\n");
435
                for (unsigned op = 0; op < record->m_size; ++op) {
436
                    int count = record->m_samples[op];
437
                    if (count) {
438
                        dataLogF("    [% 4d] has sample count: % 4d\n", op, count);
439
                        unsigned line = codeBlock->lineNumberForBytecodeOffset(op);
440 441 442
                        lineCounts.set(line, (lineCounts.contains(line) ? lineCounts.get(line) : 0) + count);
                    }
                }
443
                dataLogF("\n");
444

445 446 447 448
                int linesCount = lineCounts.size();
                Vector<LineCountInfo> lineCountInfo(linesCount);
                int lineno = 0;
                for (HashMap<unsigned,unsigned>::iterator iter = lineCounts.begin(); iter != lineCounts.end(); ++iter, ++lineno) {
449 450
                    lineCountInfo[lineno].line = iter->key;
                    lineCountInfo[lineno].count = iter->value;
451
                }
452

453
                qsort(lineCountInfo.begin(), linesCount, sizeof(LineCountInfo), compareLineCountInfoSampling);
454

455
                for (lineno = 0; lineno < linesCount; ++lineno) {
456
                    dataLogF("    Line #%d has sample count %d.\n", lineCountInfo[lineno].line, lineCountInfo[lineno].count);
457
                }
458 459 460 461
                dataLogF("\n");
                dataLogF("    [*] Samples inside host code are charged to the calling Bytecode.\n");
                dataLogF("        Samples on a call / return boundary are not charged to a specific opcode or line.\n\n");
                dataLogF("            Samples on a call / return boundary: %d / %d (%.3f%%)\n\n", record->m_sampleCount - record->m_opcodeSampleCount, record->m_sampleCount, (static_cast<double>(record->m_sampleCount - record->m_opcodeSampleCount) * 100) / record->m_sampleCount);
462 463 464
            }
        }
    }
465 466 467
#else
    UNUSED_PARAM(exec);
#endif
468 469 470 471 472 473 474 475 476 477
}

#else

void SamplingTool::dump(ExecState*)
{
}

#endif

478
} // namespace JSC