Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qqmljsbasicblocks.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
5#include "qqmljsutils_p.h"
6
7#include <QtQml/private/qv4instr_moth_p.h>
8
10
11using namespace Qt::Literals::StringLiterals;
12
13DEFINE_BOOL_CONFIG_OPTION(qv4DumpBasicBlocks, QV4_DUMP_BASIC_BLOCKS)
14DEFINE_BOOL_CONFIG_OPTION(qv4ValidateBasicBlocks, QV4_VALIDATE_BASIC_BLOCKS)
15
16void QQmlJSBasicBlocks::dumpBasicBlocks()
17{
18 qDebug().noquote() << "=== Basic Blocks for \"%1\""_L1.arg(m_context->name);
19 for (const auto &[blockOffset, block] : m_basicBlocks) {
20 QDebug debug = qDebug().nospace();
21 debug << "Block " << (blockOffset < 0 ? "Function prolog"_L1 : QString::number(blockOffset))
22 << ":\n";
23 debug << " jumpOrigins[" << block.jumpOrigins.size() << "]: ";
24 for (auto origin : block.jumpOrigins) {
25 debug << origin << ", ";
26 }
27 debug << "\n readRegisters[" << block.readRegisters.size() << "]: ";
28 for (auto reg : block.readRegisters) {
29 debug << reg << ", ";
30 }
31 debug << "\n readTypes[" << block.readTypes.size() << "]: ";
32 for (const auto &type : block.readTypes) {
33 debug << type->augmentedInternalName() << ", ";
34 }
35 debug << "\n jumpTarget: " << block.jumpTarget;
36 debug << "\n jumpIsUnConditional: " << block.jumpIsUnconditional;
37 debug << "\n isReturnBlock: " << block.isReturnBlock;
38 debug << "\n isThrowBlock: " << block.isThrowBlock;
39 }
40 qDebug() << "\n";
41}
42
43void QQmlJSBasicBlocks::dumpDOTGraph()
44{
47 s << "=== Basic Blocks Graph in DOT format for \"%1\" (spaces are encoded as"
48 " &#160; to preserve formatting)\n"_L1.arg(m_context->name);
49 s << "digraph BasicBlocks {\n"_L1;
50
51 QFlatMap<int, BasicBlock> blocks{ m_basicBlocks };
52 for (const auto &[blockOffset, block] : blocks) {
53 for (int originOffset : block.jumpOrigins) {
54 const auto originBlockIt = basicBlockForInstruction(blocks, originOffset);
55 const auto isBackEdge = originOffset > blockOffset && originBlockIt->second.jumpIsUnconditional;
56 s << " %1 -> %2%3\n"_L1.arg(QString::number(originBlockIt.key()))
57 .arg(QString::number(blockOffset))
58 .arg(isBackEdge ? " [color=blue]"_L1 : ""_L1);
59 }
60 }
61
62 for (const auto &[blockOffset, block] : blocks) {
63 if (blockOffset < 0) {
64 s << " %1 [shape=record, fontname=\"Monospace\", label=\"Function Prolog\"]\n"_L1
65 .arg(QString::number(blockOffset));
66 continue;
67 }
68
69 auto nextBlockIt = blocks.lower_bound(blockOffset + 1);
70 int nextBlockOffset = nextBlockIt == blocks.end() ? m_context->code.size() : nextBlockIt->first;
72 m_context->code.constData(), m_context->code.size(), m_context->locals.size(),
73 m_context->formals->length(), blockOffset, nextBlockOffset - 1,
75 dump = dump.replace(" "_L1, "&#160;"_L1); // prevent collapse of extra whitespace for formatting
76 dump = dump.replace("\n"_L1, "\\l"_L1); // new line + left aligned
77 s << " %1 [shape=record, fontname=\"Monospace\", label=\"{Block %1: | %2}\"]\n"_L1
78 .arg(QString::number(blockOffset))
79 .arg(dump);
80 }
81 s << "}\n"_L1;
82
83 // Have unique names to prevent overwriting of functions with the same name (eg. anonymous functions).
84 static int functionCount = 0;
85 static const auto dumpFolderPath = qEnvironmentVariable("QV4_DUMP_BASIC_BLOCKS");
86
87 QString expressionName = m_context->name == ""_L1
88 ? "anonymous"_L1
89 : QString(m_context->name).replace(" "_L1, "_"_L1);
90 QString fileName = "function"_L1 + QString::number(functionCount++) + "_"_L1 + expressionName + ".gv"_L1;
91 QFile dumpFile(dumpFolderPath + (dumpFolderPath.endsWith("/"_L1) ? ""_L1 : "/"_L1) + fileName);
92
93 if (dumpFolderPath == "-"_L1 || dumpFolderPath == "1"_L1 || dumpFolderPath == "true"_L1) {
94 qDebug().noquote() << output;
95 } else {
96 if (!dumpFile.open(QIODeviceBase::Truncate | QIODevice::WriteOnly)) {
97 qDebug() << "Error: Could not open file to dump the basic blocks into";
98 } else {
99 dumpFile.write(("//"_L1 + output).toLatin1().toStdString().c_str());
100 dumpFile.close();
101 }
102 }
103}
104
106QQmlJSBasicBlocks::run(const Function *function, QQmlJSAotCompiler::Flags compileFlags,
107 bool &basicBlocksValidationFailed)
108{
109 basicBlocksValidationFailed = false;
110
112
113 for (int i = 0, end = function->argumentTypes.size(); i != end; ++i) {
114 InstructionAnnotation annotation;
115 annotation.changedRegisterIndex = FirstArgument + i;
116 annotation.changedRegister = function->argumentTypes[i];
117 m_annotations[-annotation.changedRegisterIndex] = annotation;
118 }
119
120 for (int i = 0, end = function->registerTypes.size(); i != end; ++i) {
121 InstructionAnnotation annotation;
123 annotation.changedRegister = function->registerTypes[i];
124 m_annotations[-annotation.changedRegisterIndex] = annotation;
125 }
126
127 // Insert the function prolog block followed by the first "real" block.
129 BasicBlock zeroBlock;
130 zeroBlock.jumpOrigins.append(m_basicBlocks.begin().key());
131 m_basicBlocks.insert(0, zeroBlock);
132
133 const QByteArray byteCode = function->code;
134 decode(byteCode.constData(), static_cast<uint>(byteCode.size()));
135 if (m_hadBackJumps) {
136 // We may have missed some connections between basic blocks if there were back jumps.
137 // Fill them in via a second pass.
138
139 // We also need to re-calculate the jump targets then because the basic block boundaries
140 // may have shifted.
141 for (auto it = m_basicBlocks.begin(), end = m_basicBlocks.end(); it != end; ++it) {
142 it->second.jumpTarget = -1;
143 it->second.jumpIsUnconditional = false;
144 }
145
146 m_skipUntilNextLabel = false;
147
148 reset();
149 decode(byteCode.constData(), static_cast<uint>(byteCode.size()));
150 for (auto it = m_basicBlocks.begin(), end = m_basicBlocks.end(); it != end; ++it)
151 QQmlJSUtils::deduplicate(it->second.jumpOrigins);
152 }
153
154 if (compileFlags.testFlag(QQmlJSAotCompiler::ValidateBasicBlocks) || qv4ValidateBasicBlocks()) {
155 if (auto validationResult = basicBlocksValidation(); !validationResult.success) {
156 qDebug() << "Basic blocks validation failed: %1."_L1.arg(validationResult.errorMessage);
157 basicBlocksValidationFailed = true;
158 }
159 }
160
161 if (qv4DumpBasicBlocks()) {
162 dumpBasicBlocks();
163 dumpDOTGraph();
164 }
165
166 return { std::move(m_basicBlocks), std::move(m_annotations) };
167}
168
170{
172 if (it != m_basicBlocks.end()) {
173 m_skipUntilNextLabel = false;
174 } else if (m_skipUntilNextLabel && !instructionManipulatesContext(type)) {
175 return SkipInstruction;
176 }
177
178 return ProcessInstruction;
179}
180
182{
183 if (m_skipUntilNextLabel)
184 return;
186 if (it != m_basicBlocks.end())
187 it->second.jumpOrigins.append(currentInstructionOffset());
188}
189
191{
192 processJump(offset, Unconditional);
193}
194
196{
197 processJump(offset, Conditional);
198}
199
201{
202 processJump(offset, Conditional);
203}
204
206{
207 processJump(offset, Conditional);
208}
209
211{
212 processJump(offset, Conditional);
213}
214
216{
218 processJump(offset, Conditional);
219}
220
222{
224 processJump(offset, Conditional);
225}
226
228{
230 currentBlock.value().isReturnBlock = true;
231 m_skipUntilNextLabel = true;
232}
233
235{
237 currentBlock.value().isThrowBlock = true;
238 m_skipUntilNextLabel = true;
239}
240
242{
243 if (argc == 0)
244 return; // empty array/list, nothing to do
245
246 m_objectAndArrayDefinitions.append({
247 currentInstructionOffset(), ObjectOrArrayDefinition::ArrayClassId, argc, argv
248 });
249}
250
251void QQmlJSBasicBlocks::generate_DefineObjectLiteral(int internalClassId, int argc, int argv)
252{
253 if (argc == 0)
254 return;
255
256 m_objectAndArrayDefinitions.append({ currentInstructionOffset(), internalClassId, argc, argv });
257}
258
259void QQmlJSBasicBlocks::generate_Construct(int func, int argc, int argv)
260{
262 if (argc == 0)
263 return; // empty array/list, nothing to do
264
265 m_objectAndArrayDefinitions.append({
267 argc == 1
268 ? ObjectOrArrayDefinition::ArrayConstruct1ArgId
269 : ObjectOrArrayDefinition::ArrayClassId,
270 argc,
271 argv
272 });
273}
274
275void QQmlJSBasicBlocks::processJump(int offset, JumpMode mode)
276{
277 if (offset < 0)
278 m_hadBackJumps = true;
279 const int jumpTarget = absoluteOffset(offset);
282 currentBlock->second.jumpTarget = jumpTarget;
283 currentBlock->second.jumpIsUnconditional = (mode == Unconditional);
284 m_basicBlocks[jumpTarget].jumpOrigins.append(currentInstructionOffset());
285 if (mode == Unconditional)
286 m_skipUntilNextLabel = true;
287 else
289}
290
291QQmlJSCompilePass::BasicBlocks::iterator QQmlJSBasicBlocks::basicBlockForInstruction(
292 QFlatMap<int, BasicBlock> &container, int instructionOffset)
293{
294 auto block = container.lower_bound(instructionOffset);
295 if (block == container.end() || block->first != instructionOffset)
296 --block;
297 return block;
298}
299
300QQmlJSCompilePass::BasicBlocks::const_iterator QQmlJSBasicBlocks::basicBlockForInstruction(
301 const BasicBlocks &container, int instructionOffset)
302{
303 return basicBlockForInstruction(const_cast<BasicBlocks &>(container), instructionOffset);
304}
305
307{
308 if (m_basicBlocks.empty())
309 return {};
310
311 const QFlatMap<int, BasicBlock> blocks{ m_basicBlocks };
312 QList<QFlatMap<int, BasicBlock>::const_iterator> returnOrThrowBlocks;
313 for (auto it = blocks.cbegin(); it != blocks.cend(); ++it) {
314 if (it.value().isReturnBlock || it.value().isThrowBlock)
315 returnOrThrowBlocks.append(it);
316 }
317
318 // 1. Return blocks and throw blocks must not have a jump target
319 for (const auto &it : returnOrThrowBlocks) {
320 if (it.value().jumpTarget != -1)
321 return { false, "Return or throw block jumps to somewhere"_L1 };
322 }
323
324 // 2. The basic blocks graph must be connected.
325 QSet<int> visitedBlockOffsets;
326 QList<QFlatMap<int, BasicBlock>::const_iterator> toVisit;
327 toVisit.append(returnOrThrowBlocks);
328
329 while (!toVisit.empty()) {
330 const auto &[offset, block] = *toVisit.takeLast();
331 visitedBlockOffsets.insert(offset);
332 for (int originOffset : block.jumpOrigins) {
333 const auto originBlock = basicBlockForInstruction(blocks, originOffset);
334 if (visitedBlockOffsets.find(originBlock.key()) == visitedBlockOffsets.end()
335 && !toVisit.contains(originBlock))
336 toVisit.append(originBlock);
337 }
338 }
339
340 if (visitedBlockOffsets.size() != blocks.size())
341 return { false, "Basic blocks graph is not fully connected"_L1 };
342
343 // 3. A block's jump target must be the first offset of a block.
344 for (const auto &[blockOffset, block] : blocks) {
345 auto target = block.jumpTarget;
346 if (target != -1 && blocks.find(target) == blocks.end())
347 return { false, "Invalid jump; target is not the start of a block"_L1 };
348 }
349
350 return {};
351}
352
\inmodule QtCore
Definition qbytearray.h:57
qsizetype size() const noexcept
Returns the number of bytes in this byte array.
Definition qbytearray.h:494
const char * constData() const noexcept
Returns a pointer to the const data stored in the byte array.
Definition qbytearray.h:124
\inmodule QtCore
\inmodule QtCore
Definition qfile.h:93
bool isEmpty() const noexcept
Definition qflatmap_p.h:579
bool empty() const noexcept
Definition qflatmap_p.h:580
std::pair< iterator, bool > insert_or_assign(const Key &key, M &&obj)
Definition qflatmap_p.h:724
iterator begin()
Definition qflatmap_p.h:769
iterator end()
Definition qflatmap_p.h:773
iterator find(const Key &key)
Definition qflatmap_p.h:816
std::pair< iterator, bool > insert(const Key &key, const T &value)
Definition qflatmap_p.h:678
void append(parameter_type t)
Definition qlist.h:458
void endInstruction(QV4::Moth::Instr::Type type) override
void generate_JumpNoException(int offset) override
BasicBlocksValidationResult basicBlocksValidation()
QV4::Moth::ByteCodeHandler::Verdict startInstruction(QV4::Moth::Instr::Type type) override
void generate_GetOptionalLookup(int index, int offset) override
void generate_DefineObjectLiteral(int internalClassId, int argc, int args) override
QQmlJSCompilePass::BlocksAndAnnotations run(const Function *function, QQmlJSAotCompiler::Flags compileFlags, bool &basicBlocksValidationFailed)
void generate_Ret() override
void generate_JumpNotUndefined(int offset) override
void generate_Jump(int offset) override
static BasicBlocks::iterator basicBlockForInstruction(QFlatMap< int, BasicBlock > &container, int instructionOffset)
void generate_JumpFalse(int offset) override
void generate_IteratorNext(int value, int offset) override
void generate_ThrowException() override
void generate_DefineArray(int argc, int argv) override
void generate_JumpTrue(int offset) override
void generate_Construct(int func, int argc, int argv) override
static bool instructionManipulatesContext(QV4::Moth::Instr::Type type)
const Function * m_function
InstructionAnnotations m_annotations
QFlatMap< int, BasicBlock > BasicBlocks
const_iterator cend() const noexcept
Definition qset.h:142
const_iterator cbegin() const noexcept
Definition qset.h:138
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
QString & replace(qsizetype i, qsizetype len, QChar after)
Definition qstring.cpp:3824
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qstring.cpp:8084
\inmodule QtCore
int absoluteOffset(int relativeOffset) const
QSet< QString >::iterator it
Combined button and popup list for selecting options.
QString dumpBytecode(const char *code, int len, int nLocals, int nFormals, int, const QVector< CompiledData::CodeOffsetToLineAndStatement > &lineAndStatementNumberMapping)
DBusConnection const char DBusError DBusBusType DBusError return DBusConnection DBusHandleMessageFunction function
EGLOutputLayerEXT EGLint EGLAttrib value
[5]
#define qDebug
[1]
Definition qlogging.h:164
GLenum mode
GLuint index
[2]
GLuint GLuint end
GLenum type
GLenum target
GLenum GLuint GLintptr offset
GLdouble s
[6]
Definition qopenglext.h:235
GLenum func
Definition qopenglext.h:663
#define DEFINE_BOOL_CONFIG_OPTION(name, var)
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
static QString dump(const QByteArray &)
QString qEnvironmentVariable(const char *varName, const QString &defaultValue)
#define Q_UNUSED(x)
unsigned int uint
Definition qtypes.h:34
#define decode(x)
QT_BEGIN_NAMESPACE typedef uchar * output
static void deduplicate(Container &container)
QQmlJS::AST::FormalParameterList * formals
QVector< CompiledData::CodeOffsetToLineAndStatement > lineAndStatementNumberMapping