Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmljstypepropagator.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3// Qt-Security score:significant
4
7
9
10#include <private/qv4compilerscanfunctions_p.h>
11
12#include <QtQmlCompiler/private/qqmlsasourcelocation_p.h>
13
15
16using namespace Qt::StringLiterals;
17
18/*!
19 * \internal
20 * \class QQmlJSTypePropagator
21 *
22 * QQmlJSTypePropagator is the initial pass that performs the type inference and
23 * annotates every register in use at any instruction with the possible types it
24 * may hold. This includes information on how and in what scope the values are
25 * retrieved. These annotations may be used by further compile passes for
26 * refinement or code generation.
27 */
28
29QQmlJSCompilePass::BlocksAndAnnotations QQmlJSTypePropagator::run(const Function *function)
30{
31 m_function = function;
32 m_returnType = m_function->returnType;
33
34 // We are the only pass that merges register contents. See QQmlJSTypeResolver::m_mergeCache.
35 m_typeResolver->clearMergeCache();
36
37 // We cannot assume anything about how a script string will be used
38 if (m_returnType.containedType() == m_typeResolver->qQmlScriptStringType())
39 return {};
40
41 do {
42 // Reset the error if we need to do another pass
43 if (m_state.needsMorePasses)
44 m_logger->rollback();
45
46 m_logger->startTransaction();
47
48 m_prevStateAnnotations = m_state.annotations;
49 m_state = PassState();
50 m_state.annotations = m_annotations;
51 m_state.State::operator=(initialState(m_function));
52
53 reset();
54 decode(m_function->code.constData(), static_cast<uint>(m_function->code.size()));
55
56 // If we have found unresolved backwards jumps, we need to start over with a fresh state.
57 // Mind that m_jumpOriginRegisterStateByTargetInstructionOffset is retained in that case.
58 // This means that we won't start over for the same reason again.
59 } while (m_state.needsMorePasses);
60
61 m_logger->commit();
62 return { std::move(m_basicBlocks), std::move(m_state.annotations) };
63}
64
65#define INSTR_PROLOGUE_NOT_IMPLEMENTED()
66 addError(u"Instruction \"%1\" not implemented"_s.arg(QString::fromUtf8(__func__)));
67 return;
68
69#define INSTR_PROLOGUE_NOT_IMPLEMENTED_POPULATES_ACC()
70 addError(u"Instruction \"%1\" not implemented"_s.arg(QString::fromUtf8(__func__)));
71 setVarAccumulatorAndError(); /* Keep sane state after error */
72 return;
73
74#define INSTR_PROLOGUE_NOT_IMPLEMENTED_IGNORE()
75 m_logger->log(u"Instruction \"%1\" not implemented"_s.arg(QString::fromUtf8(__func__)),
76 qmlCompiler, QQmlJS::SourceLocation());
77 return;
78
79void QQmlJSTypePropagator::generate_Ret()
80{
81 if (m_function->isSignalHandler) {
82 // Signal handlers cannot return anything.
83 } else if (m_state.accumulatorIn().contains(m_typeResolver->voidType())) {
84 // You can always return undefined.
85 } else if (!m_returnType.isValid() && m_state.accumulatorIn().isValid()) {
86 addError(u"function without return type annotation returns %1. This may prevent proper "_s
87 u"compilation to Cpp."_s.arg(m_state.accumulatorIn().descriptiveName()));
88 return;
89 } else if (!canConvertFromTo(m_state.accumulatorIn(), m_returnType)) {
90 addError(u"cannot convert from %1 to %2"_s
91 .arg(m_state.accumulatorIn().descriptiveName(),
92 m_returnType.descriptiveName()));
93 return;
94 }
95
96 if (m_returnType.isValid()) {
97 // We need to preserve any possible undefined value as that resets the property.
98 if (m_typeResolver->canHoldUndefined(m_state.accumulatorIn()))
99 addReadAccumulator();
100 else
101 addReadAccumulator(m_returnType);
102 }
103
104 m_state.setHasInternalSideEffects();
105 m_state.skipInstructionsUntilNextJumpTarget = true;
106}
107
108void QQmlJSTypePropagator::generate_Debug()
109{
111}
112
113void QQmlJSTypePropagator::generate_LoadConst(int index)
114{
115 auto encodedConst = m_jsUnitGenerator->constant(index);
116 setAccumulator(m_typeResolver->literalType(m_typeResolver->typeForConst(encodedConst)));
117}
118
119void QQmlJSTypePropagator::generate_LoadZero()
120{
121 setAccumulator(m_typeResolver->literalType(m_typeResolver->int32Type()));
122}
123
124void QQmlJSTypePropagator::generate_LoadTrue()
125{
126 setAccumulator(m_typeResolver->literalType(m_typeResolver->boolType()));
127}
128
129void QQmlJSTypePropagator::generate_LoadFalse()
130{
131 setAccumulator(m_typeResolver->literalType(m_typeResolver->boolType()));
132}
133
134void QQmlJSTypePropagator::generate_LoadNull()
135{
136 setAccumulator(m_typeResolver->literalType(m_typeResolver->nullType()));
137}
138
139void QQmlJSTypePropagator::generate_LoadUndefined()
140{
141 setAccumulator(m_typeResolver->literalType(m_typeResolver->voidType()));
142}
143
144void QQmlJSTypePropagator::generate_LoadInt(int)
145{
146 setAccumulator(m_typeResolver->literalType(m_typeResolver->int32Type()));
147}
148
149void QQmlJSTypePropagator::generate_MoveConst(int constIndex, int destTemp)
150{
151 auto encodedConst = m_jsUnitGenerator->constant(constIndex);
152 setRegister(destTemp, m_typeResolver->literalType(m_typeResolver->typeForConst(encodedConst)));
153}
154
155void QQmlJSTypePropagator::generate_LoadReg(int reg)
156{
157 // Do not re-track the register. We're not manipulating it.
158 m_state.setIsRename(true);
159 const QQmlJSRegisterContent content = checkedInputRegister(reg);
160 m_state.addReadRegister(reg, content);
161 m_state.setRegister(Accumulator, content);
162}
163
164void QQmlJSTypePropagator::generate_StoreReg(int reg)
165{
166 // Do not re-track the register. We're not manipulating it.
167 m_state.setIsRename(true);
168 m_state.addReadAccumulator(m_state.accumulatorIn());
169 m_state.setRegister(reg, m_state.accumulatorIn());
170}
171
172void QQmlJSTypePropagator::generate_MoveReg(int srcReg, int destReg)
173{
174 Q_ASSERT(destReg != InvalidRegister);
175 // Do not re-track the register. We're not manipulating it.
176 m_state.setIsRename(true);
177 const QQmlJSRegisterContent content = checkedInputRegister(srcReg);
178 m_state.addReadRegister(srcReg, content);
179 m_state.setRegister(destReg, content);
180}
181
182void QQmlJSTypePropagator::generate_LoadImport(int index)
183{
184 Q_UNUSED(index)
186}
187
188void QQmlJSTypePropagator::generate_LoadLocal(int index)
189{
190 // TODO: In order to accurately track locals we'd need to track JavaScript contexts first.
191 // This could be done by populating the initial JS context and implementing the various
192 // Push and Pop operations. For now, this is pretty barren.
193
194 QQmlJSMetaProperty local;
195 local.setType(m_typeResolver->jsValueType());
196 local.setIndex(index);
197
198 setAccumulator(m_pool->createProperty(
199 local, QQmlJSRegisterContent::InvalidLookupIndex,
200 QQmlJSRegisterContent::InvalidLookupIndex,
201 QQmlJSRegisterContent::Property, QQmlJSRegisterContent()));
202}
203
204void QQmlJSTypePropagator::generate_StoreLocal(int index)
205{
206 Q_UNUSED(index)
208}
209
210void QQmlJSTypePropagator::generate_LoadScopedLocal(int scope, int index)
211{
212 Q_UNUSED(scope)
213 Q_UNUSED(index)
215}
216
217void QQmlJSTypePropagator::generate_StoreScopedLocal(int scope, int index)
218{
219 Q_UNUSED(scope)
220 Q_UNUSED(index)
222}
223
224void QQmlJSTypePropagator::generate_LoadRuntimeString(int stringId)
225{
226 Q_UNUSED(stringId)
227 setAccumulator(m_typeResolver->literalType(m_typeResolver->stringType()));
228}
229
230void QQmlJSTypePropagator::generate_MoveRegExp(int regExpId, int destReg)
231{
232 Q_UNUSED(regExpId)
233 m_state.setRegister(destReg, m_typeResolver->literalType(m_typeResolver->regexpType()));
234}
235
236void QQmlJSTypePropagator::generate_LoadClosure(int value)
237{
238 Q_UNUSED(value)
239 // TODO: Check the function at index and see whether it's a generator to return another type
240 // instead.
241 setAccumulator(m_typeResolver->literalType(m_typeResolver->functionType()));
242}
243
244void QQmlJSTypePropagator::generate_LoadName(int nameIndex)
245{
246 const QString name = m_jsUnitGenerator->stringForIndex(nameIndex);
247 setAccumulator(m_typeResolver->scopedType(m_function->qmlScope, name));
248 if (!m_state.accumulatorOut().isValid()) {
249 addError(u"Cannot find name "_s + name);
250 setVarAccumulatorAndError();
251 }
252}
253
254void QQmlJSTypePropagator::generate_LoadGlobalLookup(int index)
255{
256 generate_LoadName(m_jsUnitGenerator->lookupNameIndex(index));
257}
258
259void QQmlJSTypePropagator::handleUnqualifiedAccess(const QString &name, bool isMethod) const
260{
261 Q_UNUSED(name);
262 Q_UNUSED(isMethod);
263}
264
265void QQmlJSTypePropagator::handleUnqualifiedAccessAndContextProperties(
266 const QString &name, bool isMethod) const
267{
268 Q_UNUSED(name);
269 Q_UNUSED(isMethod);
270}
271
272void QQmlJSTypePropagator::checkDeprecated(QQmlJSScope::ConstPtr scope, const QString &name,
273 bool isMethod) const
274{
275 Q_UNUSED(scope);
276 Q_UNUSED(name);
277 Q_UNUSED(isMethod);
278}
279
280bool QQmlJSTypePropagator::isCallingProperty(QQmlJSScope::ConstPtr scope, const QString &name) const
281{
282 const auto property = scope->property(name);
283 return property.isValid();
284}
285
286void QQmlJSTypePropagator::generate_LoadQmlContextPropertyLookup(int index)
287{
288 // LoadQmlContextPropertyLookup does not use accumulatorIn. It always refers to the scope.
289 // Any import namespaces etc. are handled via LoadProperty or GetLookup.
290
291 const int nameIndex = m_jsUnitGenerator->lookupNameIndex(index);
292 const QString name = m_jsUnitGenerator->stringForIndex(nameIndex);
293
294 setAccumulator(m_typeResolver->scopedType(m_function->qmlScope, name, index));
295
296 if (!m_state.accumulatorOut().isValid() && m_typeResolver->isPrefix(name)) {
297 setAccumulator(m_pool->createImportNamespace(
298 nameIndex, m_typeResolver->voidType(), QQmlJSRegisterContent::ModulePrefix,
299 m_function->qmlScope));
300 return;
301 }
302
303 checkDeprecated(m_function->qmlScope.containedType(), name, false);
304
305 const QQmlJSRegisterContent accumulatorOut = m_state.accumulatorOut();
306
307 if (!accumulatorOut.isValid()) {
308 addError(u"Cannot access value for name "_s + name);
309 handleUnqualifiedAccessAndContextProperties(name, false);
310 setVarAccumulatorAndError();
311 return;
312 }
313
314 if (isQmlContextObject(accumulatorOut.scope()))
315 handleUnqualifiedAccessAndContextProperties(name, false);
316
317 const QQmlJSScope::ConstPtr retrieved
318 = m_typeResolver->genericType(accumulatorOut.containedType());
319
320 if (retrieved.isNull()) {
321 // It should really be valid.
322 // We get the generic type from aotContext->loadQmlContextPropertyIdLookup().
323 addError(u"Cannot determine generic type for "_s + name);
324 return;
325 }
326
327 if (accumulatorOut.variant() == QQmlJSRegisterContent::ObjectById
328 && !retrieved->isReferenceType()) {
329 addError(u"Cannot retrieve a non-object type by ID: "_s + name);
330 return;
331 }
332}
333
334/*!
335 \internal
336 As far as type propagation is involved, StoreNameSloppy and
337 StoreNameStrict are completely the same
338 StoreNameStrict is rejecting a few writes (where the variable was not
339 defined before) that would work in a sloppy context in JS, but the
340 compiler would always reject this. And for type propagation, this does
341 not matter at all.
342 \a nameIndex is the index in the string table corresponding to
343 the name which we are storing
344 */
345void QQmlJSTypePropagator::generate_StoreNameCommon(int nameIndex)
346{
347 const QString name = m_jsUnitGenerator->stringForIndex(nameIndex);
348 const QQmlJSRegisterContent type = m_typeResolver->scopedType(m_function->qmlScope, name);
349 const QQmlJSRegisterContent in = m_state.accumulatorIn();
350
351 if (!type.isValid()) {
352 handleUnqualifiedAccess(name, false);
353 addError(u"Cannot find name "_s + name);
354 return;
355 }
356
357 if (isQmlContextObject(type.scope()))
358 handleUnqualifiedAccess(name, false);
359
360 if (!type.isProperty()) {
361 QString message = type.isMethod() ? u"Cannot assign to method %1"_s
362 : u"Cannot assign to non-property %1"_s;
363 // The interpreter treats methods as read-only properties in its error messages
364 // and we lack a better fitting category. We might want to revisit this later.
365 m_logger->log(message.arg(name), qmlReadOnlyProperty,
366 currentSourceLocation());
367 addError(u"Cannot assign to non-property "_s + name);
368 return;
369 }
370
371 if (!type.isWritable() && !type.isList()) {
372 addError(u"Can't assign to read-only property %1"_s.arg(name));
373
374 m_logger->log(u"Cannot assign to read-only property %1"_s.arg(name), qmlReadOnlyProperty,
375 currentSourceLocation());
376
377 return;
378 }
379
380 if (!canConvertFromTo(in, type)) {
381 addError(u"cannot convert from %1 to %2"_s
382 .arg(in.descriptiveName(), type.descriptiveName()));
383 }
384
385 if (m_typeResolver->canHoldUndefined(in) && !m_typeResolver->canHoldUndefined(type)) {
386 if (in.contains(m_typeResolver->voidType()))
387 addReadAccumulator(m_typeResolver->varType());
388 else
389 addReadAccumulator();
390 } else {
391 addReadAccumulator(type);
392 }
393
394 m_state.setHasExternalSideEffects();
395}
396
397void QQmlJSTypePropagator::generate_StoreNameSloppy(int nameIndex)
398{
399 return generate_StoreNameCommon(nameIndex);
400}
401
402void QQmlJSTypePropagator::generate_StoreNameStrict(int name)
403{
404 return generate_StoreNameCommon(name);
405}
406
407bool QQmlJSTypePropagator::checkForEnumProblems(
408 QQmlJSRegisterContent base, const QString &propertyName)
409{
410 if (base.isEnumeration()) {
411 const auto metaEn = base.enumeration();
412 if (!metaEn.hasKey(propertyName)) {
413 addError(u"\"%1\" is not an entry of enum \"%2\"."_s
414 .arg(propertyName, metaEn.name()));
415 return true;
416 }
417 }
418
419 return false;
420}
421
422void QQmlJSTypePropagator::generate_LoadElement(int base)
423{
424 const QQmlJSRegisterContent in = m_state.accumulatorIn();
425 const QQmlJSRegisterContent baseRegister = m_state.registers[base].content;
426
427 const auto fallback = [&]() {
428 const QQmlJSScope::ConstPtr jsValue = m_typeResolver->jsValueType();
429
430 addReadAccumulator(jsValue);
431 addReadRegister(base, jsValue);
432
433 QQmlJSMetaProperty property;
434 property.setPropertyName(u"[]"_s);
435 property.setTypeName(jsValue->internalName());
436 property.setType(jsValue);
437
438 setAccumulator(m_pool->createProperty(
439 property, QQmlJSRegisterContent::InvalidLookupIndex,
440 QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::ListValue,
441 m_typeResolver->convert(m_typeResolver->elementType(baseRegister), jsValue)));
442 };
443
444 if (baseRegister.isList()) {
445 addReadRegister(base, m_typeResolver->arrayPrototype());
446 } else if (baseRegister.contains(m_typeResolver->stringType())) {
447 addReadRegister(base, m_typeResolver->stringType());
448 } else {
449 fallback();
450 return;
451 }
452
453 if (m_typeResolver->isNumeric(in)) {
454 const auto contained = in.containedType();
455 if (m_typeResolver->isSignedInteger(contained))
456 addReadAccumulator(m_typeResolver->sizeType());
457 else if (m_typeResolver->isUnsignedInteger(contained))
458 addReadAccumulator(m_typeResolver->uint32Type());
459 else
460 addReadAccumulator(m_typeResolver->realType());
461 } else if (m_typeResolver->isNumeric(m_typeResolver->extractNonVoidFromOptionalType(in))) {
462 addReadAccumulator();
463 } else {
464 fallback();
465 return;
466 }
467
468 // We can end up with undefined.
469 setAccumulator(m_typeResolver->merge(
470 m_typeResolver->elementType(baseRegister),
471 m_typeResolver->literalType(m_typeResolver->voidType())));
472}
473
474void QQmlJSTypePropagator::generate_StoreElement(int base, int index)
475{
476 const QQmlJSRegisterContent baseRegister = m_state.registers[base].content;
477 const QQmlJSRegisterContent indexRegister = checkedInputRegister(index);
478
479 if (!baseRegister.isList()
480 || !m_typeResolver->isNumeric(indexRegister)) {
481 const auto jsValue = m_typeResolver->jsValueType();
482 addReadAccumulator(jsValue);
483 addReadRegister(base, jsValue);
484 addReadRegister(index, jsValue);
485
486 // Writing to a JS array can have side effects all over the place since it's
487 // passed by reference.
488 m_state.setHasExternalSideEffects();
489 return;
490 }
491
492 const auto contained = indexRegister.containedType();
493 if (m_typeResolver->isSignedInteger(contained))
494 addReadRegister(index, m_typeResolver->int32Type());
495 else if (m_typeResolver->isUnsignedInteger(contained))
496 addReadRegister(index, m_typeResolver->uint32Type());
497 else
498 addReadRegister(index, m_typeResolver->realType());
499
500 addReadRegister(base, m_typeResolver->arrayPrototype());
501 addReadAccumulator(m_typeResolver->elementType(baseRegister));
502
503 // If we're writing a QQmlListProperty backed by a container somewhere else,
504 // that has side effects.
505 // If we're writing to a list retrieved from a property, that _should_ have side effects,
506 // but currently the QML engine doesn't implement them.
507 // TODO: Figure out the above and accurately set the flag.
508 m_state.setHasExternalSideEffects();
509}
510
511bool QQmlJSTypePropagator::handleImportNamespaceLookup(const QString &propertyName)
512{
513 const QQmlJSRegisterContent accumulatorIn = m_state.accumulatorIn();
514
515 if (m_typeResolver->isPrefix(propertyName)) {
516 Q_ASSERT(accumulatorIn.isValid());
517
518 if (!accumulatorIn.containedType()->isReferenceType()) {
519 setVarAccumulatorAndError();
520 return true;
521 }
522
523 addReadAccumulator();
524 setAccumulator(m_pool->createImportNamespace(
525 m_jsUnitGenerator->getStringId(propertyName),
526 accumulatorIn.containedType(),
527 QQmlJSRegisterContent::ModulePrefix,
528 accumulatorIn));
529 return true;
530 }
531
532 return false;
533}
534
535void QQmlJSTypePropagator::handleLookupError(const QString &propertyName)
536{
537 const QQmlJSRegisterContent accumulatorIn = m_state.accumulatorIn();
538
539 setVarAccumulatorAndError();
540 if (checkForEnumProblems(accumulatorIn, propertyName))
541 return;
542
543 addError(u"Cannot load property %1 from %2."_s
544 .arg(propertyName, accumulatorIn.descriptiveName()));
545}
546
547void QQmlJSTypePropagator::propagatePropertyLookup(const QString &propertyName, int lookupIndex)
548{
549 const QQmlJSRegisterContent accumulatorIn = m_state.accumulatorIn();
550 setAccumulator(
551 m_typeResolver->memberType(
552 accumulatorIn,
553 accumulatorIn.isImportNamespace()
554 ? m_jsUnitGenerator->stringForIndex(accumulatorIn.importNamespace())
555 + u'.' + propertyName
556 : propertyName, lookupIndex));
557
558 if (!m_state.accumulatorOut().isValid() && handleImportNamespaceLookup(propertyName))
559 return;
560
561 if (m_state.accumulatorOut().variant() == QQmlJSRegisterContent::Singleton
562 && accumulatorIn.variant() == QQmlJSRegisterContent::ModulePrefix
563 && !isQmlScopeObject(accumulatorIn.scope())) {
564 m_logger->log(
565 u"Cannot access singleton as a property of an object. Did you want to access an attached object?"_s,
566 qmlAccessSingleton, currentSourceLocation());
567 setAccumulator(QQmlJSRegisterContent());
568 } else if (m_state.accumulatorOut().isEnumeration()) {
569 switch (accumulatorIn.variant()) {
570 case QQmlJSRegisterContent::MetaType:
571 case QQmlJSRegisterContent::Attachment:
572 case QQmlJSRegisterContent::Enum:
573 case QQmlJSRegisterContent::ModulePrefix:
574 case QQmlJSRegisterContent::Singleton:
575 break; // OK, can look up enums on that thing
576 default:
577 setAccumulator(QQmlJSRegisterContent());
578 }
579 }
580
581 if (m_state.instructionHasError || !m_state.accumulatorOut().isValid()) {
582 handleLookupError(propertyName);
583 return;
584 }
585
586 if (m_state.accumulatorOut().isMethod() && m_state.accumulatorOut().method().size() != 1) {
587 addError(u"Cannot determine overloaded method on loadProperty"_s);
588 return;
589 }
590
591 if (m_state.accumulatorOut().isProperty()) {
592 const QQmlJSScope::ConstPtr mathObject
593 = m_typeResolver->jsGlobalObject()->property(u"Math"_s).type();
594 if (accumulatorIn.contains(mathObject)) {
595 QQmlJSMetaProperty prop;
596 prop.setPropertyName(propertyName);
597 prop.setTypeName(u"double"_s);
598 prop.setType(m_typeResolver->realType());
599 setAccumulator(
600 m_pool->createProperty(
601 prop, accumulatorIn.resultLookupIndex(), lookupIndex,
602 // Use pre-determined scope type here to avoid adjusting it later.
603 QQmlJSRegisterContent::Property, m_state.accumulatorOut().scope())
604 );
605
606 return;
607 }
608
609 if (m_state.accumulatorOut().contains(m_typeResolver->voidType())) {
610 addError(u"Type %1 does not have a property %2 for reading"_s
611 .arg(accumulatorIn.descriptiveName(), propertyName));
612 return;
613 }
614
615 if (!m_state.accumulatorOut().property().type()) {
616 m_logger->log(
617 QString::fromLatin1("Type of property \"%2\" not found").arg(propertyName),
618 qmlMissingType, currentSourceLocation());
619 }
620 }
621
622 switch (m_state.accumulatorOut().variant()) {
623 case QQmlJSRegisterContent::Enum:
624 case QQmlJSRegisterContent::Singleton:
625 // For reading enums or singletons, we don't need to access anything, unless it's an
626 // import namespace. Then we need the name.
627 if (accumulatorIn.isImportNamespace())
628 addReadAccumulator();
629 break;
630 default:
631 addReadAccumulator();
632 break;
633 }
634}
635
636void QQmlJSTypePropagator::generate_LoadProperty(int nameIndex)
637{
638 propagatePropertyLookup(m_jsUnitGenerator->stringForIndex(nameIndex));
639}
640
641void QQmlJSTypePropagator::generate_LoadOptionalProperty(int name, int offset)
642{
643 Q_UNUSED(name);
644 Q_UNUSED(offset);
646}
647
648void QQmlJSTypePropagator::generate_GetLookup(int index)
649{
650 propagatePropertyLookup(m_jsUnitGenerator->lookupName(index), index);
651}
652
653void QQmlJSTypePropagator::generate_GetOptionalLookup(int index, int offset)
654{
655 Q_UNUSED(offset);
656 saveRegisterStateForJump(offset);
657 propagatePropertyLookup(m_jsUnitGenerator->lookupName(index), index);
658}
659
660void QQmlJSTypePropagator::generate_StoreProperty(int nameIndex, int base)
661{
662 auto callBase = m_state.registers[base].content;
663 const QString propertyName = m_jsUnitGenerator->stringForIndex(nameIndex);
664
665 QQmlJSRegisterContent property = m_typeResolver->memberType(callBase, propertyName);
666 if (!property.isProperty()) {
667 QString name = callBase.descriptiveName();
668 if (!name.isEmpty())
669 name += u' ';
670 addError(u"Type %1does not have a property %2 for writing"_s.arg(name, propertyName));
671 return;
672 }
673
674 if (property.containedType().isNull()) {
675 addError(u"Cannot determine type for property %1 of type %2"_s.arg(
676 propertyName, callBase.descriptiveName()));
677 return;
678 }
679
680 if (!property.isWritable() && !property.containedType()->isListProperty()) {
681 addError(u"Can't assign to read-only property %1"_s.arg(propertyName));
682
683 m_logger->log(u"Cannot assign to read-only property %1"_s.arg(propertyName),
684 qmlReadOnlyProperty, currentSourceLocation());
685
686 return;
687 }
688
689 if (!canConvertFromTo(m_state.accumulatorIn(), property)) {
690 addError(u"cannot convert from %1 to %2"_s
691 .arg(m_state.accumulatorIn().descriptiveName(), property.descriptiveName()));
692 return;
693 }
694
695 // If the input can hold undefined we must not coerce it to the property type
696 // as that might eliminate an undefined value. For example, undefined -> string
697 // becomes "undefined".
698 // We need the undefined value for either resetting the property if that is supported
699 // or generating an exception otherwise. Therefore we explicitly require the value to
700 // be given as QVariant. This triggers the QVariant fallback path that's also used for
701 // shadowable properties. QVariant can hold undefined and the lookup functions will
702 // handle that appropriately.
703
704 const QQmlJSScope::ConstPtr varType = m_typeResolver->varType();
705 const QQmlJSRegisterContent readType = m_typeResolver->canHoldUndefined(m_state.accumulatorIn())
706 ? m_typeResolver->convert(property, varType)
707 : std::move(property);
708 addReadAccumulator(readType);
709 addReadRegister(base);
710 m_state.setHasExternalSideEffects();
711}
712
713void QQmlJSTypePropagator::generate_SetLookup(int index, int base)
714{
715 generate_StoreProperty(m_jsUnitGenerator->lookupNameIndex(index), base);
716}
717
718void QQmlJSTypePropagator::generate_LoadSuperProperty(int property)
719{
720 Q_UNUSED(property)
722}
723
724void QQmlJSTypePropagator::generate_StoreSuperProperty(int property)
725{
726 Q_UNUSED(property)
728}
729
730void QQmlJSTypePropagator::generate_Yield()
731{
733}
734
735void QQmlJSTypePropagator::generate_YieldStar()
736{
738}
739
740void QQmlJSTypePropagator::generate_Resume(int)
741{
743}
744
745void QQmlJSTypePropagator::generate_CallValue(int name, int argc, int argv)
746{
747 m_state.setHasExternalSideEffects();
748 Q_UNUSED(name)
749 Q_UNUSED(argc)
750 Q_UNUSED(argv)
752}
753
754void QQmlJSTypePropagator::generate_CallWithReceiver(int name, int thisObject, int argc, int argv)
755{
756 m_state.setHasExternalSideEffects();
757 Q_UNUSED(name)
758 Q_UNUSED(thisObject)
759 Q_UNUSED(argc)
760 Q_UNUSED(argv)
762}
763
764bool QQmlJSTypePropagator::isLoggingMethod(const QString &consoleMethod)
765{
766 return consoleMethod == u"log" || consoleMethod == u"debug" || consoleMethod == u"info"
767 || consoleMethod == u"warn" || consoleMethod == u"error";
768}
769
770void QQmlJSTypePropagator::generate_CallProperty_SCMath(
771 const QString &name, int base, int argc, int argv)
772{
773 // If we call a method on the Math object we don't need the actual Math object. We do need
774 // to transfer the type information to the code generator so that it knows that this is the
775 // Math object. Read the base register as void. void isn't stored, and the place where it's
776 // created will be optimized out if there are no other readers. The code generator can
777 // retrieve the original type and determine that it was the Math object.
778
779 addReadRegister(base, m_typeResolver->voidType());
780
781 QQmlJSRegisterContent math = m_state.registers[base].content;
782 const QList<QQmlJSMetaMethod> methods = math.containedType()->ownMethods(name);
783 if (methods.isEmpty()) {
784 setVarAccumulatorAndError();
785 std::optional<QQmlJSFixSuggestion> fixSuggestion = QQmlJSUtils::didYouMean(
786 name, math.containedType()->methods().keys(), m_logger->filePath(),
787 currentSourceLocation());
788 m_logger->log(u"Member \"%1\" not found on Math object"_s.arg(name),
789 qmlMissingProperty, currentSourceLocation(),
790 true, true, std::move(fixSuggestion));
791 return;
792 }
793 Q_ASSERT(methods.length() == 1);
794
795 // Declare the Math object as base type of itself so that it gets cloned and won't be
796 // adjusted later. This is what we do with all method calls.
797 QQmlJSRegisterContent realType = m_typeResolver->returnType(
798 methods[0], m_typeResolver->realType(),
799 m_typeResolver->baseType(math.containedType(), math));
800 for (int i = 0; i < argc; ++i)
801 addReadRegister(argv + i, realType);
802 setAccumulator(realType);
803}
804
805void QQmlJSTypePropagator::generate_CallProperty_SCconsole(
806 const QString &name, int base, int argc, int argv)
807{
808 // If we call a method on the console object we don't need the console object.
809 addReadRegister(base, m_typeResolver->voidType());
810
811 if (argc > 0) {
812 const QQmlJSRegisterContent firstContent = m_state.registers[argv].content;
813 const QQmlJSScope::ConstPtr firstArg = firstContent.containedType();
814 switch (firstArg->accessSemantics()) {
815 case QQmlJSScope::AccessSemantics::Reference:
816 // We cannot know whether this will be a logging category at run time.
817 // Therefore we always pass any object types as special last argument.
818 addReadRegister(argv, m_typeResolver->genericType(firstArg));
819 break;
820 case QQmlJSScope::AccessSemantics::Sequence:
821 addReadRegister(argv);
822 break;
823 default:
824 addReadRegister(argv, m_typeResolver->stringType());
825 break;
826 }
827 }
828
829 for (int i = 1; i < argc; ++i) {
830 const QQmlJSRegisterContent argContent = m_state.registers[argv + i].content;
831 const QQmlJSScope::ConstPtr arg = argContent.containedType();
832 if (arg->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence)
833 addReadRegister(argv + i);
834 else
835 addReadRegister(argv + i, m_typeResolver->stringType());
836 }
837
838 // It's debatable whether the console API should be considered an external side effect.
839 // You can certainly qInstallMessageHandler and then react to the message and change
840 // some property in an object exposed to the currently running method. However, we might
841 // disregard such a thing as abuse of the API. For now, the console API is considered to
842 // have external side effects, though.
843 m_state.setHasExternalSideEffects();
844
845 QQmlJSRegisterContent console = m_state.registers[base].content;
846 QList<QQmlJSMetaMethod> methods = console.containedType()->ownMethods(name);
847 Q_ASSERT(methods.length() == 1);
848
849 // Declare the console object as base type of itself so that it gets cloned and won't be
850 // adjusted later. This is what we do with all method calls.
851 setAccumulator(m_typeResolver->returnType(
852 methods[0], m_typeResolver->voidType(),
853 m_typeResolver->baseType(console.containedType(), console)));
854}
855
856void QQmlJSTypePropagator::generate_CallProperty(int nameIndex, int base, int argc, int argv)
857{
858 Q_ASSERT(m_state.registers.contains(base));
859 const auto callBase = m_state.registers[base].content;
860 const QString propertyName = m_jsUnitGenerator->stringForIndex(nameIndex);
861
862 if (callBase.contains(m_typeResolver->mathObject())) {
863 generate_CallProperty_SCMath(propertyName, base, argc, argv);
864 return;
865 }
866
867 if (callBase.contains(m_typeResolver->consoleObject()) && isLoggingMethod(propertyName)) {
868 generate_CallProperty_SCconsole(propertyName, base, argc, argv);
869 return;
870 }
871
872 const auto baseType = callBase.containedType();
873 const auto member = m_typeResolver->memberType(callBase, propertyName);
874
875 if (!member.isMethod()) {
876 if (callBase.contains(m_typeResolver->jsValueType())
877 || callBase.contains(m_typeResolver->varType())) {
878 const auto jsValueType = m_typeResolver->jsValueType();
879 addReadRegister(base, jsValueType);
880 for (int i = 0; i < argc; ++i)
881 addReadRegister(argv + i, jsValueType);
882 m_state.setHasExternalSideEffects();
883
884 QQmlJSMetaMethod method;
885 method.setIsJavaScriptFunction(true);
886 method.setMethodName(propertyName);
887 method.setMethodType(QQmlJSMetaMethod::MethodType::Method);
888
889 setAccumulator(m_typeResolver->returnType(
890 method, m_typeResolver->jsValueType(), callBase));
891 return;
892 }
893
894 setVarAccumulatorAndError();
895 addError(u"Type %1 does not have a property %2 for calling"_s
896 .arg(callBase.descriptiveName(), propertyName));
897
898 if (callBase.isType() && isCallingProperty(callBase.type(), propertyName))
899 return;
900
901 if (checkForEnumProblems(callBase, propertyName))
902 return;
903
904 std::optional<QQmlJSFixSuggestion> fixSuggestion;
905
906 if (auto suggestion = QQmlJSUtils::didYouMean(propertyName, baseType->methods().keys(),
907 m_logger->filePath(), currentSourceLocation());
908 suggestion.has_value()) {
909 fixSuggestion = suggestion;
910 }
911
912 if (baseType->isFullyResolved() || baseType->isScript()) {
913 m_logger->log(u"Member \"%1\" not found on type \"%2\""_s.arg(
914 propertyName, callBase.containedTypeName()),
915 qmlMissingProperty, currentSourceLocation(), true, true, fixSuggestion);
916 }
917 return;
918 }
919
920 checkDeprecated(baseType, propertyName, true);
921
922 addReadRegister(base);
923
924 if (callBase.contains(m_typeResolver->stringType())) {
925 if (propertyName == u"arg"_s && argc == 1) {
926 propagateStringArgCall(callBase, argv);
927 return;
928 }
929 }
930
931 if (baseType->accessSemantics() == QQmlJSScope::AccessSemantics::Sequence
932 && member.scope().contains(m_typeResolver->arrayPrototype())
933 && propagateArrayMethod(propertyName, argc, argv, callBase)) {
934 return;
935 }
936
937 propagateCall(member.method(), argc, argv, member.scope());
938}
939
940QQmlJSMetaMethod QQmlJSTypePropagator::bestMatchForCall(const QList<QQmlJSMetaMethod> &methods,
941 int argc, int argv, QStringList *errors)
942{
943 QQmlJSMetaMethod javascriptFunction;
944 QQmlJSMetaMethod candidate;
945 bool hasMultipleCandidates = false;
946
947 for (const auto &method : methods) {
948
949 // If we encounter a JavaScript function, use this as a fallback if no other method matches
950 if (method.isJavaScriptFunction() && !javascriptFunction.isValid())
951 javascriptFunction = method;
952
953 if (method.returnType().isNull() && !method.returnTypeName().isEmpty()) {
954 errors->append(u"return type %1 cannot be resolved"_s
955 .arg(method.returnTypeName()));
956 continue;
957 }
958
959 const auto arguments = method.parameters();
960 if (argc != arguments.size()) {
961 errors->append(u"Function expects %1 arguments, but %2 were provided"_s
962 .arg(QString::number(arguments.size()), QString::number(argc)));
963 continue;
964 }
965
966 bool fuzzyMatch = true;
967 bool exactMatch = true;
968 for (int i = 0; i < argc; ++i) {
969 const auto argumentType = arguments[i].type();
970 if (argumentType.isNull()) {
971 errors->append(u"type %1 for argument %2 cannot be resolved"_s
972 .arg(arguments[i].typeName(), QString::number(i)));
973 exactMatch = false;
974 fuzzyMatch = false;
975 break;
976 }
977
978 const auto content = m_state.registers[argv + i].content;
979 if (content.contains(argumentType))
980 continue;
981
982 exactMatch = false;
983 if (canConvertFromTo(content, argumentType))
984 continue;
985
986 // We can try to call a method that expects a derived type.
987 if (argumentType->isReferenceType()
988 && m_typeResolver->inherits(
989 argumentType->baseType(), content.containedType())) {
990 continue;
991 }
992
993 errors->append(u"argument %1 contains %2 but is expected to contain the type %3"_s
994 .arg(QString::number(i), content.descriptiveName(),
995 arguments[i].typeName()));
996 fuzzyMatch = false;
997 break;
998 }
999
1000 if (exactMatch) {
1001 return method;
1002 } else if (fuzzyMatch) {
1003 if (!candidate.isValid())
1004 candidate = method;
1005 else
1006 hasMultipleCandidates = true;
1007 }
1008 }
1009
1010 if (hasMultipleCandidates)
1011 return QQmlJSMetaMethod();
1012
1013 return candidate.isValid() ? candidate : javascriptFunction;
1014}
1015
1016void QQmlJSTypePropagator::setAccumulator(QQmlJSRegisterContent content)
1017{
1018 setRegister(Accumulator, content);
1019}
1020
1021void QQmlJSTypePropagator::setRegister(int index, QQmlJSRegisterContent content)
1022{
1023 // If we've come to the same conclusion before, let's not track the type again.
1024 auto it = m_prevStateAnnotations.find(currentInstructionOffset());
1025 if (it != m_prevStateAnnotations.end()) {
1026 QQmlJSRegisterContent lastTry = it->second.changedRegister;
1027 if (lastTry.contains(content.containedType())) {
1028 m_state.setRegister(index, lastTry);
1029 return;
1030 }
1031 }
1032
1033 m_state.setRegister(index, content);
1034}
1035
1036/*! \internal
1037 * Merges the types of two variations of the register at \index
1038 * When the code branches and merges, the same register can carry one of multiple types.
1039 * For example:
1040 *
1041 * let a
1042 * if (something)
1043 * a = 12
1044 * else
1045 * a = "stringstring"
1046 * console.log(a)
1047 *
1048 * At the point where we log the value we need a type that can hold both, the number and
1049 * the string because we don't know which branch was taken before. mergeRegister chooses a
1050 * type that can hold both variants.
1051 *
1052 * Since the type propagator can run multiple passes over the same code (for loops with back
1053 * jumps), we need to reproduce previous resolutions of the merge where they still fit. To that
1054 * effect, we check m_prevStateAnnotations here.
1055 */
1056void QQmlJSTypePropagator::mergeRegister(
1057 int index, const VirtualRegister &a, const VirtualRegister &b)
1058{
1059 const VirtualRegister merged = {
1060 (a.content == b.content) ? a.content : m_typeResolver->merge(a.content, b.content),
1061 a.canMove && b.canMove,
1062 a.affectedBySideEffects || b.affectedBySideEffects,
1063 a.isShadowable || b.isShadowable,
1064 };
1065
1066 Q_ASSERT(merged.content.isValid());
1067
1068 if (!merged.content.isConversion()) {
1069 // The registers were the same. We're already tracking them.
1070 m_state.annotations[currentInstructionOffset()].typeConversions[index] = merged;
1071 m_state.registers[index] = merged;
1072 return;
1073 }
1074
1075 auto tryPrevStateConversion = [this](int index, const VirtualRegister &merged) -> bool {
1076 auto it = m_prevStateAnnotations.find(currentInstructionOffset());
1077 if (it == m_prevStateAnnotations.end())
1078 return false;
1079
1080 auto conversion = it->second.typeConversions.find(index);
1081 if (conversion == it->second.typeConversions.end())
1082 return false;
1083
1084 const VirtualRegister &lastTry = conversion.value();
1085
1086 Q_ASSERT(lastTry.content.isValid());
1087 if (!lastTry.content.isConversion())
1088 return false;
1089
1090 if (lastTry.content.conversionResultType() != merged.content.conversionResultType()
1091 || lastTry.content.conversionOrigins() != merged.content.conversionOrigins()
1092 || lastTry.canMove != merged.canMove
1093 || lastTry.affectedBySideEffects != merged.affectedBySideEffects
1094 || lastTry.isShadowable != merged.isShadowable) {
1095 return false;
1096 }
1097
1098 // We don't need to track it again if we've come to the same conclusion before.
1099 m_state.annotations[currentInstructionOffset()].typeConversions[index] = lastTry;
1100
1101 // Do not reset the side effects
1102 Q_ASSERT(!m_state.registers[index].affectedBySideEffects || lastTry.affectedBySideEffects);
1103
1104 m_state.registers[index] = lastTry;
1105 return true;
1106 };
1107
1108 if (!tryPrevStateConversion(index, merged)) {
1109 // if a != b, we have already re-tracked it.
1110 const VirtualRegister cloned = {
1111 (a == b) ? m_pool->clone(merged.content) : merged.content,
1112 merged.canMove,
1113 merged.affectedBySideEffects,
1114 merged.isShadowable,
1115 };
1116 Q_ASSERT(cloned.content.isValid());
1117 m_state.annotations[currentInstructionOffset()].typeConversions[index] = cloned;
1118 m_state.registers[index] = cloned;
1119 }
1120}
1121
1122void QQmlJSTypePropagator::addReadRegister(int index)
1123{
1124 // Explicitly pass the same type through without conversion
1125 m_state.addReadRegister(index, m_state.registers[index].content);
1126}
1127
1128void QQmlJSTypePropagator::addReadRegister(int index, QQmlJSRegisterContent convertTo)
1129{
1130 if (m_state.registers[index].content == convertTo) {
1131 // Explicitly pass the same type through without conversion
1132 m_state.addReadRegister(index, convertTo);
1133 } else {
1134 m_state.addReadRegister(
1135 index, m_typeResolver->convert(m_state.registers[index].content, convertTo));
1136 }
1137}
1138
1139void QQmlJSTypePropagator::addReadRegister(int index, const QQmlJSScope::ConstPtr &convertTo)
1140{
1141 m_state.addReadRegister(
1142 index, m_typeResolver->convert(m_state.registers[index].content, convertTo));
1143}
1144
1145void QQmlJSTypePropagator::propagateCall(
1146 const QList<QQmlJSMetaMethod> &methods, int argc, int argv,
1147 QQmlJSRegisterContent scope)
1148{
1149 QStringList errors;
1150 const QQmlJSMetaMethod match = bestMatchForCall(methods, argc, argv, &errors);
1151
1152 if (!match.isValid()) {
1153 setVarAccumulatorAndError();
1154 if (methods.size() == 1) {
1155 // Cannot have multiple fuzzy matches if there is only one method
1156 Q_ASSERT(errors.size() == 1);
1157 addError(errors.first());
1158 } else if (errors.size() < methods.size()) {
1159 addError(u"Multiple matching overrides found. Cannot determine the right one."_s);
1160 } else {
1161 addError(u"No matching override found. Candidates:\n"_s + errors.join(u'\n'));
1162 }
1163 return;
1164 }
1165
1166 QQmlJSScope::ConstPtr returnType;
1167 if (match.isJavaScriptFunction())
1168 returnType = m_typeResolver->jsValueType();
1169 else if (match.isConstructor())
1170 returnType = scope.containedType();
1171 else
1172 returnType = match.returnType();
1173
1174 setAccumulator(m_typeResolver->returnType(match, returnType, scope));
1175 if (!m_state.accumulatorOut().isValid())
1176 addError(u"Cannot store return type of method %1()."_s.arg(match.methodName()));
1177
1178 const auto types = match.parameters();
1179 for (int i = 0; i < argc; ++i) {
1180 if (i < types.size()) {
1181 const QQmlJSScope::ConstPtr type = match.isJavaScriptFunction()
1182 ? m_typeResolver->jsValueType()
1183 : QQmlJSScope::ConstPtr(types.at(i).type());
1184 if (!type.isNull()) {
1185 addReadRegister(argv + i, type);
1186 continue;
1187 }
1188 }
1189 addReadRegister(argv + i, m_typeResolver->jsValueType());
1190 }
1191 m_state.setHasExternalSideEffects();
1192}
1193
1194void QQmlJSTypePropagator::propagateTranslationMethod_SAcheck(const QString &methodName)
1195{
1196 Q_UNUSED(methodName);
1197}
1198
1199bool QQmlJSTypePropagator::propagateTranslationMethod(
1200 const QList<QQmlJSMetaMethod> &methods, int argc, int argv)
1201{
1202 if (methods.size() != 1)
1203 return false;
1204
1205 const QQmlJSMetaMethod method = methods.front();
1206 const QQmlJSScope::ConstPtr intType = m_typeResolver->int32Type();
1207 const QQmlJSScope::ConstPtr stringType = m_typeResolver->stringType();
1208
1209 const QQmlJSRegisterContent returnType = m_typeResolver->returnType(
1210 method, m_typeResolver->stringType(), m_typeResolver->jsGlobalObjectContent());
1211
1212 if (method.methodName() == u"qsTranslate"_s) {
1213 switch (argc) {
1214 case 4:
1215 addReadRegister(argv + 3, intType); // n
1216 Q_FALLTHROUGH();
1217 case 3:
1218 addReadRegister(argv + 2, stringType); // disambiguation
1219 Q_FALLTHROUGH();
1220 case 2:
1221 addReadRegister(argv + 1, stringType); // sourceText
1222 addReadRegister(argv, stringType); // context
1223 setAccumulator(returnType);
1224 propagateTranslationMethod_SAcheck(method.methodName());
1225 return true;
1226 default:
1227 return false;
1228 }
1229 }
1230
1231 if (method.methodName() == u"QT_TRANSLATE_NOOP"_s) {
1232 switch (argc) {
1233 case 3:
1234 addReadRegister(argv + 2, stringType); // disambiguation
1235 Q_FALLTHROUGH();
1236 case 2:
1237 addReadRegister(argv + 1, stringType); // sourceText
1238 addReadRegister(argv, stringType); // context
1239 setAccumulator(returnType);
1240 propagateTranslationMethod_SAcheck(method.methodName());
1241 return true;
1242 default:
1243 return false;
1244 }
1245 }
1246
1247 if (method.methodName() == u"qsTr"_s) {
1248 switch (argc) {
1249 case 3:
1250 addReadRegister(argv + 2, intType); // n
1251 Q_FALLTHROUGH();
1252 case 2:
1253 addReadRegister(argv + 1, stringType); // disambiguation
1254 Q_FALLTHROUGH();
1255 case 1:
1256 addReadRegister(argv, stringType); // sourceText
1257 setAccumulator(returnType);
1258 propagateTranslationMethod_SAcheck(method.methodName());
1259 return true;
1260 default:
1261 return false;
1262 }
1263 }
1264
1265 if (method.methodName() == u"QT_TR_NOOP"_s) {
1266 switch (argc) {
1267 case 2:
1268 addReadRegister(argv + 1, stringType); // disambiguation
1269 Q_FALLTHROUGH();
1270 case 1:
1271 addReadRegister(argv, stringType); // sourceText
1272 setAccumulator(returnType);
1273 propagateTranslationMethod_SAcheck(method.methodName());
1274 return true;
1275 default:
1276 return false;
1277 }
1278 }
1279
1280 if (method.methodName() == u"qsTrId"_s) {
1281 switch (argc) {
1282 case 2:
1283 addReadRegister(argv + 1, intType); // n
1284 Q_FALLTHROUGH();
1285 case 1:
1286 addReadRegister(argv, stringType); // id
1287 setAccumulator(returnType);
1288 propagateTranslationMethod_SAcheck(method.methodName());
1289 return true;
1290 default:
1291 return false;
1292 }
1293 }
1294
1295 if (method.methodName() == u"QT_TRID_NOOP"_s) {
1296 switch (argc) {
1297 case 1:
1298 addReadRegister(argv, stringType); // id
1299 setAccumulator(returnType);
1300 propagateTranslationMethod_SAcheck(method.methodName());
1301 return true;
1302 default:
1303 return false;
1304 }
1305 }
1306
1307 return false;
1308}
1309
1310void QQmlJSTypePropagator::propagateStringArgCall(QQmlJSRegisterContent base, int argv)
1311{
1312 QQmlJSMetaMethod method;
1313 method.setIsJavaScriptFunction(true);
1314 method.setMethodName(u"arg"_s);
1315 setAccumulator(m_typeResolver->returnType(method, m_typeResolver->stringType(), base));
1316 Q_ASSERT(m_state.accumulatorOut().isValid());
1317
1318 const QQmlJSScope::ConstPtr input = m_state.registers[argv].content.containedType();
1319
1320 if (input == m_typeResolver->uint32Type()
1321 || input == m_typeResolver->int64Type()
1322 || input == m_typeResolver->uint64Type()) {
1323 addReadRegister(argv, m_typeResolver->realType());
1324 return;
1325 }
1326
1327 if (m_typeResolver->isIntegral(input)) {
1328 addReadRegister(argv, m_typeResolver->int32Type());
1329 return;
1330 }
1331
1332 if (m_typeResolver->isNumeric(input)) {
1333 addReadRegister(argv, m_typeResolver->realType());
1334 return;
1335 }
1336
1337 if (input == m_typeResolver->boolType()) {
1338 addReadRegister(argv, m_typeResolver->boolType());
1339 return;
1340 }
1341
1342 addReadRegister(argv, m_typeResolver->stringType());
1343}
1344
1345bool QQmlJSTypePropagator::propagateArrayMethod(
1346 const QString &name, int argc, int argv, QQmlJSRegisterContent baseType)
1347{
1348 // TODO:
1349 // * For concat() we need to decide what kind of array to return and what kinds of arguments to
1350 // accept.
1351 // * For entries(), keys(), and values() we need iterators.
1352 // * For find(), findIndex(), sort(), every(), some(), forEach(), map(), filter(), reduce(),
1353 // and reduceRight() we need typed function pointers.
1354
1355 // TODO:
1356 // For now, every method that mutates the original array is considered to have external
1357 // side effects. We could do better by figuring out whether the array is actually backed
1358 // by an external property or has entries backed by an external property. If not, there
1359 // can't be any external side effects.
1360
1361 const auto intType = m_typeResolver->int32Type();
1362 const auto stringType = m_typeResolver->stringType();
1363 const auto baseContained = baseType.containedType();
1364 const auto elementContained = baseContained->elementType();
1365
1366 const auto setReturnType = [&](const QQmlJSScope::ConstPtr type) {
1367 QQmlJSMetaMethod method;
1368 method.setIsJavaScriptFunction(true);
1369 method.setMethodName(name);
1370 setAccumulator(m_typeResolver->returnType(method, type, baseType));
1371 };
1372
1373 if (name == u"copyWithin" && argc > 0 && argc < 4) {
1374 for (int i = 0; i < argc; ++i) {
1375 if (!canConvertFromTo(m_state.registers[argv + i].content, intType))
1376 return false;
1377 }
1378
1379 for (int i = 0; i < argc; ++i)
1380 addReadRegister(argv + i, intType);
1381
1382 m_state.setHasExternalSideEffects();
1383 setReturnType(baseContained);
1384 return true;
1385 }
1386
1387 if (name == u"fill" && argc > 0 && argc < 4) {
1388 if (!canConvertFromTo(m_state.registers[argv].content, elementContained))
1389 return false;
1390
1391 for (int i = 1; i < argc; ++i) {
1392 if (!canConvertFromTo(m_state.registers[argv + i].content, intType))
1393 return false;
1394 }
1395
1396 addReadRegister(argv, elementContained);
1397
1398 for (int i = 1; i < argc; ++i)
1399 addReadRegister(argv + i, intType);
1400
1401 m_state.setHasExternalSideEffects();
1402 setReturnType(baseContained);
1403 return true;
1404 }
1405
1406 if (name == u"includes" && argc > 0 && argc < 3) {
1407 if (!canConvertFromTo(m_state.registers[argv].content, elementContained))
1408 return false;
1409
1410 if (argc == 2) {
1411 if (!canConvertFromTo(m_state.registers[argv + 1].content, intType))
1412 return false;
1413 addReadRegister(argv + 1, intType);
1414 }
1415
1416 addReadRegister(argv, elementContained);
1417 setReturnType(m_typeResolver->boolType());
1418 return true;
1419 }
1420
1421 if (name == u"toString" || (name == u"join" && argc < 2)) {
1422 if (argc == 1) {
1423 if (!canConvertFromTo(m_state.registers[argv].content, stringType))
1424 return false;
1425 addReadRegister(argv, stringType);
1426 }
1427
1428 setReturnType(m_typeResolver->stringType());
1429 return true;
1430 }
1431
1432 if ((name == u"pop" || name == u"shift") && argc == 0) {
1433 m_state.setHasExternalSideEffects();
1434 setReturnType(elementContained);
1435 return true;
1436 }
1437
1438 if (name == u"push" || name == u"unshift") {
1439 for (int i = 0; i < argc; ++i) {
1440 if (!canConvertFromTo(m_state.registers[argv + i].content, elementContained))
1441 return false;
1442 }
1443
1444 for (int i = 0; i < argc; ++i)
1445 addReadRegister(argv + i, elementContained);
1446
1447 m_state.setHasExternalSideEffects();
1448 setReturnType(m_typeResolver->int32Type());
1449 return true;
1450 }
1451
1452 if (name == u"reverse" && argc == 0) {
1453 m_state.setHasExternalSideEffects();
1454 setReturnType(baseContained);
1455 return true;
1456 }
1457
1458 if (name == u"slice" && argc < 3) {
1459 for (int i = 0; i < argc; ++i) {
1460 if (!canConvertFromTo(m_state.registers[argv + i].content, intType))
1461 return false;
1462 }
1463
1464 for (int i = 0; i < argc; ++i)
1465 addReadRegister(argv + i, intType);
1466
1467 setReturnType(baseType.containedType()->isListProperty()
1468 ? m_typeResolver->qObjectListType()
1469 : baseContained);
1470 return true;
1471 }
1472
1473 if (name == u"splice" && argc > 0) {
1474 const int startAndDeleteCount = std::min(argc, 2);
1475 for (int i = 0; i < startAndDeleteCount; ++i) {
1476 if (!canConvertFromTo(m_state.registers[argv + i].content, intType))
1477 return false;
1478 }
1479
1480 for (int i = 2; i < argc; ++i) {
1481 if (!canConvertFromTo(m_state.registers[argv + i].content, elementContained))
1482 return false;
1483 }
1484
1485 for (int i = 0; i < startAndDeleteCount; ++i)
1486 addReadRegister(argv + i, intType);
1487
1488 for (int i = 2; i < argc; ++i)
1489 addReadRegister(argv + i, elementContained);
1490
1491 m_state.setHasExternalSideEffects();
1492 setReturnType(baseContained);
1493 return true;
1494 }
1495
1496 if ((name == u"indexOf" || name == u"lastIndexOf") && argc > 0 && argc < 3) {
1497 if (!canConvertFromTo(m_state.registers[argv].content, elementContained))
1498 return false;
1499
1500 if (argc == 2) {
1501 if (!canConvertFromTo(m_state.registers[argv + 1].content, intType))
1502 return false;
1503 addReadRegister(argv + 1, intType);
1504 }
1505
1506 addReadRegister(argv, elementContained);
1507 setReturnType(m_typeResolver->int32Type());
1508 return true;
1509 }
1510
1511 return false;
1512}
1513
1514void QQmlJSTypePropagator::generate_CallPropertyLookup(int lookupIndex, int base, int argc,
1515 int argv)
1516{
1517 generate_CallProperty(m_jsUnitGenerator->lookupNameIndex(lookupIndex), base, argc, argv);
1518}
1519
1520void QQmlJSTypePropagator::generate_CallName(int name, int argc, int argv)
1521{
1522 propagateScopeLookupCall(m_jsUnitGenerator->stringForIndex(name), argc, argv);
1523}
1524
1525void QQmlJSTypePropagator::generate_CallPossiblyDirectEval(int argc, int argv)
1526{
1527 m_state.setHasExternalSideEffects();
1528 Q_UNUSED(argc)
1529 Q_UNUSED(argv)
1530
1532}
1533
1534void QQmlJSTypePropagator::propagateScopeLookupCall(const QString &functionName, int argc, int argv)
1535{
1536 const QQmlJSRegisterContent resolvedContent
1537 = m_typeResolver->scopedType(m_function->qmlScope, functionName);
1538 if (resolvedContent.isMethod()) {
1539 if (isQmlContextObject(resolvedContent.scope()))
1540 handleUnqualifiedAccessAndContextProperties(functionName, true);
1541
1542 const auto methods = resolvedContent.method();
1543 if (resolvedContent.scope().contains(m_typeResolver->jsGlobalObject())) {
1544 if (propagateTranslationMethod(methods, argc, argv))
1545 return;
1546 }
1547
1548 if (!methods.isEmpty()) {
1549 propagateCall(methods, argc, argv, resolvedContent.scope());
1550 return;
1551 }
1552 }
1553
1554 addError(u"method %1 cannot be resolved."_s.arg(functionName));
1555 const auto jsValue = m_typeResolver->jsValueType();
1556 QQmlJSMetaMethod method;
1557 method.setMethodName(functionName);
1558 method.setIsJavaScriptFunction(true);
1559 setAccumulator(m_typeResolver->returnType(method, jsValue, m_function->qmlScope));
1560
1561 addError(u"Cannot find function '%1'"_s.arg(functionName));
1562
1563 handleUnqualifiedAccessAndContextProperties(functionName, true);
1564}
1565
1566void QQmlJSTypePropagator::generate_CallGlobalLookup(int index, int argc, int argv)
1567{
1568 propagateScopeLookupCall(m_jsUnitGenerator->lookupName(index), argc, argv);
1569}
1570
1571void QQmlJSTypePropagator::generate_CallQmlContextPropertyLookup(int index, int argc, int argv)
1572{
1573 const QString name = m_jsUnitGenerator->lookupName(index);
1574 propagateScopeLookupCall(name, argc, argv);
1575 checkDeprecated(m_function->qmlScope.containedType(), name, true);
1576}
1577
1578void QQmlJSTypePropagator::generate_CallWithSpread(int func, int thisObject, int argc, int argv)
1579{
1580 m_state.setHasExternalSideEffects();
1581 Q_UNUSED(func)
1582 Q_UNUSED(thisObject)
1583 Q_UNUSED(argc)
1584 Q_UNUSED(argv)
1586}
1587
1588void QQmlJSTypePropagator::generate_TailCall(int func, int thisObject, int argc, int argv)
1589{
1590 m_state.setHasExternalSideEffects();
1591 Q_UNUSED(func)
1592 Q_UNUSED(thisObject)
1593 Q_UNUSED(argc)
1594 Q_UNUSED(argv)
1596}
1597
1598void QQmlJSTypePropagator::generate_Construct_SCDate(
1599 const QQmlJSMetaMethod &ctor, int argc, int argv)
1600{
1601 setAccumulator(m_typeResolver->returnType(ctor, m_typeResolver->dateTimeType(), {}));
1602
1603 if (argc == 1) {
1604 const QQmlJSRegisterContent argType = m_state.registers[argv].content;
1605 if (m_typeResolver->isNumeric(argType)) {
1606 addReadRegister(argv, m_typeResolver->realType());
1607 } else if (argType.contains(m_typeResolver->stringType())) {
1608 addReadRegister(argv, m_typeResolver->stringType());
1609 } else if (argType.contains(m_typeResolver->dateTimeType())
1610 || argType.contains(m_typeResolver->dateType())
1611 || argType.contains(m_typeResolver->timeType())) {
1612 addReadRegister(argv, m_typeResolver->dateTimeType());
1613 } else {
1614 addReadRegister(argv, m_typeResolver->jsPrimitiveType());
1615 }
1616 } else {
1617 constexpr int maxArgc = 7; // year, month, day, hours, minutes, seconds, milliseconds
1618 for (int i = 0; i < std::min(argc, maxArgc); ++i)
1619 addReadRegister(argv + i, m_typeResolver->realType());
1620 }
1621}
1622
1623void QQmlJSTypePropagator::generate_Construct_SCArray(
1624 const QQmlJSMetaMethod &ctor, int argc, int argv)
1625{
1626 if (argc == 1) {
1627 if (m_typeResolver->isNumeric(m_state.registers[argv].content)) {
1628 setAccumulator(m_typeResolver->returnType(ctor, m_typeResolver->variantListType(), {}));
1629 addReadRegister(argv, m_typeResolver->realType());
1630 } else {
1631 generate_DefineArray(argc, argv);
1632 }
1633 } else {
1634 generate_DefineArray(argc, argv);
1635 }
1636}
1637void QQmlJSTypePropagator::generate_Construct(int func, int argc, int argv)
1638{
1639 const QQmlJSRegisterContent type = m_state.registers[func].content;
1640 if (type.contains(m_typeResolver->metaObjectType())) {
1641 const QQmlJSRegisterContent valueType = type.scope();
1642 const QQmlJSScope::ConstPtr contained = type.scopeType();
1643 if (contained->isValueType() && contained->isCreatable()) {
1644 const auto extension = contained->extensionType();
1645 if (extension.extensionSpecifier == QQmlJSScope::ExtensionType) {
1646 propagateCall(
1647 extension.scope->ownMethods(extension.scope->internalName()),
1648 argc, argv, valueType);
1649 } else {
1650 propagateCall(
1651 contained->ownMethods(contained->internalName()), argc, argv, valueType);
1652 }
1653 return;
1654 }
1655 }
1656
1657 if (!type.isMethod()) {
1658 m_state.setHasExternalSideEffects();
1659 QQmlJSMetaMethod method;
1660 method.setMethodName(type.containedTypeName());
1661 method.setIsJavaScriptFunction(true);
1662 method.setIsConstructor(true);
1663 setAccumulator(m_typeResolver->returnType(method, m_typeResolver->jsValueType(), {}));
1664 return;
1665 }
1666
1667 if (const auto methods = type.method();
1668 methods == m_typeResolver->jsGlobalObject()->methods(u"Date"_s)) {
1669 Q_ASSERT(methods.length() == 1);
1670 generate_Construct_SCDate(methods[0], argc, argv);
1671 return;
1672 }
1673
1674 if (const auto methods = type.method();
1675 methods == m_typeResolver->jsGlobalObject()->methods(u"Array"_s)) {
1676 Q_ASSERT(methods.length() == 1);
1677 generate_Construct_SCArray(methods[0], argc, argv);
1678 return;
1679 }
1680
1681 m_state.setHasExternalSideEffects();
1682
1683 QStringList errors;
1684 QQmlJSMetaMethod match = bestMatchForCall(type.method(), argc, argv, &errors);
1685 if (!match.isValid())
1686 addError(u"Cannot determine matching constructor. Candidates:\n"_s + errors.join(u'\n'));
1687 setAccumulator(m_typeResolver->returnType(match, m_typeResolver->jsValueType(), {}));
1688}
1689
1690void QQmlJSTypePropagator::generate_ConstructWithSpread(int func, int argc, int argv)
1691{
1692 m_state.setHasExternalSideEffects();
1693 Q_UNUSED(func)
1694 Q_UNUSED(argc)
1695 Q_UNUSED(argv)
1697}
1698
1699void QQmlJSTypePropagator::generate_SetUnwindHandler(int offset)
1700{
1701 m_state.setHasInternalSideEffects();
1702
1703 // See QQmlJSBasicBlocks::generate_SetUnwindHandler()
1704 if (offset != 0)
1705 saveRegisterStateForJump(offset);
1707}
1708
1709void QQmlJSTypePropagator::generate_UnwindDispatch()
1710{
1711 m_state.setHasInternalSideEffects();
1713}
1714
1715void QQmlJSTypePropagator::generate_UnwindToLabel(int level, int offset)
1716{
1717 m_state.setHasInternalSideEffects();
1718 Q_UNUSED(level)
1719 Q_UNUSED(offset)
1721}
1722
1723void QQmlJSTypePropagator::generate_DeadTemporalZoneCheck(int name)
1724{
1725 const auto fail = [this, name]() {
1726 addError(u"Cannot statically assert the dead temporal zone check for %1"_s.arg(
1727 name ? m_jsUnitGenerator->stringForIndex(name) : u"the anonymous accumulator"_s));
1728 };
1729
1730 const QQmlJSRegisterContent in = m_state.accumulatorIn();
1731 if (in.isConversion()) {
1732 const auto &inConversionOrigins = in.conversionOrigins();
1733 for (QQmlJSRegisterContent origin : inConversionOrigins) {
1734 if (!origin.contains(m_typeResolver->emptyType()))
1735 continue;
1736 fail();
1737 break;
1738 }
1739 } else if (in.contains(m_typeResolver->emptyType())) {
1740 fail();
1741 }
1742}
1743
1744void QQmlJSTypePropagator::generate_ThrowException()
1745{
1746 addReadAccumulator(m_typeResolver->jsValueType());
1747 m_state.setHasInternalSideEffects();
1748 m_state.skipInstructionsUntilNextJumpTarget = true;
1749}
1750
1751void QQmlJSTypePropagator::generate_GetException()
1752{
1754}
1755
1756void QQmlJSTypePropagator::generate_SetException()
1757{
1758 m_state.setHasInternalSideEffects();
1760}
1761
1762void QQmlJSTypePropagator::generate_CreateCallContext()
1763{
1764 m_state.setHasInternalSideEffects();
1765}
1766
1767void QQmlJSTypePropagator::generate_PushCatchContext(int index, int name)
1768{
1769 m_state.setHasInternalSideEffects();
1770 Q_UNUSED(index)
1771 Q_UNUSED(name)
1773}
1774
1775void QQmlJSTypePropagator::generate_PushWithContext()
1776{
1777 m_state.setHasInternalSideEffects();
1779}
1780
1781void QQmlJSTypePropagator::generate_PushBlockContext(int index)
1782{
1783 m_state.setHasInternalSideEffects();
1784 Q_UNUSED(index)
1786}
1787
1788void QQmlJSTypePropagator::generate_CloneBlockContext()
1789{
1790 m_state.setHasInternalSideEffects();
1792}
1793
1794void QQmlJSTypePropagator::generate_PushScriptContext(int index)
1795{
1796 m_state.setHasInternalSideEffects();
1797 Q_UNUSED(index)
1799}
1800
1801void QQmlJSTypePropagator::generate_PopScriptContext()
1802{
1803 m_state.setHasInternalSideEffects();
1805}
1806
1807void QQmlJSTypePropagator::generate_PopContext()
1808{
1809 m_state.setHasInternalSideEffects();
1810}
1811
1812void QQmlJSTypePropagator::generate_GetIterator(int iterator)
1813{
1814 const QQmlJSRegisterContent listType = m_state.accumulatorIn();
1815 if (!listType.isList()) {
1816 const QQmlJSScope::ConstPtr jsValue = m_typeResolver->jsValueType();
1817 addReadAccumulator(jsValue);
1818
1819 QQmlJSMetaProperty prop;
1820 prop.setPropertyName(u"<>"_s);
1821 prop.setTypeName(jsValue->internalName());
1822 prop.setType(jsValue);
1823 setAccumulator(m_pool->createProperty(
1824 prop, currentInstructionOffset(),
1825 QQmlJSRegisterContent::InvalidLookupIndex, QQmlJSRegisterContent::ListIterator,
1826 listType));
1827 return;
1828 }
1829
1830 addReadAccumulator();
1831 setAccumulator(m_typeResolver->iteratorPointer(
1832 listType, QQmlJS::AST::ForEachType(iterator), currentInstructionOffset()));
1833}
1834
1835void QQmlJSTypePropagator::generate_IteratorNext(int value, int offset)
1836{
1837 const QQmlJSRegisterContent iteratorType = m_state.accumulatorIn();
1838 addReadAccumulator();
1839 setRegister(value, m_typeResolver->merge(
1840 m_typeResolver->elementType(iteratorType),
1841 m_typeResolver->literalType(m_typeResolver->voidType())));
1842 saveRegisterStateForJump(offset);
1843 m_state.setHasInternalSideEffects();
1844}
1845
1846void QQmlJSTypePropagator::generate_IteratorNextForYieldStar(int iterator, int object, int offset)
1847{
1848 Q_UNUSED(iterator)
1849 Q_UNUSED(object)
1850 Q_UNUSED(offset)
1852}
1853
1854void QQmlJSTypePropagator::generate_IteratorClose()
1855{
1856 // Noop
1857}
1858
1859void QQmlJSTypePropagator::generate_DestructureRestElement()
1860{
1862}
1863
1864void QQmlJSTypePropagator::generate_DeleteProperty(int base, int index)
1865{
1866 Q_UNUSED(base)
1867 Q_UNUSED(index)
1869}
1870
1871void QQmlJSTypePropagator::generate_DeleteName(int name)
1872{
1873 Q_UNUSED(name)
1875}
1876
1877void QQmlJSTypePropagator::generate_TypeofName(int name)
1878{
1879 Q_UNUSED(name);
1880 setAccumulator(m_typeResolver->operationType(m_typeResolver->stringType()));
1881}
1882
1883void QQmlJSTypePropagator::generate_TypeofValue()
1884{
1885 setAccumulator(m_typeResolver->operationType(m_typeResolver->stringType()));
1886}
1887
1888void QQmlJSTypePropagator::generate_DeclareVar(int varName, int isDeletable)
1889{
1890 Q_UNUSED(varName)
1891 Q_UNUSED(isDeletable)
1893}
1894
1895void QQmlJSTypePropagator::generate_DefineArray(int argc, int args)
1896{
1897 setAccumulator(m_typeResolver->operationType(m_typeResolver->variantListType()));
1898
1899 // Track all arguments as the same type.
1900 const QQmlJSScope::ConstPtr elementType = m_typeResolver->varType();
1901 for (int i = 0; i < argc; ++i)
1902 addReadRegister(args + i, elementType);
1903}
1904
1905void QQmlJSTypePropagator::generate_DefineObjectLiteral(int internalClassId, int argc, int args)
1906{
1907 const int classSize = m_jsUnitGenerator->jsClassSize(internalClassId);
1908 Q_ASSERT(argc >= classSize);
1909
1910 // Track each element as separate type
1911 for (int i = 0; i < classSize; ++i)
1912 addReadRegister(args + i, m_typeResolver->varType());
1913
1914 for (int i = classSize; i < argc; i += 3) {
1915 // layout for remaining members is:
1916 // 0: ObjectLiteralArgument - Value|Method|Getter|Setter
1917 // We cannot do anything useful with this. Any code that would call a getter/setter/method
1918 // could not be compiled to C++. Ignore it.
1919
1920 // 1: name of argument
1921 addReadRegister(args + i + 1, m_typeResolver->stringType());
1922
1923 // 2: value of argument
1924 addReadRegister(args + i + 2, m_typeResolver->varType());
1925 }
1926
1927 setAccumulator(m_typeResolver->operationType(m_typeResolver->variantMapType()));
1928}
1929
1930void QQmlJSTypePropagator::generate_CreateClass(int classIndex, int heritage, int computedNames)
1931{
1932 Q_UNUSED(classIndex)
1933 Q_UNUSED(heritage)
1934 Q_UNUSED(computedNames)
1936}
1937
1938void QQmlJSTypePropagator::generate_CreateMappedArgumentsObject()
1939{
1941}
1942
1943void QQmlJSTypePropagator::generate_CreateUnmappedArgumentsObject()
1944{
1946}
1947
1948void QQmlJSTypePropagator::generate_CreateRestParameter(int argIndex)
1949{
1950 Q_UNUSED(argIndex)
1952}
1953
1954void QQmlJSTypePropagator::generate_ConvertThisToObject()
1955{
1956 setRegister(This, m_pool->clone(m_function->qmlScope));
1957}
1958
1959void QQmlJSTypePropagator::generate_LoadSuperConstructor()
1960{
1962}
1963
1964void QQmlJSTypePropagator::generate_ToObject()
1965{
1967}
1968
1969void QQmlJSTypePropagator::generate_Jump(int offset)
1970{
1971 saveRegisterStateForJump(offset);
1972 m_state.skipInstructionsUntilNextJumpTarget = true;
1973 m_state.setHasInternalSideEffects();
1974}
1975
1976void QQmlJSTypePropagator::generate_JumpTrue(int offset)
1977{
1978 if (!canConvertFromTo(m_state.accumulatorIn(), m_typeResolver->boolType())) {
1979 addError(u"cannot convert from %1 to boolean"_s
1980 .arg(m_state.accumulatorIn().descriptiveName()));
1981 return;
1982 }
1983 saveRegisterStateForJump(offset);
1984 addReadAccumulator(m_typeResolver->boolType());
1985 m_state.setHasInternalSideEffects();
1986}
1987
1988void QQmlJSTypePropagator::generate_JumpFalse(int offset)
1989{
1990 if (!canConvertFromTo(m_state.accumulatorIn(), m_typeResolver->boolType())) {
1991 addError(u"cannot convert from %1 to boolean"_s
1992 .arg(m_state.accumulatorIn().descriptiveName()));
1993 return;
1994 }
1995 saveRegisterStateForJump(offset);
1996 addReadAccumulator(m_typeResolver->boolType());
1997 m_state.setHasInternalSideEffects();
1998}
1999
2000void QQmlJSTypePropagator::generate_JumpNoException(int offset)
2001{
2002 saveRegisterStateForJump(offset);
2003 m_state.setHasInternalSideEffects();
2004}
2005
2006void QQmlJSTypePropagator::generate_JumpNotUndefined(int offset)
2007{
2008 Q_UNUSED(offset)
2010}
2011
2012void QQmlJSTypePropagator::generate_CheckException()
2013{
2014 m_state.setHasInternalSideEffects();
2015}
2016
2017void QQmlJSTypePropagator::recordEqualsNullType()
2018{
2019 // TODO: We can specialize this further, for QVariant, QJSValue, int, bool, whatever.
2020 if (m_state.accumulatorIn().contains(m_typeResolver->nullType())
2021 || m_state.accumulatorIn().containedType()->isReferenceType()) {
2022 addReadAccumulator();
2023 } else {
2024 addReadAccumulator(m_typeResolver->jsPrimitiveType());
2025 }
2026}
2027void QQmlJSTypePropagator::recordEqualsIntType()
2028{
2029 // We have specializations for numeric types and bool.
2030 const QQmlJSScope::ConstPtr in = m_state.accumulatorIn().containedType();
2031 if (m_state.accumulatorIn().contains(m_typeResolver->boolType())
2032 || m_typeResolver->isNumeric(m_state.accumulatorIn())) {
2033 addReadAccumulator();
2034 } else {
2035 addReadAccumulator(m_typeResolver->jsPrimitiveType());
2036 }
2037}
2038void QQmlJSTypePropagator::recordEqualsType(int lhs)
2039{
2040 const auto isNumericOrEnum = [this](QQmlJSRegisterContent content) {
2041 return content.isEnumeration() || m_typeResolver->isNumeric(content);
2042 };
2043
2044 const auto accumulatorIn = m_state.accumulatorIn();
2045 const auto lhsRegister = m_state.registers[lhs].content;
2046
2047 // If the types are primitive, we compare directly ...
2048 if (m_typeResolver->isPrimitive(accumulatorIn) || accumulatorIn.isEnumeration()) {
2049 if (accumulatorIn.contains(lhsRegister.containedType())
2050 || (isNumericOrEnum(accumulatorIn) && isNumericOrEnum(lhsRegister))
2051 || m_typeResolver->isPrimitive(lhsRegister)) {
2052 addReadRegister(lhs);
2053 addReadAccumulator();
2054 return;
2055 }
2056 }
2057
2058 const auto containedAccumulatorIn = m_typeResolver->isOptionalType(accumulatorIn)
2059 ? m_typeResolver->extractNonVoidFromOptionalType(accumulatorIn).containedType()
2060 : accumulatorIn.containedType();
2061
2062 const auto containedLhs = m_typeResolver->isOptionalType(lhsRegister)
2063 ? m_typeResolver->extractNonVoidFromOptionalType(lhsRegister).containedType()
2064 : lhsRegister.containedType();
2065
2066 // We don't modify types if the types are comparable with QObject, QUrl or var types
2067 if (QQmlJSUtils::canStrictlyCompareWithVar(m_typeResolver, containedLhs, containedAccumulatorIn)
2068 || QQmlJSUtils::canCompareWithQObject(m_typeResolver, containedLhs, containedAccumulatorIn)
2069 || QQmlJSUtils::canCompareWithQUrl(m_typeResolver, containedLhs, containedAccumulatorIn)) {
2070 addReadRegister(lhs);
2071 addReadAccumulator();
2072 return;
2073 }
2074
2075 // Otherwise they're both casted to QJSValue.
2076 // TODO: We can add more specializations here: object/null etc
2077
2078 const QQmlJSScope::ConstPtr jsval = m_typeResolver->jsValueType();
2079 addReadRegister(lhs, jsval);
2080 addReadAccumulator(jsval);
2081}
2082
2083void QQmlJSTypePropagator::recordCompareType(int lhs)
2084{
2085 // TODO: Revisit this. Does it make any sense to do a comparison on something non-numeric?
2086 // Does it pay off to record the exact number type to use?
2087
2088 const QQmlJSRegisterContent lhsContent = m_state.registers[lhs].content;
2089 const QQmlJSRegisterContent rhsContent = m_state.accumulatorIn();
2090 if (lhsContent == rhsContent) {
2091 // Do not re-track in this case. We want any manipulations on the original types to persist.
2092 // TODO: Why? Can we just use double and be done with it?
2093 addReadRegister(lhs, lhsContent);
2094 addReadAccumulator(lhsContent);
2095 } else if (m_typeResolver->isNumeric(lhsContent) && m_typeResolver->isNumeric(rhsContent)) {
2096 // If they're both numeric, we can compare them directly.
2097 // They may be casted to double, though.
2098 const QQmlJSRegisterContent merged = m_typeResolver->merge(lhsContent, rhsContent);
2099 addReadRegister(lhs, merged);
2100 addReadAccumulator(merged);
2101 } else {
2102 const QQmlJSScope::ConstPtr primitive = m_typeResolver->jsPrimitiveType();
2103 addReadRegister(lhs, primitive);
2104 addReadAccumulator(primitive);
2105 }
2106}
2107
2108void QQmlJSTypePropagator::warnAboutTypeCoercion(int lhs)
2109{
2110 Q_UNUSED(lhs);
2111}
2112
2113void QQmlJSTypePropagator::generate_CmpEqNull()
2114{
2115 recordEqualsNullType();
2116 setAccumulator(m_typeResolver->operationType(m_typeResolver->boolType()));
2117}
2118
2119void QQmlJSTypePropagator::generate_CmpNeNull()
2120{
2121 recordEqualsNullType();
2122 setAccumulator(m_typeResolver->operationType(m_typeResolver->boolType()));
2123}
2124
2125void QQmlJSTypePropagator::generate_CmpEqInt(int lhsConst)
2126{
2127 recordEqualsIntType();
2128 Q_UNUSED(lhsConst)
2129 setAccumulator(m_typeResolver->typeForBinaryOperation(
2130 QSOperator::Op::Equal, m_typeResolver->literalType(m_typeResolver->int32Type()),
2131 m_state.accumulatorIn()));
2132}
2133
2134void QQmlJSTypePropagator::generate_CmpNeInt(int lhsConst)
2135{
2136 recordEqualsIntType();
2137 Q_UNUSED(lhsConst)
2138 setAccumulator(m_typeResolver->typeForBinaryOperation(
2139 QSOperator::Op::NotEqual, m_typeResolver->literalType(m_typeResolver->int32Type()),
2140 m_state.accumulatorIn()));
2141}
2142
2143void QQmlJSTypePropagator::generate_CmpEq(int lhs)
2144{
2145 warnAboutTypeCoercion(lhs);
2146 recordEqualsType(lhs);
2147 propagateBinaryOperation(QSOperator::Op::Equal, lhs);
2148}
2149
2150void QQmlJSTypePropagator::generate_CmpNe(int lhs)
2151{
2152 warnAboutTypeCoercion(lhs);
2153 recordEqualsType(lhs);
2154 propagateBinaryOperation(QSOperator::Op::NotEqual, lhs);
2155}
2156
2157void QQmlJSTypePropagator::generate_CmpGt(int lhs)
2158{
2159 recordCompareType(lhs);
2160 propagateBinaryOperation(QSOperator::Op::Gt, lhs);
2161}
2162
2163void QQmlJSTypePropagator::generate_CmpGe(int lhs)
2164{
2165 recordCompareType(lhs);
2166 propagateBinaryOperation(QSOperator::Op::Ge, lhs);
2167}
2168
2169void QQmlJSTypePropagator::generate_CmpLt(int lhs)
2170{
2171 recordCompareType(lhs);
2172 propagateBinaryOperation(QSOperator::Op::Lt, lhs);
2173}
2174
2175void QQmlJSTypePropagator::generate_CmpLe(int lhs)
2176{
2177 recordCompareType(lhs);
2178 propagateBinaryOperation(QSOperator::Op::Le, lhs);
2179}
2180
2181void QQmlJSTypePropagator::generate_CmpStrictEqual(int lhs)
2182{
2183 recordEqualsType(lhs);
2184 propagateBinaryOperation(QSOperator::Op::StrictEqual, lhs);
2185}
2186
2187void QQmlJSTypePropagator::generate_CmpStrictNotEqual(int lhs)
2188{
2189 recordEqualsType(lhs);
2190 propagateBinaryOperation(QSOperator::Op::StrictNotEqual, lhs);
2191}
2192
2193void QQmlJSTypePropagator::generate_CmpIn(int lhs)
2194{
2195 // TODO: Most of the time we don't need the object at all, but only its metatype.
2196 // Fix this when we add support for the "in" instruction to the code generator.
2197 // Also, specialize on lhs to avoid conversion to QJSPrimitiveValue.
2198
2199 addReadRegister(lhs, m_typeResolver->jsValueType());
2200 addReadAccumulator(m_typeResolver->jsValueType());
2201
2202 propagateBinaryOperation(QSOperator::Op::In, lhs);
2203}
2204
2205void QQmlJSTypePropagator::generate_CmpInstanceOf(int lhs)
2206{
2207 Q_UNUSED(lhs)
2209}
2210
2211void QQmlJSTypePropagator::generate_As(int lhs)
2212{
2213 const QQmlJSRegisterContent input = checkedInputRegister(lhs);
2214 const QQmlJSScope::ConstPtr inContained = input.containedType();
2215
2216 QQmlJSRegisterContent output;
2217
2218 const QQmlJSRegisterContent accumulatorIn = m_state.accumulatorIn();
2219 switch (accumulatorIn.variant()) {
2220 case QQmlJSRegisterContent::Attachment:
2221 output = accumulatorIn.scope();
2222 break;
2223 case QQmlJSRegisterContent::MetaType:
2224 output = accumulatorIn.scope();
2225 if (output.containedType()->isComposite()) // Otherwise we don't need it
2226 addReadAccumulator(m_typeResolver->metaObjectType());
2227 break;
2228 default:
2229 output = accumulatorIn;
2230 break;
2231 }
2232
2233 QQmlJSScope::ConstPtr outContained = output.containedType();
2234
2235 if (outContained->accessSemantics() == QQmlJSScope::AccessSemantics::Reference) {
2236 // A referece type cast can result in either the type or null.
2237 // Reference types can hold null. We don't need to special case that.
2238
2239 if (m_typeResolver->inherits(inContained, outContained))
2240 output = m_pool->clone(input);
2241 else
2242 output = m_pool->castTo(input, outContained);
2243 } else if (m_typeResolver->inherits(inContained, outContained)) {
2244 // A "slicing" cannot result in void
2245 output = m_pool->castTo(input, outContained);
2246 } else {
2247 // A value type cast can result in either the type or undefined.
2248 // Using convert() retains the variant of the input type.
2249 output = m_typeResolver->merge(
2250 m_pool->castTo(input, outContained),
2251 m_pool->castTo(input, m_typeResolver->voidType()));
2252 }
2253
2254 addReadRegister(lhs);
2255 setAccumulator(output);
2256}
2257
2258void QQmlJSTypePropagator::checkConversion(
2259 QQmlJSRegisterContent from, QQmlJSRegisterContent to)
2260{
2261 if (!canConvertFromTo(from, to)) {
2262 addError(u"cannot convert from %1 to %2"_s
2263 .arg(from.descriptiveName(), to.descriptiveName()));
2264 }
2265}
2266
2267void QQmlJSTypePropagator::generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator op)
2268{
2269 const QQmlJSRegisterContent type = m_typeResolver->typeForArithmeticUnaryOperation(
2270 op, m_state.accumulatorIn());
2271 checkConversion(m_state.accumulatorIn(), type);
2272 addReadAccumulator(type);
2273 setAccumulator(type);
2274}
2275
2276void QQmlJSTypePropagator::generate_UNot()
2277{
2278 generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator::Not);
2279}
2280
2281void QQmlJSTypePropagator::generate_UPlus()
2282{
2283 generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator::Plus);
2284}
2285
2286void QQmlJSTypePropagator::generate_UMinus()
2287{
2288 generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator::Minus);
2289}
2290
2291void QQmlJSTypePropagator::generate_UCompl()
2292{
2293 generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator::Complement);
2294}
2295
2296void QQmlJSTypePropagator::generate_Increment()
2297{
2298 generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator::Increment);
2299}
2300
2301void QQmlJSTypePropagator::generate_Decrement()
2302{
2303 generateUnaryArithmeticOperation(QQmlJSTypeResolver::UnaryOperator::Decrement);
2304}
2305
2306void QQmlJSTypePropagator::generateBinaryArithmeticOperation(QSOperator::Op op, int lhs)
2307{
2308 const QQmlJSRegisterContent type = propagateBinaryOperation(op, lhs);
2309
2310 checkConversion(checkedInputRegister(lhs), type);
2311 addReadRegister(lhs, type);
2312
2313 checkConversion(m_state.accumulatorIn(), type);
2314 addReadAccumulator(type);
2315}
2316
2317void QQmlJSTypePropagator::generateBinaryConstArithmeticOperation(QSOperator::Op op)
2318{
2319 const QQmlJSRegisterContent type = m_typeResolver->typeForBinaryOperation(
2320 op, m_state.accumulatorIn(),
2321 m_typeResolver->literalType(m_typeResolver->int32Type()));
2322
2323 checkConversion(m_state.accumulatorIn(), type);
2324 addReadAccumulator(type);
2325 setAccumulator(type);
2326}
2327
2328void QQmlJSTypePropagator::generate_Add(int lhs)
2329{
2330 generateBinaryArithmeticOperation(QSOperator::Op::Add, lhs);
2331}
2332
2333void QQmlJSTypePropagator::generate_BitAnd(int lhs)
2334{
2335 generateBinaryArithmeticOperation(QSOperator::Op::BitAnd, lhs);
2336}
2337
2338void QQmlJSTypePropagator::generate_BitOr(int lhs)
2339{
2340 generateBinaryArithmeticOperation(QSOperator::Op::BitOr, lhs);
2341}
2342
2343void QQmlJSTypePropagator::generate_BitXor(int lhs)
2344{
2345 generateBinaryArithmeticOperation(QSOperator::Op::BitXor, lhs);
2346}
2347
2348void QQmlJSTypePropagator::generate_UShr(int lhs)
2349{
2350 generateBinaryArithmeticOperation(QSOperator::Op::URShift, lhs);
2351}
2352
2353void QQmlJSTypePropagator::generate_Shr(int lhs)
2354{
2355 generateBinaryArithmeticOperation(QSOperator::Op::RShift, lhs);
2356}
2357
2358void QQmlJSTypePropagator::generate_Shl(int lhs)
2359{
2360 generateBinaryArithmeticOperation(QSOperator::Op::LShift, lhs);
2361}
2362
2363void QQmlJSTypePropagator::generate_BitAndConst(int rhsConst)
2364{
2365 Q_UNUSED(rhsConst)
2366 generateBinaryConstArithmeticOperation(QSOperator::Op::BitAnd);
2367}
2368
2369void QQmlJSTypePropagator::generate_BitOrConst(int rhsConst)
2370{
2371 Q_UNUSED(rhsConst)
2372 generateBinaryConstArithmeticOperation(QSOperator::Op::BitOr);
2373}
2374
2375void QQmlJSTypePropagator::generate_BitXorConst(int rhsConst)
2376{
2377 Q_UNUSED(rhsConst)
2378 generateBinaryConstArithmeticOperation(QSOperator::Op::BitXor);
2379}
2380
2381void QQmlJSTypePropagator::generate_UShrConst(int rhsConst)
2382{
2383 Q_UNUSED(rhsConst)
2384 generateBinaryConstArithmeticOperation(QSOperator::Op::URShift);
2385}
2386
2387void QQmlJSTypePropagator::generate_ShrConst(int rhsConst)
2388{
2389 Q_UNUSED(rhsConst)
2390 generateBinaryConstArithmeticOperation(QSOperator::Op::RShift);
2391}
2392
2393void QQmlJSTypePropagator::generate_ShlConst(int rhsConst)
2394{
2395 Q_UNUSED(rhsConst)
2396 generateBinaryConstArithmeticOperation(QSOperator::Op::LShift);
2397}
2398
2399void QQmlJSTypePropagator::generate_Exp(int lhs)
2400{
2401 generateBinaryArithmeticOperation(QSOperator::Op::Exp, lhs);
2402}
2403
2404void QQmlJSTypePropagator::generate_Mul(int lhs)
2405{
2406 generateBinaryArithmeticOperation(QSOperator::Op::Mul, lhs);
2407}
2408
2409void QQmlJSTypePropagator::generate_Div(int lhs)
2410{
2411 generateBinaryArithmeticOperation(QSOperator::Op::Div, lhs);
2412}
2413
2414void QQmlJSTypePropagator::generate_Mod(int lhs)
2415{
2416 generateBinaryArithmeticOperation(QSOperator::Op::Mod, lhs);
2417}
2418
2419void QQmlJSTypePropagator::generate_Sub(int lhs)
2420{
2421 generateBinaryArithmeticOperation(QSOperator::Op::Sub, lhs);
2422}
2423
2424void QQmlJSTypePropagator::generate_InitializeBlockDeadTemporalZone(int firstReg, int count)
2425{
2426 setAccumulator(m_typeResolver->literalType(m_typeResolver->emptyType()));
2427 for (int reg = firstReg, end = firstReg + count; reg < end; ++reg)
2428 setRegister(reg, m_typeResolver->literalType(m_typeResolver->emptyType()));
2429}
2430
2431void QQmlJSTypePropagator::generate_ThrowOnNullOrUndefined()
2432{
2434}
2435
2436void QQmlJSTypePropagator::generate_GetTemplateObject(int index)
2437{
2438 Q_UNUSED(index)
2440}
2441
2442QV4::Moth::ByteCodeHandler::Verdict
2443QQmlJSTypePropagator::startInstruction(QV4::Moth::Instr::Type type)
2444{
2445 if (m_state.jumpTargets.contains(currentInstructionOffset())) {
2446 if (m_state.skipInstructionsUntilNextJumpTarget) {
2447 // When re-surfacing from dead code, all registers are invalid.
2448 m_state.registers.clear();
2449 m_state.skipInstructionsUntilNextJumpTarget = false;
2450 }
2451 } else if (m_state.skipInstructionsUntilNextJumpTarget
2452 && !instructionManipulatesContext(type)) {
2453 return SkipInstruction;
2454 }
2455
2456 const int currentOffset = currentInstructionOffset();
2457
2458 // If we reach an instruction that is a target of a jump earlier, then we must check that the
2459 // register state at the origin matches the current state. If not, then we may have to inject
2460 // conversion code (communicated to code gen via m_state.typeConversions). For
2461 // example:
2462 //
2463 // function blah(x: number) { return x > 10 ? 10 : x}
2464 //
2465 // translates to a situation where in the "true" case, we load an integer into the accumulator
2466 // and in the else case a number (x). When the control flow is joined, the types don't match and
2467 // we need to make sure that the int is converted to a double just before the jump.
2468 for (auto originRegisterStateIt =
2469 m_jumpOriginRegisterStateByTargetInstructionOffset.constFind(currentOffset);
2470 originRegisterStateIt != m_jumpOriginRegisterStateByTargetInstructionOffset.constEnd()
2471 && originRegisterStateIt.key() == currentOffset;
2472 ++originRegisterStateIt) {
2473 auto stateToMerge = *originRegisterStateIt;
2474 for (auto registerIt = stateToMerge.registers.constBegin(),
2475 end = stateToMerge.registers.constEnd();
2476 registerIt != end; ++registerIt) {
2477 const int registerIndex = registerIt.key();
2478
2479 const VirtualRegister &newType = registerIt.value();
2480 if (!newType.content.isValid()) {
2481 addError(u"When reached from offset %1, %2 is undefined"_s
2482 .arg(QString::number(stateToMerge.originatingOffset),
2483 registerName(registerIndex)));
2484 return SkipInstruction;
2485 }
2486
2487 auto currentRegister = m_state.registers.find(registerIndex);
2488 if (currentRegister != m_state.registers.end())
2489 mergeRegister(registerIndex, newType, currentRegister.value());
2490 else
2491 mergeRegister(registerIndex, newType, newType);
2492 }
2493 }
2494
2495 return ProcessInstruction;
2496}
2497
2498bool QQmlJSTypePropagator::populatesAccumulator(QV4::Moth::Instr::Type instr) const
2499{
2500 switch (instr) {
2501 case QV4::Moth::Instr::Type::CheckException:
2502 case QV4::Moth::Instr::Type::CloneBlockContext:
2503 case QV4::Moth::Instr::Type::ConvertThisToObject:
2504 case QV4::Moth::Instr::Type::CreateCallContext:
2505 case QV4::Moth::Instr::Type::DeadTemporalZoneCheck:
2506 case QV4::Moth::Instr::Type::Debug:
2507 case QV4::Moth::Instr::Type::DeclareVar:
2508 case QV4::Moth::Instr::Type::IteratorClose:
2509 case QV4::Moth::Instr::Type::IteratorNext:
2510 case QV4::Moth::Instr::Type::IteratorNextForYieldStar:
2511 case QV4::Moth::Instr::Type::Jump:
2512 case QV4::Moth::Instr::Type::JumpFalse:
2513 case QV4::Moth::Instr::Type::JumpNoException:
2514 case QV4::Moth::Instr::Type::JumpNotUndefined:
2515 case QV4::Moth::Instr::Type::JumpTrue:
2516 case QV4::Moth::Instr::Type::MoveConst:
2517 case QV4::Moth::Instr::Type::MoveReg:
2518 case QV4::Moth::Instr::Type::MoveRegExp:
2519 case QV4::Moth::Instr::Type::PopContext:
2520 case QV4::Moth::Instr::Type::PushBlockContext:
2521 case QV4::Moth::Instr::Type::PushCatchContext:
2522 case QV4::Moth::Instr::Type::PushScriptContext:
2523 case QV4::Moth::Instr::Type::Resume:
2524 case QV4::Moth::Instr::Type::Ret:
2525 case QV4::Moth::Instr::Type::SetException:
2526 case QV4::Moth::Instr::Type::SetLookup:
2527 case QV4::Moth::Instr::Type::SetUnwindHandler:
2528 case QV4::Moth::Instr::Type::StoreElement:
2529 case QV4::Moth::Instr::Type::StoreLocal:
2530 case QV4::Moth::Instr::Type::StoreNameSloppy:
2531 case QV4::Moth::Instr::Type::StoreNameStrict:
2532 case QV4::Moth::Instr::Type::StoreProperty:
2533 case QV4::Moth::Instr::Type::StoreReg:
2534 case QV4::Moth::Instr::Type::StoreScopedLocal:
2535 case QV4::Moth::Instr::Type::StoreSuperProperty:
2536 case QV4::Moth::Instr::Type::ThrowException:
2537 case QV4::Moth::Instr::Type::ThrowOnNullOrUndefined:
2538 case QV4::Moth::Instr::Type::UnwindDispatch:
2539 case QV4::Moth::Instr::Type::UnwindToLabel:
2540 case QV4::Moth::Instr::Type::Yield:
2541 case QV4::Moth::Instr::Type::YieldStar:
2542 return false;
2543 case QV4::Moth::Instr::Type::Add:
2544 case QV4::Moth::Instr::Type::As:
2545 case QV4::Moth::Instr::Type::BitAnd:
2546 case QV4::Moth::Instr::Type::BitAndConst:
2547 case QV4::Moth::Instr::Type::BitOr:
2548 case QV4::Moth::Instr::Type::BitOrConst:
2549 case QV4::Moth::Instr::Type::BitXor:
2550 case QV4::Moth::Instr::Type::BitXorConst:
2551 case QV4::Moth::Instr::Type::CallGlobalLookup:
2552 case QV4::Moth::Instr::Type::CallName:
2553 case QV4::Moth::Instr::Type::CallPossiblyDirectEval:
2554 case QV4::Moth::Instr::Type::CallProperty:
2555 case QV4::Moth::Instr::Type::CallPropertyLookup:
2556 case QV4::Moth::Instr::Type::CallQmlContextPropertyLookup:
2557 case QV4::Moth::Instr::Type::CallValue:
2558 case QV4::Moth::Instr::Type::CallWithReceiver:
2559 case QV4::Moth::Instr::Type::CallWithSpread:
2560 case QV4::Moth::Instr::Type::CmpEq:
2561 case QV4::Moth::Instr::Type::CmpEqInt:
2562 case QV4::Moth::Instr::Type::CmpEqNull:
2563 case QV4::Moth::Instr::Type::CmpGe:
2564 case QV4::Moth::Instr::Type::CmpGt:
2565 case QV4::Moth::Instr::Type::CmpIn:
2566 case QV4::Moth::Instr::Type::CmpInstanceOf:
2567 case QV4::Moth::Instr::Type::CmpLe:
2568 case QV4::Moth::Instr::Type::CmpLt:
2569 case QV4::Moth::Instr::Type::CmpNe:
2570 case QV4::Moth::Instr::Type::CmpNeInt:
2571 case QV4::Moth::Instr::Type::CmpNeNull:
2572 case QV4::Moth::Instr::Type::CmpStrictEqual:
2573 case QV4::Moth::Instr::Type::CmpStrictNotEqual:
2574 case QV4::Moth::Instr::Type::Construct:
2575 case QV4::Moth::Instr::Type::ConstructWithSpread:
2576 case QV4::Moth::Instr::Type::CreateClass:
2577 case QV4::Moth::Instr::Type::CreateMappedArgumentsObject:
2578 case QV4::Moth::Instr::Type::CreateRestParameter:
2579 case QV4::Moth::Instr::Type::CreateUnmappedArgumentsObject:
2580 case QV4::Moth::Instr::Type::Decrement:
2581 case QV4::Moth::Instr::Type::DefineArray:
2582 case QV4::Moth::Instr::Type::DefineObjectLiteral:
2583 case QV4::Moth::Instr::Type::DeleteName:
2584 case QV4::Moth::Instr::Type::DeleteProperty:
2585 case QV4::Moth::Instr::Type::DestructureRestElement:
2586 case QV4::Moth::Instr::Type::Div:
2587 case QV4::Moth::Instr::Type::Exp:
2588 case QV4::Moth::Instr::Type::GetException:
2589 case QV4::Moth::Instr::Type::GetIterator:
2590 case QV4::Moth::Instr::Type::GetLookup:
2591 case QV4::Moth::Instr::Type::GetOptionalLookup:
2592 case QV4::Moth::Instr::Type::GetTemplateObject:
2593 case QV4::Moth::Instr::Type::Increment:
2594 case QV4::Moth::Instr::Type::InitializeBlockDeadTemporalZone:
2595 case QV4::Moth::Instr::Type::LoadClosure:
2596 case QV4::Moth::Instr::Type::LoadConst:
2597 case QV4::Moth::Instr::Type::LoadElement:
2598 case QV4::Moth::Instr::Type::LoadFalse:
2599 case QV4::Moth::Instr::Type::LoadGlobalLookup:
2600 case QV4::Moth::Instr::Type::LoadImport:
2601 case QV4::Moth::Instr::Type::LoadInt:
2602 case QV4::Moth::Instr::Type::LoadLocal:
2603 case QV4::Moth::Instr::Type::LoadName:
2604 case QV4::Moth::Instr::Type::LoadNull:
2605 case QV4::Moth::Instr::Type::LoadOptionalProperty:
2606 case QV4::Moth::Instr::Type::LoadProperty:
2607 case QV4::Moth::Instr::Type::LoadQmlContextPropertyLookup:
2608 case QV4::Moth::Instr::Type::LoadReg:
2609 case QV4::Moth::Instr::Type::LoadRuntimeString:
2610 case QV4::Moth::Instr::Type::LoadScopedLocal:
2611 case QV4::Moth::Instr::Type::LoadSuperConstructor:
2612 case QV4::Moth::Instr::Type::LoadSuperProperty:
2613 case QV4::Moth::Instr::Type::LoadTrue:
2614 case QV4::Moth::Instr::Type::LoadUndefined:
2615 case QV4::Moth::Instr::Type::LoadZero:
2616 case QV4::Moth::Instr::Type::Mod:
2617 case QV4::Moth::Instr::Type::Mul:
2618 case QV4::Moth::Instr::Type::PushWithContext:
2619 case QV4::Moth::Instr::Type::Shl:
2620 case QV4::Moth::Instr::Type::ShlConst:
2621 case QV4::Moth::Instr::Type::Shr:
2622 case QV4::Moth::Instr::Type::ShrConst:
2623 case QV4::Moth::Instr::Type::Sub:
2624 case QV4::Moth::Instr::Type::TailCall:
2625 case QV4::Moth::Instr::Type::ToObject:
2626 case QV4::Moth::Instr::Type::TypeofName:
2627 case QV4::Moth::Instr::Type::TypeofValue:
2628 case QV4::Moth::Instr::Type::UCompl:
2629 case QV4::Moth::Instr::Type::UMinus:
2630 case QV4::Moth::Instr::Type::UNot:
2631 case QV4::Moth::Instr::Type::UPlus:
2632 case QV4::Moth::Instr::Type::UShr:
2633 case QV4::Moth::Instr::Type::UShrConst:
2634 return true;
2635 default:
2636 Q_UNREACHABLE_RETURN(false);
2637 }
2638}
2639
2640bool QQmlJSTypePropagator::isNoop(QV4::Moth::Instr::Type instr) const
2641{
2642 switch (instr) {
2643 case QV4::Moth::Instr::Type::DeadTemporalZoneCheck:
2644 case QV4::Moth::Instr::Type::IteratorClose:
2645 return true;
2646 default:
2647 return false;
2648 }
2649}
2650
2651void QQmlJSTypePropagator::endInstruction(QV4::Moth::Instr::Type instr)
2652{
2653 InstructionAnnotation &currentInstruction = m_state.annotations[currentInstructionOffset()];
2654 currentInstruction.changedRegister = m_state.changedRegister();
2655 currentInstruction.changedRegisterIndex = m_state.changedRegisterIndex();
2656 currentInstruction.readRegisters = m_state.takeReadRegisters();
2657 currentInstruction.hasExternalSideEffects = m_state.hasExternalSideEffects();
2658 currentInstruction.hasInternalSideEffects = m_state.hasInternalSideEffects();
2659 currentInstruction.isRename = m_state.isRename();
2660
2661 bool populates = populatesAccumulator(instr);
2662 int changedIndex = m_state.changedRegisterIndex();
2663
2664 // TODO: Find a way to deal with instructions that change multiple registers
2665 if (instr != QV4::Moth::Instr::Type::InitializeBlockDeadTemporalZone) {
2666 Q_ASSERT((populates && changedIndex == Accumulator && m_state.accumulatorOut().isValid())
2667 || (!populates && changedIndex != Accumulator));
2668 }
2669
2670 if (!m_logger->currentFunctionHasCompileError() && !isNoop(instr)) {
2671 // An instruction needs to have side effects or write to another register or be a known
2672 // noop. Anything else is a problem.
2673 Q_ASSERT(m_state.hasInternalSideEffects() || changedIndex != InvalidRegister);
2674 }
2675
2676 if (changedIndex != InvalidRegister) {
2677 Q_ASSERT(m_logger->currentFunctionHasCompileError() || m_state.changedRegister().isValid());
2678 VirtualRegister &r = m_state.registers[changedIndex];
2679 r.content = m_state.changedRegister();
2680 r.canMove = false;
2681 r.affectedBySideEffects = m_state.isRename()
2682 && m_state.isRegisterAffectedBySideEffects(m_state.renameSourceRegisterIndex());
2683 m_state.clearChangedRegister();
2684 }
2685
2686 m_state.resetSideEffects();
2687 m_state.setIsRename(false);
2688 m_state.setReadRegisters(VirtualRegisters());
2689 m_state.instructionHasError = false;
2690}
2691
2692QQmlJSRegisterContent QQmlJSTypePropagator::propagateBinaryOperation(QSOperator::Op op, int lhs)
2693{
2694 auto lhsRegister = checkedInputRegister(lhs);
2695 if (!lhsRegister.isValid())
2696 return QQmlJSRegisterContent();
2697
2698 const QQmlJSRegisterContent type = m_typeResolver->typeForBinaryOperation(
2699 op, lhsRegister, m_state.accumulatorIn());
2700
2701 setAccumulator(type);
2702 return type;
2703}
2704
2705static bool deepCompare(const QQmlJSRegisterContent &a, const QQmlJSRegisterContent &b)
2706{
2707 if (!a.isValid() && !b.isValid())
2708 return true;
2709
2710 return a.containedType() == b.containedType()
2711 && a.variant() == b.variant()
2712 && deepCompare(a.scope(), b.scope());
2713}
2714
2715void QQmlJSTypePropagator::saveRegisterStateForJump(int offset)
2716{
2717 auto jumpToOffset = offset + nextInstructionOffset();
2718 ExpectedRegisterState state;
2719 state.registers = m_state.registers;
2720 state.originatingOffset = currentInstructionOffset();
2721 m_state.jumpTargets.insert(jumpToOffset);
2722 if (offset < 0) {
2723 // We're jumping backwards. We won't get to merge the register states in this pass anymore.
2724
2725 const auto registerStates =
2726 m_jumpOriginRegisterStateByTargetInstructionOffset.equal_range(jumpToOffset);
2727 for (auto it = registerStates.first; it != registerStates.second; ++it) {
2728 if (it->registers.keys() != state.registers.keys())
2729 continue;
2730
2731 const auto valuesIt = it->registers.values();
2732 const auto valuesState = state.registers.values();
2733
2734 bool different = false;
2735 for (qsizetype i = 0, end = valuesIt.size(); i != end; ++i) {
2736 const auto &valueIt = valuesIt[i];
2737 const auto &valueState = valuesState[i];
2738 if (valueIt.affectedBySideEffects != valueState.affectedBySideEffects
2739 || valueIt.canMove != valueState.canMove
2740 || valueIt.isShadowable != valueState.isShadowable
2741 || !deepCompare(valueIt.content, valueState.content)) {
2742 different = true;
2743 break;
2744 }
2745 }
2746
2747 if (!different)
2748 return; // We've seen the same register state before. No need for merging.
2749 }
2750
2751 // The register state at the target offset needs to be resolved in a further pass.
2752 m_state.needsMorePasses = true;
2753 }
2754 m_jumpOriginRegisterStateByTargetInstructionOffset.insert(jumpToOffset, state);
2755}
2756
2757QString QQmlJSTypePropagator::registerName(int registerIndex) const
2758{
2759 switch (registerIndex) {
2760 case InvalidRegister:
2761 return u"invalid"_s;
2762 case CurrentFunction:
2763 return u"function"_s;
2764 case Context:
2765 return u"context"_s;
2766 case Accumulator:
2767 return u"accumulator"_s;
2768 case This:
2769 return u"this"_s;
2770 case Argc:
2771 return u"argc"_s;
2772 case NewTarget:
2773 return u"newTarget"_s;
2774 default:
2775 break;
2776 }
2777
2778 if (isArgument(registerIndex))
2779 return u"argument %1"_s.arg(registerIndex - FirstArgument);
2780
2781 return u"temporary register %1"_s.arg(
2782 registerIndex - FirstArgument - m_function->argumentTypes.size());
2783}
2784
2785QQmlJSRegisterContent QQmlJSTypePropagator::checkedInputRegister(int reg)
2786{
2787 const auto regIt = m_state.registers.find(reg);
2788 if (regIt != m_state.registers.end())
2789 return regIt.value().content;
2790
2791 switch (reg) {
2792 case CurrentFunction:
2793 return m_typeResolver->syntheticType(m_typeResolver->functionType());
2794 case Context:
2795 return m_typeResolver->syntheticType(m_typeResolver->jsValueType());
2796 case Accumulator:
2797 addError(u"Type error: no value found in accumulator"_s);
2798 return {};
2799 case This:
2800 return m_function->qmlScope;
2801 case Argc:
2802 return m_typeResolver->syntheticType(m_typeResolver->int32Type());
2803 case NewTarget:
2804 // over-approximation: needed in qmllint to not crash on `eval()`-calls
2805 return m_typeResolver->syntheticType(m_typeResolver->varType());
2806 default:
2807 break;
2808 }
2809
2810 if (isArgument(reg))
2811 return argumentType(reg);
2812
2813 addError(u"Type error: could not infer the type of an expression"_s);
2814 return {};
2815}
2816
2817bool QQmlJSTypePropagator::canConvertFromTo(
2818 QQmlJSRegisterContent from, QQmlJSRegisterContent to)
2819{
2820 return m_typeResolver->canConvertFromTo(from, to);
2821}
2822
2823bool QQmlJSTypePropagator::canConvertFromTo(
2824 QQmlJSRegisterContent from, const QQmlJSScope::ConstPtr &to)
2825{
2826 return m_typeResolver->canConvertFromTo(from.containedType(), to);
2827}
2828
2829QT_END_NAMESPACE
Combined button and popup list for selecting options.
#define INSTR_PROLOGUE_NOT_IMPLEMENTED()
static bool deepCompare(const QQmlJSRegisterContent &a, const QQmlJSRegisterContent &b)
#define INSTR_PROLOGUE_NOT_IMPLEMENTED_IGNORE()
#define INSTR_PROLOGUE_NOT_IMPLEMENTED_POPULATES_ACC()