aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/jit/qv4ir.cpp
blob: cb3eeeec6069696863b1197dcc2ae4253d7ddb0a (plain)
1
2
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <private/qqmlglobal_p.h>
#include "qv4ir_p.h"
#include "qv4node_p.h"
#include "qv4function_p.h"
#include <qv4graph_p.h>
#include "qv4stackframe_p.h"
#include "qv4operation_p.h"
#include "qv4util_p.h"

#include <QtCore/qloggingcategory.h>
#include <QtCore/qjsonobject.h>
#include <QtCore/qjsonarray.h>
#include <QtCore/qfile.h>

QT_BEGIN_NAMESPACE
namespace QV4 {
namespace IR {

Q_LOGGING_CATEGORY(lcJsonIR, "qt.v4.ir.json");
Q_LOGGING_CATEGORY(lcDotIR, "qt.v4.ir.dot");
Q_LOGGING_CATEGORY(lcVerify, "qt.v4.ir.verify");

Function::Function(QV4::Function *qv4Function)
    : qv4Function(qv4Function)
    , m_graph(Graph::create(this))
    , m_dumper(nullptr)
    , m_nodeInfo(128, nullptr)
{
}

Function::~Function()
{
    delete m_dumper;
}

QString Function::name() const
{
    QString name;
    if (auto n = v4Function()->name())
        name = n->toQString();
    if (name.isEmpty())
        name = QString::asprintf("%p", v4Function());
    auto loc = v4Function()->sourceLocation();
    return name + QStringLiteral(" (%1:%2:%3)").arg(loc.sourceFile, QString::number(loc.line),
                                                    QString::number(loc.column));
}

void Function::dump(const QString &description) const
{
    Dumper::dump(this, description);
}

void Function::dump() const
{
    dump(QStringLiteral("Debug:"));
}

Dumper *Function::dumper() const
{
    if (!m_dumper)
        m_dumper = new Dumper(this);
    return m_dumper;
}

Function::StringId Function::addString(const QString &s)
{
    m_stringPool.push_back(s);
    return m_stringPool.size() - 1;
}

NodeInfo *Function::nodeInfo(Node *n, bool createIfNecessary) const
{
    if (n->id() >= m_nodeInfo.size())
        m_nodeInfo.resize(n->id() * 2, nullptr);

    NodeInfo *&info = m_nodeInfo[n->id()];
    if (info == nullptr && createIfNecessary) {
        info = m_pool.New<NodeInfo>();
        info->setType(n->operation()->type());
    }
    return info;
}

void Function::copyBytecodeOffsets(Node *from, Node *to)
{
    auto toInfo = nodeInfo(to);
    if (auto fromInfo = nodeInfo(from)) {
        toInfo->setBytecodeOffsets(fromInfo->currentInstructionOffset(),
                                   fromInfo->nextInstructionOffset());
    }
}

Dumper::Dumper(const Function *f)
{
    if (!f)
        return;
}

void Dumper::dump(const Function *f, const QString &description)
{
    if (false && lcJsonIR().isDebugEnabled()) {
        Dumper *dumper = f->dumper();

        qCDebug(lcJsonIR).noquote().nospace() << description + QLatin1String(":\n");
        for (const auto &line : dumper->dump(f).split('\n'))
            qCDebug(lcJsonIR).noquote().nospace() << line;
    }

    if (lcDotIR().isDebugEnabled())
        dot(f, description);
}

QByteArray Dumper::dump(const Function *f)
{
    QJsonObject fo;

    {
        QString name;
        if (auto n = f->v4Function()->name())
            name = n->toQString();
        fo[QLatin1String("_searchKey")] = QStringLiteral("function %1").arg(name);
        if (name.isEmpty())
            name = QString::asprintf("%p", f->v4Function());
        fo[QLatin1String("name")] = name;
    }

    auto loc = f->v4Function()->sourceLocation();
    fo[QLatin1String("source")] = loc.sourceFile;
    fo[QLatin1String("line")] = loc.line;
    fo[QLatin1String("column")] = loc.column;

    {
        QJsonArray gn;
        QJsonArray ge;
        NodeCollector nodes(f->graph(), /*collectUses =*/ true);
        nodes.sortById();
        for (Node *n : nodes.reachable()) {
            gn.append(dump(n, f));
            int inputIndex = 0;
            for (Node *input : n->inputs()) {
                QJsonObject edge;
                edge[QLatin1String("from")] = int(input->id());
                edge[QLatin1String("to")] = int(n->id());
                edge[QLatin1String("index")] = inputIndex;
                if (inputIndex < n->operation()->valueInputCount()) {
                    edge[QLatin1String("type")] = QLatin1String("value");
                } else if (inputIndex < n->operation()->valueInputCount()
                           + n->operation()->effectInputCount()) {
                    edge[QLatin1String("type")] = QLatin1String("effect");
                } else {
                    edge[QLatin1String("type")] = QLatin1String("control");
                }
                Q_ASSERT(inputIndex < n->operation()->valueInputCount()
                         + n->operation()->effectInputCount()
                         + n->operation()->controlInputCount());
                ge.append(edge);
                ++inputIndex;
            }
        }
        QJsonObject g;
        g[QLatin1String("nodes")] = gn;
        g[QLatin1String("edges")] = ge;
        fo[QLatin1String("graph")] = g;
    }

    m_doc.setObject(fo);
    return m_doc.toJson(QJsonDocument::Indented);
}

QJsonValue toJSonValue(QV4::Value v)
{
    switch (v.type()) {
    case QV4::Value::Undefined_Type: return QJsonValue(QJsonValue::Undefined);
    case QV4::Value::Null_Type: return QJsonValue(QJsonValue::Null);
    case QV4::Value::Boolean_Type: return QJsonValue(v.booleanValue());
    case QV4::Value::Integer_Type: return QJsonValue(v.int_32());
    case QV4::Value::Managed_Type:
        if (String *s = v.stringValue())
            return QJsonValue(s->toQString());
        else
            return QJsonValue(QLatin1String("<managed>"));
    default: return QJsonValue(v.doubleValue());
    }
}

QJsonValue Dumper::dump(const Node * const node, const Function *f)
{
    QJsonObject n;
    n[QLatin1String("id")] = int(node->id());
    n[QLatin1String("kind")] = node->operation()->debugString();
    switch (node->operation()->kind()) {
    case Meta::Parameter: {
        auto info = ParameterPayload::get(*node->operation());
        n[QLatin1String("name")] = f->string(info->stringId());
        n[QLatin1String("index")] = int(info->parameterIndex());
        break;
    }
    case Meta::Constant: {
        auto info = ConstantPayload::get(*node->operation());
        n[QLatin1String("value")] = toJSonValue(info->value());
        break;
    }
    default:
        break;
    }
    return n;
}

void Dumper::dot(const Function *f, const QString &description)
{
    static const bool skipFramestate = qEnvironmentVariableIsSet("QV4_JIT_DOT_SKIP_FRAMESTATE");

    auto node = [](Node *n) {
        return QStringLiteral("n%1[label=\"%1: %2%3\"];\n").arg(QString::number(n->id()),
                                                                n->operation()->debugString(),
                                                                n->isDead() ? QStringLiteral(" (dead)")
                                                                            : QString());
    };

    Graph *g = f->graph();
    QString out;
    out += QLatin1Char('\n');
    out += QStringLiteral("digraph{root=\"n%1\" label=\"%2\";"
                          "node[shape=rect];"
                          "edge[dir=back fontsize=10];\n")
            .arg(g->startNode()->id())
            .arg(description);
    out += node(g->startNode());
    const bool dumpUses = false; // set to true to see all nodes
    NodeCollector nodes(g, dumpUses, skipFramestate);
    for (Node *n : nodes.reachable()) {
        if (n == g->startNode())
            continue;

        out += node(n);

        unsigned inputIndex = 0;
        for (Node *input : n->inputs()) {
            if (input == nullptr)
                continue;
            out += QStringLiteral("n%2->n%1[style=").arg(QString::number(n->id()),
                                                         QString::number(input->id()));
            if (inputIndex < n->operation()->valueInputCount() ||
                    inputIndex == n->operation()->indexOfFrameStateInput()) {
                out += QStringLiteral("solid headlabel=\"%1\"").arg(inputIndex);
            } else if (inputIndex < unsigned(n->operation()->valueInputCount()
                                             + n->operation()->effectInputCount())) {
                out += QStringLiteral("dotted headlabel=\"%1\"").arg(inputIndex);
            } else {
                out += QStringLiteral("dashed headlabel=\"%1\"").arg(inputIndex);
            }
            out += QStringLiteral("];\n");
            ++inputIndex;
        }
    }
    out += QStringLiteral("}\n");
    qCDebug(lcDotIR).nospace().noquote() << out;

    QFile of(description + QStringLiteral(".dot"));
    of.open(QIODevice::WriteOnly);
    of.write(out.toUtf8());
    of.close();
}

void Function::verify() const
{
#ifndef QT_NO_DEBUG
    unsigned problemsFound = 0;

    auto verifyNodeAgainstOperation = [&problemsFound](const Node *n) {
        const Operation *op = n->operation();
        if (op->totalInputCount() != n->inputCount()) {
            ++problemsFound;
            qCDebug(lcVerify()) << "Node" << n->id() << "has" << n->inputCount()
                                << "inputs, but it's operation" << op->debugString()
                                << "requires" << op->totalInputCount() << "inputs";
        }

        if (n->opcode() == Meta::Phi || n->opcode() == Meta::EffectPhi) {
            if (n->controlInput()->opcode() != Meta::Region) {
                ++problemsFound;
                qCDebug(lcVerify()) << "Control input of phi node" << n->id() << "is not a region";
            }
            if (n->controlInput()->inputCount() + 1 != n->inputCount()) {
                ++problemsFound;
                qCDebug(lcVerify()) << "Control input of phi node" << n->id()
                                    << "has" << n->controlInput()->inputCount()
                                    << "inputs while phi node has" << n->inputCount()
                                    << "inputs";
            }
        }

        //### todo: verify outputs: value outputs are allowed to be unused, but the effect and
        //          control outputs have to be linked up, except:
        //### todo: verify if no use is a nullptr, except for operations that can throw, where the
        //          last one is allowed to be a nullptr when an unwind handler is missing.
    };

    NodeWorkList todo(graph());
    todo.enqueue(graph()->endNode());
    while (Node *n = todo.dequeueNextNodeForVisiting()) {
        todo.enqueueAllInputs(n);
        todo.enqueueAllUses(n);

        verifyNodeAgainstOperation(n);
    }
    //### TODO:
    if (problemsFound != 0) {
        dump(QStringLiteral("Problematic graph"));
        qFatal("Found %u problems during graph verification!", problemsFound);
    }
#endif // QT_NO_xDEBUG
}

QString Type::debugString() const
{
    if (isNone())
        return QStringLiteral("none");
    if (isInvalid())
        return QStringLiteral("invalid");

    QStringList s;
    if (m_t & Bool)
        s += QStringLiteral("boolean");
    if (m_t & Int32)
        s += QStringLiteral("int32");
    if (m_t & Double)
        s += QStringLiteral("double");
    if (m_t & Undefined)
        s += QStringLiteral("undefined");
    if (m_t & Null)
        s += QStringLiteral("null");
    if (m_t & Empty)
        s += QStringLiteral("empty");
    if (m_t & RawPointer)
        s += QStringLiteral("raw pointer");

    return s.join(QLatin1String(" "));
}

} // IR namespace
} // QV4 namespace
QT_END_NAMESPACE