aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/qml/v4vm/qv4isel_masm.cpp
blob: 027e2c5e2f2204846a428bdc3a402ab4aa182c2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the V4VM module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qv4isel_masm_p.h"
#include "qv4runtime_p.h"
#include "qv4object_p.h"
#include "qv4functionobject_p.h"
#include "qv4regexpobject_p.h"
#include "qv4unwindhelper_p.h"
#include "qv4lookup_p.h"

#include <assembler/LinkBuffer.h>
#include <WTFStubs.h>

#include <iostream>
#include <cassert>

#if USE(UDIS86)
#  include <udis86.h>
#endif

using namespace QQmlJS;
using namespace QQmlJS::MASM;
using namespace QQmlJS::VM;

/* Platform/Calling convention/Architecture specific section */

#if CPU(X86_64)
static const Assembler::RegisterID calleeSavedRegisters[] = {
    // Not used: JSC::X86Registers::rbx,
    // Not used: JSC::X86Registers::r10,
    JSC::X86Registers::r12, // LocalsRegister
    // Not used: JSC::X86Registers::r13,
    JSC::X86Registers::r14 // ContextRegister
    // Not used: JSC::X86Registers::r15,
};
#endif

#if CPU(X86)
static const Assembler::RegisterID calleeSavedRegisters[] = {
    // Not used: JSC::X86Registers::ebx,
    JSC::X86Registers::esi, // ContextRegister
    JSC::X86Registers::edi  // LocalsRegister
};
#endif

#if CPU(ARM)
static const Assembler::RegisterID calleeSavedRegisters[] = {
    // ### FIXME: remove unused registers.
    // Keep these in reverse order and make sure to also edit the unwind program in
    // qv4unwindhelper_p-arm.h when changing this list.
    JSC::ARMRegisters::r12,
    JSC::ARMRegisters::r10,
    JSC::ARMRegisters::r9,
    JSC::ARMRegisters::r8,
    JSC::ARMRegisters::r7,
    JSC::ARMRegisters::r6,
    JSC::ARMRegisters::r5,
    JSC::ARMRegisters::r4
};
#endif

const int Assembler::calleeSavedRegisterCount = sizeof(calleeSavedRegisters) / sizeof(calleeSavedRegisters[0]);

/* End of platform/calling convention/architecture specific section */


const Assembler::VoidType Assembler::Void;

Assembler::Assembler(V4IR::Function* function, VM::Function *vmFunction, VM::ExecutionEngine *engine)
    : _function(function), _vmFunction(vmFunction), _engine(engine)
{
}

void Assembler::registerBlock(V4IR::BasicBlock* block)
{
    _addrs[block] = label();
}

void Assembler::jumpToBlock(V4IR::BasicBlock* current, V4IR::BasicBlock *target)
{
    if (current->index + 1 != target->index)
        _patches[target].append(jump());
}

void Assembler::addPatch(V4IR::BasicBlock* targetBlock, Jump targetJump)
{
    _patches[targetBlock].append(targetJump);
}

void Assembler::addPatch(DataLabelPtr patch, Label target)
{
    DataLabelPatch p;
    p.dataLabel = patch;
    p.target = target;
    _dataLabelPatches.append(p);
}

void Assembler::addPatch(DataLabelPtr patch, V4IR::BasicBlock *target)
{
    _labelPatches[target].append(patch);
}

Assembler::Pointer Assembler::loadTempAddress(RegisterID reg, V4IR::Temp *t)
{
    int32_t offset = 0;
    int scope = t->scope;
    VM::Function *f = _vmFunction;
    RegisterID context = ContextRegister;
    if (scope) {
        loadPtr(Address(ContextRegister, offsetof(ExecutionContext, outer)), ScratchRegister);
        --scope;
        f = f->outer;
        context = ScratchRegister;
        while (scope) {
            loadPtr(Address(context, offsetof(ExecutionContext, outer)), context);
            f = f->outer;
            --scope;
        }
    }
    if (t->index < 0) {
        const int arg = -t->index - 1;
        loadPtr(Address(context, offsetof(CallContext, arguments)), reg);
        offset = arg * sizeof(Value);
    } else if (t->index < f->locals.size()) {
        loadPtr(Address(context, offsetof(CallContext, locals)), reg);
        offset = t->index * sizeof(Value);
    } else {
        assert(t->scope == 0);
        const int arg = _function->maxNumberOfArguments + t->index - _function->locals.size() + 1;
        offset = - sizeof(Value) * (arg + 1);
        offset -= sizeof(void*) * calleeSavedRegisterCount;
        reg = LocalsRegister;
    }
    return Pointer(reg, offset);
}

template <typename Result, typename Source>
void Assembler::copyValue(Result result, Source source)
{
#ifdef VALUE_FITS_IN_REGISTER
    // Use ReturnValueRegister as "scratch" register because loadArgument
    // and storeArgument are functions that may need a scratch register themselves.
    loadArgument(source, ReturnValueRegister);
    storeArgument(ReturnValueRegister, result);
#else
    loadDouble(source, FPGpr0);
    storeDouble(FPGpr0, result);
#endif
}

template <typename Result>
void Assembler::copyValue(Result result, V4IR::Expr* source)
{
#ifdef VALUE_FITS_IN_REGISTER
    // Use ReturnValueRegister as "scratch" register because loadArgument
    // and storeArgument are functions that may need a scratch register themselves.
    loadArgument(source, ReturnValueRegister);
    storeArgument(ReturnValueRegister, result);
#else
    if (V4IR::Temp *temp = source->asTemp()) {
        loadDouble(temp, FPGpr0);
        storeDouble(FPGpr0, result);
    } else if (V4IR::Const *c = source->asConst()) {
        VM::Value v = convertToValue(c);
        storeValue(v, result);
    } else {
        assert(! "not implemented");
    }
#endif
}


void Assembler::storeValue(VM::Value value, V4IR::Temp* destination)
{
    Address addr = loadTempAddress(ScratchRegister, destination);
    storeValue(value, addr);
}

void Assembler::enterStandardStackFrame(int locals)
{
    platformEnterStandardStackFrame();

    // ### FIXME: Handle through calleeSavedRegisters mechanism
    // or eliminate StackFrameRegister altogether.
    push(StackFrameRegister);
    move(StackPointerRegister, StackFrameRegister);

    // space for the locals and callee saved registers
    int32_t frameSize = locals * sizeof(QQmlJS::VM::Value) + sizeof(void*) * calleeSavedRegisterCount;

#if CPU(X86) || CPU(X86_64)
    frameSize = (frameSize + 15) & ~15; // align on 16 byte boundaries for MMX
#endif
    subPtr(TrustedImm32(frameSize), StackPointerRegister);

    for (int i = 0; i < calleeSavedRegisterCount; ++i)
        storePtr(calleeSavedRegisters[i], Address(StackFrameRegister, -(i + 1) * sizeof(void*)));

    move(StackFrameRegister, LocalsRegister);
}

void Assembler::leaveStandardStackFrame(int locals)
{
    // restore the callee saved registers
    for (int i = calleeSavedRegisterCount - 1; i >= 0; --i)
        loadPtr(Address(StackFrameRegister, -(i + 1) * sizeof(void*)), calleeSavedRegisters[i]);

    // space for the locals and the callee saved registers
    int32_t frameSize = locals * sizeof(QQmlJS::VM::Value) + sizeof(void*) * calleeSavedRegisterCount;
#if CPU(X86) || CPU(X86_64)
    frameSize = (frameSize + 15) & ~15; // align on 16 byte boundaries for MMX
#endif
    // Work around bug in ARMv7Assembler.h where add32(imm, sp, sp) doesn't
    // work well for large immediates.
#if CPU(ARM_THUMB2)
    move(TrustedImm32(frameSize), Assembler::ScratchRegister);
    add32(Assembler::ScratchRegister, StackPointerRegister);
#else
    addPtr(TrustedImm32(frameSize), StackPointerRegister);
#endif

    pop(StackFrameRegister);
    platformLeaveStandardStackFrame();
}



#define OP(op) \
    { isel_stringIfy(op), op, 0, 0 }

#define INLINE_OP(op, memOp, immOp) \
    { isel_stringIfy(op), op, memOp, immOp }

#define NULL_OP \
    { 0, 0, 0, 0 }

const Assembler::BinaryOperationInfo Assembler::binaryOperations[QQmlJS::V4IR::LastAluOp + 1] = {
    NULL_OP, // OpInvalid
    NULL_OP, // OpIfTrue
    NULL_OP, // OpNot
    NULL_OP, // OpUMinus
    NULL_OP, // OpUPlus
    NULL_OP, // OpCompl
    NULL_OP, // OpIncrement
    NULL_OP, // OpDecrement

    INLINE_OP(__qmljs_bit_and, &Assembler::inline_and32, &Assembler::inline_and32), // OpBitAnd
    INLINE_OP(__qmljs_bit_or, &Assembler::inline_or32, &Assembler::inline_or32), // OpBitOr
    INLINE_OP(__qmljs_bit_xor, &Assembler::inline_xor32, &Assembler::inline_xor32), // OpBitXor

    INLINE_OP(__qmljs_add, &Assembler::inline_add32, &Assembler::inline_add32), // OpAdd
    INLINE_OP(__qmljs_sub, &Assembler::inline_sub32, &Assembler::inline_sub32), // OpSub
    INLINE_OP(__qmljs_mul, &Assembler::inline_mul32, &Assembler::inline_mul32), // OpMul

    OP(__qmljs_div), // OpDiv
    OP(__qmljs_mod), // OpMod

    INLINE_OP(__qmljs_shl, &Assembler::inline_shl32, &Assembler::inline_shl32), // OpLShift
    INLINE_OP(__qmljs_shr, &Assembler::inline_shr32, &Assembler::inline_shr32), // OpRShift
    INLINE_OP(__qmljs_ushr, &Assembler::inline_ushr32, &Assembler::inline_ushr32), // OpURShift

    OP(__qmljs_gt), // OpGt
    OP(__qmljs_lt), // OpLt
    OP(__qmljs_ge), // OpGe
    OP(__qmljs_le), // OpLe
    OP(__qmljs_eq), // OpEqual
    OP(__qmljs_ne), // OpNotEqual
    OP(__qmljs_se), // OpStrictEqual
    OP(__qmljs_sne), // OpStrictNotEqual

    OP(__qmljs_instanceof), // OpInstanceof
    OP(__qmljs_in), // OpIn

    NULL_OP, // OpAnd
    NULL_OP // OpOr
};

void Assembler::generateBinOp(V4IR::AluOp operation, V4IR::Temp* target, V4IR::Temp *left, V4IR::Temp *right)
{
    const BinaryOperationInfo& info = binaryOperations[operation];
    if (!info.fallbackImplementation) {
        assert(!"unreachable");
        return;
    }

    Value leftConst = Value::undefinedValue();
    Value rightConst = Value::undefinedValue();

    bool canDoInline = info.inlineMemRegOp && info.inlineImmRegOp;

    if (canDoInline) {
        if (left->asConst()) {
            leftConst = convertToValue(left->asConst());
            canDoInline = canDoInline && leftConst.tryIntegerConversion();
        }
        if (right->asConst()) {
            rightConst = convertToValue(right->asConst());
            canDoInline = canDoInline && rightConst.tryIntegerConversion();
        }
    }

    Jump binOpFinished;

    if (canDoInline) {

        Jump leftTypeCheck;
        if (left->asTemp()) {
            Address typeAddress = loadTempAddress(ScratchRegister, left->asTemp());
            typeAddress.offset += offsetof(VM::Value, tag);
            leftTypeCheck = branch32(NotEqual, typeAddress, TrustedImm32(VM::Value::_Integer_Type));
        }

        Jump rightTypeCheck;
        if (right->asTemp()) {
            Address typeAddress = loadTempAddress(ScratchRegister, right->asTemp());
            typeAddress.offset += offsetof(VM::Value, tag);
            rightTypeCheck = branch32(NotEqual, typeAddress, TrustedImm32(VM::Value::_Integer_Type));
        }

        if (left->asTemp()) {
            Address leftValue = loadTempAddress(ScratchRegister, left->asTemp());
            leftValue.offset += offsetof(VM::Value, int_32);
            load32(leftValue, IntegerOpRegister);
        } else { // left->asConst()
            move(TrustedImm32(leftConst.integerValue()), IntegerOpRegister);
        }

        Jump overflowCheck;

        if (right->asTemp()) {
            Address rightValue = loadTempAddress(ScratchRegister, right->asTemp());
            rightValue.offset += offsetof(VM::Value, int_32);

            overflowCheck = (this->*info.inlineMemRegOp)(rightValue, IntegerOpRegister);
        } else { // right->asConst()
            overflowCheck = (this->*info.inlineImmRegOp)(TrustedImm32(rightConst.integerValue()), IntegerOpRegister);
        }

        Address resultAddr = loadTempAddress(ScratchRegister, target);
        Address resultValueAddr = resultAddr;
        resultValueAddr.offset += offsetof(VM::Value, int_32);
        store32(IntegerOpRegister, resultValueAddr);

        Address resultTypeAddr = resultAddr;
        resultTypeAddr.offset += offsetof(VM::Value, tag);
        store32(TrustedImm32(VM::Value::_Integer_Type), resultTypeAddr);

        binOpFinished = jump();

        if (leftTypeCheck.isSet())
            leftTypeCheck.link(this);
        if (rightTypeCheck.isSet())
            rightTypeCheck.link(this);
        if (overflowCheck.isSet())
            overflowCheck.link(this);
    }

    // Fallback
    generateFunctionCallImp(Assembler::Void, info.name, info.fallbackImplementation, ContextRegister,
                            Assembler::PointerToValue(target), Assembler::Reference(left), Assembler::Reference(right));

    if (binOpFinished.isSet())
        binOpFinished.link(this);
}
#if OS(LINUX)
static void printDisassembledOutputWithCalls(const char* output, const QHash<void*, const char*>& functions,
                                             const QVector<String*> &identifiers)
{
    QByteArray processedOutput(output);
    for (QHash<void*, const char*>::ConstIterator it = functions.begin(), end = functions.end();
         it != end; ++it) {
        QByteArray ptrString = QByteArray::number(quintptr(it.key()), 16);
        ptrString.prepend("0x");
        processedOutput = processedOutput.replace(ptrString, it.value());
    }
    for (QVector<String*>::ConstIterator it = identifiers.begin(), end = identifiers.end();
         it != end; ++it) {
        QByteArray ptrString = QByteArray::number(quintptr(*it), 16);
        ptrString.prepend("0x");
        QByteArray replacement = "\"" + (*it)->toQString().toUtf8() + "\"";
        processedOutput = processedOutput.replace(ptrString, replacement);
    }
    fprintf(stderr, "%s\n", processedOutput.constData());
}
#endif

void Assembler::link(VM::Function *vmFunc)
{
    Label endOfCode = label();
#ifdef Q_PROCESSOR_ARM
    // Let the ARM exception table follow right after that
    for (int i = 0, nops = UnwindHelper::unwindInfoSize() / 2; i < nops; ++i)
        nop();
#endif

    {
        QHashIterator<V4IR::BasicBlock *, QVector<Jump> > it(_patches);
        while (it.hasNext()) {
            it.next();
            V4IR::BasicBlock *block = it.key();
            Label target = _addrs.value(block);
            assert(target.isSet());
            foreach (Jump jump, it.value())
                jump.linkTo(target, this);
        }
    }

    JSC::JSGlobalData dummy(_engine->executableAllocator);
    JSC::LinkBuffer linkBuffer(dummy, this, 0);
    vmFunc->codeSize = linkBuffer.offsetOf(endOfCode);

    QHash<void*, const char*> functions;
    foreach (CallToLink ctl, _callsToLink) {
        linkBuffer.link(ctl.call, ctl.externalFunction);
        functions[ctl.externalFunction.value()] = ctl.functionName;
    }

    foreach (const DataLabelPatch &p, _dataLabelPatches)
        linkBuffer.patch(p.dataLabel, linkBuffer.locationOf(p.target));

    {
        QHashIterator<V4IR::BasicBlock *, QVector<DataLabelPtr> > it(_labelPatches);
        while (it.hasNext()) {
            it.next();
            V4IR::BasicBlock *block = it.key();
            Label target = _addrs.value(block);
            assert(target.isSet());
            foreach (DataLabelPtr label, it.value())
                linkBuffer.patch(label, linkBuffer.locationOf(target));
        }
    }

#ifdef Q_PROCESSOR_ARM
    UnwindHelper::writeARMUnwindInfo(linkBuffer.debugAddress(), linkBuffer.offsetOf(endOfCode));
#endif

    static bool showCode = !qgetenv("SHOW_CODE").isNull();
    if (showCode) {
#if OS(LINUX)
        char* disasmOutput = 0;
        size_t disasmLength = 0;
        FILE* disasmStream = open_memstream(&disasmOutput, &disasmLength);
        WTF::setDataFile(disasmStream);
#endif

        QByteArray name = _function->name->toUtf8();
        if (name.isEmpty()) {
            name = QByteArray::number(quintptr(_function), 16);
            name.prepend("IR::Function(0x");
            name.append(")");
        }
        vmFunc->codeRef = linkBuffer.finalizeCodeWithDisassembly("%s", name.data());

        WTF::setDataFile(stderr);
#if OS(LINUX)
        fclose(disasmStream);
#if CPU(X86) || CPU(X86_64)
        QHash<void*, String*> idents;
        printDisassembledOutputWithCalls(disasmOutput, functions, _vmFunction->identifiers);
#endif
        free(disasmOutput);
#endif
    } else {
        vmFunc->codeRef = linkBuffer.finalizeCodeWithoutDisassembly();
    }

    vmFunc->code = (Value (*)(VM::ExecutionContext *, const uchar *)) vmFunc->codeRef.code().executableAddress();
}

InstructionSelection::InstructionSelection(VM::ExecutionEngine *engine, V4IR::Module *module)
    : EvalInstructionSelection(engine, module)
    , _block(0)
    , _function(0)
    , _vmFunction(0)
    , _as(0)
{
}

InstructionSelection::~InstructionSelection()
{
    delete _as;
}

void InstructionSelection::run(VM::Function *vmFunction, V4IR::Function *function)
{
    QVector<Lookup> lookups;
    QSet<V4IR::BasicBlock*> reentryBlocks;
    qSwap(_function, function);
    qSwap(_vmFunction, vmFunction);
    qSwap(_lookups, lookups);
    qSwap(_reentryBlocks, reentryBlocks);
    Assembler* oldAssembler = _as;
    _as = new Assembler(_function, _vmFunction, engine());

    int locals = (_function->tempCount - _function->locals.size() + _function->maxNumberOfArguments) + 1;
    locals = (locals + 1) & ~1;
    _as->enterStandardStackFrame(locals);

    int contextPointer = 0;
#ifndef VALUE_FITS_IN_REGISTER
    // When the return VM value doesn't fit into a register, then
    // the caller provides a pointer for storage as first argument.
    // That shifts the index the context pointer argument by one.
    contextPointer++;
#endif

#ifdef ARGUMENTS_IN_REGISTERS
    _as->move(_as->registerForArgument(contextPointer), Assembler::ContextRegister);
#else
    _as->loadPtr(addressForArgument(contextPointer), Assembler::ContextRegister);
#endif

    foreach (V4IR::BasicBlock *block, _function->basicBlocks) {
        _block = block;
        _as->registerBlock(_block);

        if (_reentryBlocks.contains(_block)) {
            _as->enterStandardStackFrame(/*locals*/0);
#ifdef ARGUMENTS_IN_REGISTERS
            _as->move(Assembler::registerForArgument(0), Assembler::ContextRegister);
            _as->move(Assembler::registerForArgument(1), Assembler::LocalsRegister);
#else
            _as->loadPtr(addressForArgument(0), Assembler::ContextRegister);
            _as->loadPtr(addressForArgument(1), Assembler::LocalsRegister);
#endif
        }

        foreach (V4IR::Stmt *s, block->statements) {
            s->accept(this);
        }
    }

    _as->leaveStandardStackFrame(locals);
#ifndef ARGUMENTS_IN_REGISTERS
    // Emulate ret(n) instruction
    // Pop off return address into scratch register ...
    _as->pop(Assembler::ScratchRegister);
    // ... and overwrite the invisible argument with
    // the return address.
    _as->poke(Assembler::ScratchRegister);
#endif
    _as->ret();

    _as->link(_vmFunction);

    if (_lookups.size()) {
        _vmFunction->lookups = new Lookup[_lookups.size()];
        memcpy(_vmFunction->lookups, _lookups.constData(), _lookups.size()*sizeof(Lookup));
    }

    UnwindHelper::registerFunction(_vmFunction);

    qSwap(_vmFunction, vmFunction);
    qSwap(_function, function);
    qSwap(_lookups, lookups);
    qSwap(_reentryBlocks, reentryBlocks);
    delete _as;
    _as = oldAssembler;
}

void InstructionSelection::callBuiltinInvalid(V4IR::Name *func, V4IR::ExprList *args, V4IR::Temp *result)
{
    int argc = prepareVariableArguments(args);
    VM::String *s = identifier(*func->id);

    if (useFastLookups && func->global) {
        uint index = addGlobalLookup(s);
        generateFunctionCall(Assembler::Void, __qmljs_call_global_lookup,
                             Assembler::ContextRegister, Assembler::PointerToValue(result),
                             Assembler::TrustedImm32(index),
                             baseAddressForCallArguments(),
                             Assembler::TrustedImm32(argc));
    } else {
        generateFunctionCall(Assembler::Void, __qmljs_call_activation_property,
                             Assembler::ContextRegister, Assembler::PointerToValue(result),
                             s,
                             baseAddressForCallArguments(),
                             Assembler::TrustedImm32(argc));
    }
}

void InstructionSelection::callBuiltinTypeofMember(V4IR::Temp *base, const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_typeof_member, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::Reference(base), identifier(name));
}

void InstructionSelection::callBuiltinTypeofSubscript(V4IR::Temp *base, V4IR::Temp *index, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_typeof_element,
            Assembler::ContextRegister, Assembler::PointerToValue(result),
            Assembler::Reference(base), Assembler::Reference(index));
}

void InstructionSelection::callBuiltinTypeofName(const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_typeof_name, Assembler::ContextRegister, Assembler::PointerToValue(result), identifier(name));
}

void InstructionSelection::callBuiltinTypeofValue(V4IR::Temp *value, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_typeof, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::Reference(value));
}

void InstructionSelection::callBuiltinDeleteMember(V4IR::Temp *base, const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_delete_member, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::Reference(base), identifier(name));
}

void InstructionSelection::callBuiltinDeleteSubscript(V4IR::Temp *base, V4IR::Temp *index, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_delete_subscript, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::Reference(base), Assembler::Reference(index));
}

void InstructionSelection::callBuiltinDeleteName(const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_delete_name, Assembler::ContextRegister, Assembler::PointerToValue(result), identifier(name));
}

void InstructionSelection::callBuiltinDeleteValue(V4IR::Temp *result)
{
    _as->storeValue(Value::fromBoolean(false), result);
}

void InstructionSelection::callBuiltinPostIncrementMember(V4IR::Temp *base, const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_increment_member, Assembler::ContextRegister,
                         Assembler::PointerToValue(result), Assembler::PointerToValue(base), identifier(name));
}

void InstructionSelection::callBuiltinPostIncrementSubscript(V4IR::Temp *base, V4IR::Temp *index, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_increment_element, Assembler::ContextRegister,
                         Assembler::PointerToValue(result), Assembler::Reference(base), Assembler::PointerToValue(index));
}

void InstructionSelection::callBuiltinPostIncrementName(const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_increment_name, Assembler::ContextRegister,
                         Assembler::PointerToValue(result), identifier(name));
}

void InstructionSelection::callBuiltinPostIncrementValue(V4IR::Temp *value, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_increment,
                         Assembler::PointerToValue(result), Assembler::PointerToValue(value));
}

void InstructionSelection::callBuiltinPostDecrementMember(V4IR::Temp *base, const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_decrement_member, Assembler::ContextRegister,
                         Assembler::PointerToValue(result), Assembler::Reference(base), identifier(name));
}

void InstructionSelection::callBuiltinPostDecrementSubscript(V4IR::Temp *base, V4IR::Temp *index, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_decrement_element, Assembler::ContextRegister,
                         Assembler::PointerToValue(result), Assembler::Reference(base),
                         Assembler::Reference(index));
}

void InstructionSelection::callBuiltinPostDecrementName(const QString &name, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_decrement_name, Assembler::ContextRegister,
                         Assembler::PointerToValue(result), identifier(name));
}

void InstructionSelection::callBuiltinPostDecrementValue(V4IR::Temp *value, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_post_decrement,
                         Assembler::PointerToValue(result), Assembler::PointerToValue(value));
}

void InstructionSelection::callBuiltinThrow(V4IR::Temp *arg)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_throw, Assembler::ContextRegister, Assembler::Reference(arg));
}

typedef void *(*MiddleOfFunctionEntryPoint(ExecutionContext *, void *localsPtr));
static void *tryWrapper(ExecutionContext *context, void *localsPtr, MiddleOfFunctionEntryPoint tryBody, MiddleOfFunctionEntryPoint catchBody,
                        VM::String *exceptionVarName, Value *exceptionVar)
{
    *exceptionVar = Value::undefinedValue();
    void *addressToContinueAt = 0;
    try {
        addressToContinueAt = tryBody(context, localsPtr);
    } catch (Exception& ex) {
        ex.accept(context);
        *exceptionVar = ex.value();
        try {
            ExecutionContext *catchContext = __qmljs_builtin_push_catch_scope(exceptionVarName, ex.value(), context);
            addressToContinueAt = catchBody(catchContext, localsPtr);
            context = __qmljs_builtin_pop_scope(catchContext);
        } catch (Exception& ex) {
            *exceptionVar = ex.value();
            ex.accept(context);
            addressToContinueAt = catchBody(context, localsPtr);
        }
    }
    return addressToContinueAt;
}

void InstructionSelection::visitTry(V4IR::Try *t)
{
    // Call tryWrapper, which is going to re-enter the same function at the address of the try block. At then end
    // of the try function the JIT code will return with the address of the sub-sequent instruction, which tryWrapper
    // returns and to which we jump to.

    _reentryBlocks.insert(t->tryBlock);
    _reentryBlocks.insert(t->catchBlock);

    generateFunctionCall(Assembler::ReturnValueRegister, tryWrapper, Assembler::ContextRegister, Assembler::LocalsRegister,
                         Assembler::ReentryBlock(t->tryBlock), Assembler::ReentryBlock(t->catchBlock),
                         identifier(t->exceptionVarName), Assembler::PointerToValue(t->exceptionVar));
    _as->jump(Assembler::ReturnValueRegister);
}

void InstructionSelection::callBuiltinFinishTry()
{
    // This assumes that we're in code that was called by tryWrapper, so we return to try wrapper
    // with the address that we'd like to continue at, which is right after the ret below.
    Assembler::DataLabelPtr continuation = _as->moveWithPatch(Assembler::TrustedImmPtr(0), Assembler::ReturnValueRegister);
    _as->leaveStandardStackFrame(/*locals*/0);
    _as->ret();
    _as->addPatch(continuation, _as->label());
}

void InstructionSelection::callBuiltinForeachIteratorObject(V4IR::Temp *arg, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_foreach_iterator_object, Assembler::ContextRegister, Assembler::PointerToValue(result), Assembler::Reference(arg), Assembler::ContextRegister);
}

void InstructionSelection::callBuiltinForeachNextPropertyname(V4IR::Temp *arg, V4IR::Temp *result)
{
    generateFunctionCall(Assembler::Void, __qmljs_foreach_next_property_name, Assembler::PointerToValue(result), Assembler::Reference(arg));
}

void InstructionSelection::callBuiltinPushWithScope(V4IR::Temp *arg)
{
    generateFunctionCall(Assembler::ContextRegister, __qmljs_builtin_push_with_scope, Assembler::Reference(arg), Assembler::ContextRegister);
}

void InstructionSelection::callBuiltinPopScope()
{
    generateFunctionCall(Assembler::ContextRegister, __qmljs_builtin_pop_scope, Assembler::ContextRegister);
}

void InstructionSelection::callBuiltinDeclareVar(bool deletable, const QString &name)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_declare_var, Assembler::ContextRegister,
                         Assembler::TrustedImm32(deletable), identifier(name));
}

void InstructionSelection::callBuiltinDefineGetterSetter(V4IR::Temp *object, const QString &name, V4IR::Temp *getter, V4IR::Temp *setter)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_define_getter_setter, Assembler::ContextRegister,
                         Assembler::Reference(object), identifier(name), Assembler::PointerToValue(getter), Assembler::PointerToValue(setter));
}

void InstructionSelection::callBuiltinDefineProperty(V4IR::Temp *object, const QString &name, V4IR::Temp *value)
{
    generateFunctionCall(Assembler::Void, __qmljs_builtin_define_property, Assembler::ContextRegister,
                         Assembler::Reference(object), identifier(name), Assembler::PointerToValue(value));
}

void InstructionSelection::callBuiltinDefineArray(V4IR::Temp *result, V4IR::ExprList *args)
{
    int length = prepareVariableArguments(args);
    generateFunctionCall(Assembler::Void, __qmljs_builtin_define_array, Assembler::ContextRegister,
                         Assembler::PointerToValue(result),
                         baseAddressForCallArguments(), Assembler::TrustedImm32(length));
}

void InstructionSelection::callValue(V4IR::Temp *value, V4IR::ExprList *args, V4IR::Temp *result)
{
    int argc = prepareVariableArguments(args);
    V4IR::Temp* thisObject = 0;
    generateFunctionCall(Assembler::Void, __qmljs_call_value, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::PointerToValue(thisObject),
            Assembler::Reference(value), baseAddressForCallArguments(), Assembler::TrustedImm32(argc));
}

void InstructionSelection::loadThisObject(V4IR::Temp *temp)
{
#if defined(VALUE_FITS_IN_REGISTER)
    _as->loadPtr(Pointer(Assembler::ContextRegister, offsetof(ExecutionContext, thisObject)), Assembler::ReturnValueRegister);
    _as->storeArgument(Assembler::ReturnValueRegister, temp);
#else
    _as->copyValue(temp, Pointer(Assembler::ContextRegister, offsetof(ExecutionContext, thisObject)));
#endif
}

void InstructionSelection::loadConst(V4IR::Const *sourceConst, V4IR::Temp *targetTemp)
{
    _as->storeValue(convertToValue(sourceConst), targetTemp);
}

void InstructionSelection::loadString(const QString &str, V4IR::Temp *targetTemp)
{
    Value v = Value::fromString(identifier(str));
    _as->storeValue(v, targetTemp);
}

void InstructionSelection::loadRegexp(V4IR::RegExp *sourceRegexp, V4IR::Temp *targetTemp)
{
    Value v = Value::fromObject(engine()->newRegExpObject(*sourceRegexp->value,
                                                          sourceRegexp->flags));
    _vmFunction->generatedValues.append(v);
    _as->storeValue(v, targetTemp);
}

void InstructionSelection::getActivationProperty(const V4IR::Name *name, V4IR::Temp *temp)
{
    String *propertyName = identifier(*name->id);
    if (useFastLookups && name->global) {
        uint index = addGlobalLookup(propertyName);
        generateFunctionCall(Assembler::Void, __qmljs_get_global_lookup, Assembler::ContextRegister, Assembler::PointerToValue(temp),
                             Assembler::TrustedImm32(index));
        return;
    }
    generateFunctionCall(Assembler::Void, __qmljs_get_activation_property, Assembler::ContextRegister, Assembler::PointerToValue(temp), propertyName);
}

void InstructionSelection::setActivationProperty(V4IR::Temp *source, const QString &targetName)
{
    String *propertyName = identifier(targetName);
    generateFunctionCall(Assembler::Void, __qmljs_set_activation_property,
            Assembler::ContextRegister, propertyName, Assembler::Reference(source));
}

void InstructionSelection::initClosure(V4IR::Closure *closure, V4IR::Temp *target)
{
    VM::Function *vmFunc = vmFunction(closure->value);
    assert(vmFunc);
    generateFunctionCall(Assembler::Void, __qmljs_init_closure, Assembler::ContextRegister, Assembler::PointerToValue(target), Assembler::TrustedImmPtr(vmFunc));
}

void InstructionSelection::getProperty(V4IR::Temp *base, const QString &name, V4IR::Temp *target)
{
    if (useFastLookups) {
        VM::String *s = identifier(name);
        uint index = addLookup(s);
        generateFunctionCall(Assembler::Void, __qmljs_get_property_lookup, Assembler::ContextRegister, Assembler::PointerToValue(target),
                             Assembler::Reference(base), Assembler::TrustedImm32(index));
    } else {
        generateFunctionCall(Assembler::Void, __qmljs_get_property, Assembler::ContextRegister, Assembler::PointerToValue(target),
                             Assembler::Reference(base), identifier(name));
    }
}

void InstructionSelection::setProperty(V4IR::Temp *source, V4IR::Temp *targetBase, const QString &targetName)
{
    if (useFastLookups) {
        VM::String *s = identifier(targetName);
        uint index = addLookup(s);
        generateFunctionCall(Assembler::Void, __qmljs_set_property_lookup,
                Assembler::ContextRegister, Assembler::Reference(targetBase),
                Assembler::TrustedImm32(index), Assembler::Reference(source));
    } else {
        generateFunctionCall(Assembler::Void, __qmljs_set_property, Assembler::ContextRegister,
                Assembler::Reference(targetBase),
                identifier(targetName), Assembler::Reference(source));
    }
}

void InstructionSelection::getElement(V4IR::Temp *base, V4IR::Temp *index, V4IR::Temp *target)
{
    generateFunctionCall(Assembler::Void, __qmljs_get_element, Assembler::ContextRegister,
                         Assembler::PointerToValue(target), Assembler::Reference(base),
                         Assembler::Reference(index));
}

void InstructionSelection::setElement(V4IR::Temp *source, V4IR::Temp *targetBase, V4IR::Temp *targetIndex)
{
    generateFunctionCall(Assembler::Void, __qmljs_set_element, Assembler::ContextRegister,
                         Assembler::Reference(targetBase), Assembler::Reference(targetIndex),
                         Assembler::Reference(source));
}

void InstructionSelection::copyValue(V4IR::Temp *sourceTemp, V4IR::Temp *targetTemp)
{
    _as->copyValue(targetTemp, sourceTemp);
}

#define setOp(op, opName, operation) \
    do { op = operation; opName = isel_stringIfy(operation); } while (0)

void InstructionSelection::unop(V4IR::AluOp oper, V4IR::Temp *sourceTemp, V4IR::Temp *targetTemp)
{
    VM::UnaryOpName op = 0;
    const char *opName = 0;
    switch (oper) {
    case V4IR::OpIfTrue: assert(!"unreachable"); break;
    case V4IR::OpNot: setOp(op, opName, __qmljs_not); break;
    case V4IR::OpUMinus: setOp(op, opName, __qmljs_uminus); break;
    case V4IR::OpUPlus: setOp(op, opName, __qmljs_uplus); break;
    case V4IR::OpCompl: setOp(op, opName, __qmljs_compl); break;
    case V4IR::OpIncrement: setOp(op, opName, __qmljs_increment); break;
    case V4IR::OpDecrement: setOp(op, opName, __qmljs_decrement); break;
    default: assert(!"unreachable"); break;
    } // switch

    if (op)
        _as->generateFunctionCallImp(Assembler::Void, opName, op, Assembler::PointerToValue(targetTemp),
                                     Assembler::Reference(sourceTemp));
}

void InstructionSelection::binop(V4IR::AluOp oper, V4IR::Temp *leftSource, V4IR::Temp *rightSource, V4IR::Temp *target)
{
    _as->generateBinOp(oper, target, leftSource, rightSource);
}

void InstructionSelection::inplaceNameOp(V4IR::AluOp oper, V4IR::Temp *rightSource, const QString &targetName)
{
    VM::InplaceBinOpName op = 0;
    const char *opName = 0;
    switch (oper) {
    case V4IR::OpBitAnd: setOp(op, opName, __qmljs_inplace_bit_and_name); break;
    case V4IR::OpBitOr: setOp(op, opName, __qmljs_inplace_bit_or_name); break;
    case V4IR::OpBitXor: setOp(op, opName, __qmljs_inplace_bit_xor_name); break;
    case V4IR::OpAdd: setOp(op, opName, __qmljs_inplace_add_name); break;
    case V4IR::OpSub: setOp(op, opName, __qmljs_inplace_sub_name); break;
    case V4IR::OpMul: setOp(op, opName, __qmljs_inplace_mul_name); break;
    case V4IR::OpDiv: setOp(op, opName, __qmljs_inplace_div_name); break;
    case V4IR::OpMod: setOp(op, opName, __qmljs_inplace_mod_name); break;
    case V4IR::OpLShift: setOp(op, opName, __qmljs_inplace_shl_name); break;
    case V4IR::OpRShift: setOp(op, opName, __qmljs_inplace_shr_name); break;
    case V4IR::OpURShift: setOp(op, opName, __qmljs_inplace_ushr_name); break;
    default:
        Q_UNREACHABLE();
        break;
    }
    if (op) {
        _as->generateFunctionCallImp(Assembler::Void, opName, op, Assembler::ContextRegister,
                identifier(targetName), Assembler::Reference(rightSource));
    }
}

void InstructionSelection::inplaceElementOp(V4IR::AluOp oper, V4IR::Temp *source, V4IR::Temp *targetBaseTemp, V4IR::Temp *targetIndexTemp)
{
    VM::InplaceBinOpElement op = 0;
    const char *opName = 0;
    switch (oper) {
    case V4IR::OpBitAnd: setOp(op, opName, __qmljs_inplace_bit_and_element); break;
    case V4IR::OpBitOr: setOp(op, opName, __qmljs_inplace_bit_or_element); break;
    case V4IR::OpBitXor: setOp(op, opName, __qmljs_inplace_bit_xor_element); break;
    case V4IR::OpAdd: setOp(op, opName, __qmljs_inplace_add_element); break;
    case V4IR::OpSub: setOp(op, opName, __qmljs_inplace_sub_element); break;
    case V4IR::OpMul: setOp(op, opName, __qmljs_inplace_mul_element); break;
    case V4IR::OpDiv: setOp(op, opName, __qmljs_inplace_div_element); break;
    case V4IR::OpMod: setOp(op, opName, __qmljs_inplace_mod_element); break;
    case V4IR::OpLShift: setOp(op, opName, __qmljs_inplace_shl_element); break;
    case V4IR::OpRShift: setOp(op, opName, __qmljs_inplace_shr_element); break;
    case V4IR::OpURShift: setOp(op, opName, __qmljs_inplace_ushr_element); break;
    default:
        Q_UNREACHABLE();
        break;
    }

    if (op) {
        _as->generateFunctionCallImp(Assembler::Void, opName, op, Assembler::ContextRegister,
                                     Assembler::Reference(targetBaseTemp), Assembler::Reference(targetIndexTemp),
                                     Assembler::Reference(source));
    }
}

void InstructionSelection::inplaceMemberOp(V4IR::AluOp oper, V4IR::Temp *source, V4IR::Temp *targetBase, const QString &targetName)
{
    VM::InplaceBinOpMember op = 0;
    const char *opName = 0;
    switch (oper) {
    case V4IR::OpBitAnd: setOp(op, opName, __qmljs_inplace_bit_and_member); break;
    case V4IR::OpBitOr: setOp(op, opName, __qmljs_inplace_bit_or_member); break;
    case V4IR::OpBitXor: setOp(op, opName, __qmljs_inplace_bit_xor_member); break;
    case V4IR::OpAdd: setOp(op, opName, __qmljs_inplace_add_member); break;
    case V4IR::OpSub: setOp(op, opName, __qmljs_inplace_sub_member); break;
    case V4IR::OpMul: setOp(op, opName, __qmljs_inplace_mul_member); break;
    case V4IR::OpDiv: setOp(op, opName, __qmljs_inplace_div_member); break;
    case V4IR::OpMod: setOp(op, opName, __qmljs_inplace_mod_member); break;
    case V4IR::OpLShift: setOp(op, opName, __qmljs_inplace_shl_member); break;
    case V4IR::OpRShift: setOp(op, opName, __qmljs_inplace_shr_member); break;
    case V4IR::OpURShift: setOp(op, opName, __qmljs_inplace_ushr_member); break;
    default:
        Q_UNREACHABLE();
        break;
    }

    if (op) {
        String* member = identifier(targetName);
        _as->generateFunctionCallImp(Assembler::Void, opName, op, Assembler::ContextRegister,
                                     Assembler::Reference(targetBase), identifier(targetName),
                                     Assembler::Reference(source));
    }
}

void InstructionSelection::callProperty(V4IR::Temp *base, const QString &name,
                                        V4IR::ExprList *args, V4IR::Temp *result)
{
    assert(base != 0);

    int argc = prepareVariableArguments(args);
    VM::String *s = identifier(name);

    if (useFastLookups) {
        uint index = addLookup(s);
        generateFunctionCall(Assembler::Void, __qmljs_call_property_lookup,
                             Assembler::ContextRegister, Assembler::PointerToValue(result),
                             Assembler::Reference(base), Assembler::TrustedImm32(index),
                             baseAddressForCallArguments(),
                             Assembler::TrustedImm32(argc));
    } else {
        generateFunctionCall(Assembler::Void, __qmljs_call_property,
                             Assembler::ContextRegister, Assembler::PointerToValue(result),
                             Assembler::Reference(base), s,
                             baseAddressForCallArguments(),
                             Assembler::TrustedImm32(argc));
    }
}

void InstructionSelection::callSubscript(V4IR::Temp *base, V4IR::Temp *index, V4IR::ExprList *args, V4IR::Temp *result)
{
    assert(base != 0);

    int argc = prepareVariableArguments(args);
    generateFunctionCall(Assembler::Void, __qmljs_call_element,
                         Assembler::ContextRegister, Assembler::PointerToValue(result),
                         Assembler::Reference(base), Assembler::Reference(index),
                         baseAddressForCallArguments(),
                         Assembler::TrustedImm32(argc));
}

String *InstructionSelection::identifier(const QString &s)
{
    String *str = engine()->newIdentifier(s);
    _vmFunction->identifiers.append(str);
    return str;
}

void InstructionSelection::constructActivationProperty(V4IR::Name *func, V4IR::ExprList *args, V4IR::Temp *result)
{
    assert(func != 0);

    if (useFastLookups && func->global) {
        int argc = prepareVariableArguments(args);
        VM::String *s = identifier(*func->id);

        uint index = addGlobalLookup(s);
        generateFunctionCall(Assembler::Void, __qmljs_construct_global_lookup,
                             Assembler::ContextRegister, Assembler::PointerToValue(result),
                             Assembler::TrustedImm32(index),
                             baseAddressForCallArguments(),
                             Assembler::TrustedImm32(argc));
        return;
    }

    callRuntimeMethod(result, __qmljs_construct_activation_property, func, args);
}

void InstructionSelection::constructProperty(V4IR::Temp *base, const QString &name, V4IR::ExprList *args, V4IR::Temp *result)
{
    int argc = prepareVariableArguments(args);
    generateFunctionCall(Assembler::Void, __qmljs_construct_property, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::Reference(base), identifier(name), baseAddressForCallArguments(), Assembler::TrustedImm32(argc));
}

void InstructionSelection::constructValue(V4IR::Temp *value, V4IR::ExprList *args, V4IR::Temp *result)
{
    assert(value != 0);

    int argc = prepareVariableArguments(args);
    generateFunctionCall(Assembler::Void, __qmljs_construct_value, Assembler::ContextRegister,
            Assembler::PointerToValue(result), Assembler::Reference(value), baseAddressForCallArguments(), Assembler::TrustedImm32(argc));
}

void InstructionSelection::visitJump(V4IR::Jump *s)
{
    _as->jumpToBlock(_block, s->target);
}

void InstructionSelection::visitCJump(V4IR::CJump *s)
{
    if (V4IR::Temp *t = s->cond->asTemp()) {
        Address temp = _as->loadTempAddress(Assembler::ScratchRegister, t);
        Address tag = temp;
        tag.offset += offsetof(VM::Value, tag);
        Assembler::Jump booleanConversion = _as->branch32(Assembler::NotEqual, tag, Assembler::TrustedImm32(VM::Value::Boolean_Type));

        Address data = temp;
        data.offset += offsetof(VM::Value, int_32);
        _as->load32(data, Assembler::ReturnValueRegister);
        Assembler::Jump testBoolean = _as->jump();

        booleanConversion.link(_as);
        {
            generateFunctionCall(Assembler::ReturnValueRegister, __qmljs_to_boolean, Assembler::Reference(t));
        }

        testBoolean.link(_as);
        Assembler::Jump target = _as->branch32(Assembler::NotEqual, Assembler::ReturnValueRegister, Assembler::TrustedImm32(0));
        _as->addPatch(s->iftrue, target);

        _as->jumpToBlock(_block, s->iffalse);
        return;
    } else if (V4IR::Binop *b = s->cond->asBinop()) {
        if (b->left->asTemp() && b->right->asTemp()) {
            VM::CmpOp op = 0;
            const char *opName = 0;
            switch (b->op) {
            default: Q_UNREACHABLE(); assert(!"todo"); break;
            case V4IR::OpGt: setOp(op, opName, __qmljs_cmp_gt); break;
            case V4IR::OpLt: setOp(op, opName, __qmljs_cmp_lt); break;
            case V4IR::OpGe: setOp(op, opName, __qmljs_cmp_ge); break;
            case V4IR::OpLe: setOp(op, opName, __qmljs_cmp_le); break;
            case V4IR::OpEqual: setOp(op, opName, __qmljs_cmp_eq); break;
            case V4IR::OpNotEqual: setOp(op, opName, __qmljs_cmp_ne); break;
            case V4IR::OpStrictEqual: setOp(op, opName, __qmljs_cmp_se); break;
            case V4IR::OpStrictNotEqual: setOp(op, opName, __qmljs_cmp_sne); break;
            case V4IR::OpInstanceof: setOp(op, opName, __qmljs_cmp_instanceof); break;
            case V4IR::OpIn: setOp(op, opName, __qmljs_cmp_in); break;
            } // switch

            _as->generateFunctionCallImp(Assembler::ReturnValueRegister, opName, op, Assembler::ContextRegister,
                                         Assembler::Reference(b->left->asTemp()),
                                         Assembler::Reference(b->right->asTemp()));

            Assembler::Jump target = _as->branch32(Assembler::NotEqual, Assembler::ReturnValueRegister, Assembler::TrustedImm32(0));
            _as->addPatch(s->iftrue, target);

            _as->jumpToBlock(_block, s->iffalse);
            return;
        } else {
            assert(!"wip");
        }
        Q_UNIMPLEMENTED();
    }
    Q_UNIMPLEMENTED();
    assert(!"TODO");
}

void InstructionSelection::visitRet(V4IR::Ret *s)
{
    if (V4IR::Temp *t = s->expr->asTemp()) {
#if defined(ARGUMENTS_IN_REGISTERS) && defined(VALUE_FITS_IN_REGISTER)
        _as->copyValue(Assembler::ReturnValueRegister, t);
#else
        _as->loadPtr(addressForArgument(0), Assembler::ReturnValueRegister);
        _as->copyValue(Address(Assembler::ReturnValueRegister, 0), t);
#endif
        return;
    }
    Q_UNIMPLEMENTED();
    Q_UNUSED(s);
}

int InstructionSelection::prepareVariableArguments(V4IR::ExprList* args)
{
    int argc = 0;
    for (V4IR::ExprList *it = args; it; it = it->next) {
        ++argc;
    }

    int i = 0;
    for (V4IR::ExprList *it = args; it; it = it->next, ++i) {
//        V4IR::Temp *arg = it->expr->asTemp();
//        assert(arg != 0);
        _as->copyValue(argumentAddressForCall(i), it->expr);
    }

    return argc;
}

void InstructionSelection::callRuntimeMethodImp(V4IR::Temp *result, const char* name, ActivationMethod method, V4IR::Expr *base, V4IR::ExprList *args)
{
    V4IR::Name *baseName = base->asName();
    assert(baseName != 0);

    int argc = prepareVariableArguments(args);
    _as->generateFunctionCallImp(Assembler::Void, name, method, Assembler::ContextRegister, Assembler::PointerToValue(result),
                                 identifier(*baseName->id), baseAddressForCallArguments(),
                                 Assembler::TrustedImm32(argc));
}


uint InstructionSelection::addLookup(VM::String *name)
{
    uint index = (uint)_lookups.size();
    VM::Lookup l;
    l.lookupProperty = Lookup::lookupPropertyGeneric;
    for (int i = 0; i < Lookup::Size; ++i)
        l.classList[i] = 0;
    l.level = -1;
    l.index = UINT_MAX;
    l.name = name;
    _lookups.append(l);
    return index;
}

uint InstructionSelection::addGlobalLookup(VM::String *name)
{
    uint index = (uint)_lookups.size();
    VM::Lookup l;
    l.lookupGlobal = Lookup::lookupGlobalGeneric;
    for (int i = 0; i < Lookup::Size; ++i)
        l.classList[i] = 0;
    l.level = -1;
    l.index = UINT_MAX;
    l.name = name;
    _lookups.append(l);
    return index;
}