This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 305
/
jsemit.cpp
7746 lines (6991 loc) · 264 KB
/
jsemit.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=99:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* JS bytecode generation.
*/
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
#include <new>
#include <string.h>
#include "jstypes.h"
#include "jsstdint.h"
#include "jsarena.h"
#include "jsutil.h"
#include "jsbit.h"
#include "jsprf.h"
#include "jsapi.h"
#include "jsatom.h"
#include "jsbool.h"
#include "jscntxt.h"
#include "jsversion.h"
#include "jsemit.h"
#include "jsfun.h"
#include "jsnum.h"
#include "jsopcode.h"
#include "jsparse.h"
#include "jsregexp.h"
#include "jsscan.h"
#include "jsscope.h"
#include "jsscript.h"
#include "jsautooplen.h" // generated headers last
#include "jsstaticcheck.h"
#include "jsobjinlines.h"
#include "jsscopeinlines.h"
/* Allocation chunk counts, must be powers of two in general. */
#define BYTECODE_CHUNK 256 /* code allocation increment */
#define SRCNOTE_CHUNK 64 /* initial srcnote allocation increment */
#define TRYNOTE_CHUNK 64 /* trynote allocation increment */
/* Macros to compute byte sizes from typed element counts. */
#define BYTECODE_SIZE(n) ((n) * sizeof(jsbytecode))
#define SRCNOTE_SIZE(n) ((n) * sizeof(jssrcnote))
#define TRYNOTE_SIZE(n) ((n) * sizeof(JSTryNote))
using namespace js;
using namespace js::gc;
static JSBool
NewTryNote(JSContext *cx, JSCodeGenerator *cg, JSTryNoteKind kind,
uintN stackDepth, size_t start, size_t end);
static JSBool
EmitIndexOp(JSContext *cx, JSOp op, uintN index, JSCodeGenerator *cg);
static JSBool
EmitLeaveBlock(JSContext *cx, JSCodeGenerator *cg, JSOp op, JSObjectBox *box);
JSCodeGenerator::JSCodeGenerator(Parser *parser,
JSArenaPool *cpool, JSArenaPool *npool,
uintN lineno)
: JSTreeContext(parser),
codePool(cpool), notePool(npool),
codeMark(JS_ARENA_MARK(cpool)), noteMark(JS_ARENA_MARK(npool)),
stackDepth(0), maxStackDepth(0),
ntrynotes(0), lastTryNode(NULL),
spanDeps(NULL), jumpTargets(NULL), jtFreeList(NULL),
numSpanDeps(0), numJumpTargets(0), spanDepTodo(0),
arrayCompDepth(0),
emitLevel(0),
constMap(parser->context),
constList(parser->context),
globalUses(ContextAllocPolicy(parser->context)),
closedArgs(ContextAllocPolicy(parser->context)),
closedVars(ContextAllocPolicy(parser->context)),
traceIndex(0)
{
flags = TCF_COMPILING;
memset(&prolog, 0, sizeof prolog);
memset(&main, 0, sizeof main);
current = &main;
firstLine = prolog.currentLine = main.currentLine = lineno;
prolog.noteMask = main.noteMask = SRCNOTE_CHUNK - 1;
memset(&upvarMap, 0, sizeof upvarMap);
}
bool JSCodeGenerator::init()
{
return constMap.init();
}
JSCodeGenerator::~JSCodeGenerator()
{
JS_ARENA_RELEASE(codePool, codeMark);
JS_ARENA_RELEASE(notePool, noteMark);
/* NB: non-null only after OOM. */
if (spanDeps)
parser->context->free(spanDeps);
if (upvarMap.vector)
parser->context->free(upvarMap.vector);
}
static ptrdiff_t
EmitCheck(JSContext *cx, JSCodeGenerator *cg, JSOp op, ptrdiff_t delta)
{
jsbytecode *base, *limit, *next;
ptrdiff_t offset, length;
size_t incr, size;
base = CG_BASE(cg);
next = CG_NEXT(cg);
limit = CG_LIMIT(cg);
offset = next - base;
if (next + delta > limit) {
length = offset + delta;
length = (length <= BYTECODE_CHUNK)
? BYTECODE_CHUNK
: JS_BIT(JS_CeilingLog2(length));
incr = BYTECODE_SIZE(length);
if (!base) {
JS_ARENA_ALLOCATE_CAST(base, jsbytecode *, cg->codePool, incr);
} else {
size = BYTECODE_SIZE(limit - base);
incr -= size;
JS_ARENA_GROW_CAST(base, jsbytecode *, cg->codePool, size, incr);
}
if (!base) {
js_ReportOutOfScriptQuota(cx);
return -1;
}
CG_BASE(cg) = base;
CG_LIMIT(cg) = base + length;
CG_NEXT(cg) = base + offset;
}
return offset;
}
static void
UpdateDepth(JSContext *cx, JSCodeGenerator *cg, ptrdiff_t target)
{
jsbytecode *pc;
JSOp op;
const JSCodeSpec *cs;
uintN extra, depth, nuses;
intN ndefs;
pc = CG_CODE(cg, target);
op = (JSOp) *pc;
cs = &js_CodeSpec[op];
#ifdef JS_TRACER
extern uint8 js_opcode2extra[];
extra = js_opcode2extra[op];
#else
extra = 0;
#endif
if ((cs->format & JOF_TMPSLOT_MASK) || extra) {
depth = (uintN) cg->stackDepth +
((cs->format & JOF_TMPSLOT_MASK) >> JOF_TMPSLOT_SHIFT) +
extra;
/* :TODO: hack - remove later. */
switch (op) {
case JSOP_PROPINC:
case JSOP_PROPDEC:
depth += 1;
break;
case JSOP_NAMEINC:
case JSOP_NAMEDEC:
case JSOP_INCNAME:
case JSOP_DECNAME:
case JSOP_GNAMEINC:
case JSOP_GNAMEDEC:
case JSOP_INCGNAME:
case JSOP_DECGNAME:
depth += 2;
break;
default:
break;
}
if (depth > cg->maxStackDepth)
cg->maxStackDepth = depth;
}
nuses = js_GetStackUses(cs, op, pc);
cg->stackDepth -= nuses;
JS_ASSERT(cg->stackDepth >= 0);
if (cg->stackDepth < 0) {
char numBuf[12];
TokenStream *ts;
JS_snprintf(numBuf, sizeof numBuf, "%d", target);
ts = &cg->parser->tokenStream;
JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING,
js_GetErrorMessage, NULL,
JSMSG_STACK_UNDERFLOW,
ts->getFilename() ? ts->getFilename() : "stdin",
numBuf);
}
ndefs = cs->ndefs;
if (ndefs < 0) {
JSObject *blockObj;
/* We just executed IndexParsedObject */
JS_ASSERT(op == JSOP_ENTERBLOCK);
JS_ASSERT(nuses == 0);
blockObj = cg->objectList.lastbox->object;
JS_ASSERT(blockObj->isStaticBlock());
JS_ASSERT(blockObj->getSlot(JSSLOT_BLOCK_DEPTH).isUndefined());
OBJ_SET_BLOCK_DEPTH(cx, blockObj, cg->stackDepth);
ndefs = OBJ_BLOCK_COUNT(cx, blockObj);
}
cg->stackDepth += ndefs;
if ((uintN)cg->stackDepth > cg->maxStackDepth)
cg->maxStackDepth = cg->stackDepth;
}
ptrdiff_t
js_Emit1(JSContext *cx, JSCodeGenerator *cg, JSOp op)
{
ptrdiff_t offset = EmitCheck(cx, cg, op, 1);
if (offset >= 0) {
*CG_NEXT(cg)++ = (jsbytecode)op;
UpdateDepth(cx, cg, offset);
}
return offset;
}
ptrdiff_t
js_Emit2(JSContext *cx, JSCodeGenerator *cg, JSOp op, jsbytecode op1)
{
ptrdiff_t offset = EmitCheck(cx, cg, op, 2);
if (offset >= 0) {
jsbytecode *next = CG_NEXT(cg);
next[0] = (jsbytecode)op;
next[1] = op1;
CG_NEXT(cg) = next + 2;
UpdateDepth(cx, cg, offset);
}
return offset;
}
ptrdiff_t
js_Emit3(JSContext *cx, JSCodeGenerator *cg, JSOp op, jsbytecode op1,
jsbytecode op2)
{
ptrdiff_t offset = EmitCheck(cx, cg, op, 3);
if (offset >= 0) {
jsbytecode *next = CG_NEXT(cg);
next[0] = (jsbytecode)op;
next[1] = op1;
next[2] = op2;
CG_NEXT(cg) = next + 3;
UpdateDepth(cx, cg, offset);
}
return offset;
}
ptrdiff_t
js_Emit5(JSContext *cx, JSCodeGenerator *cg, JSOp op, uint16 op1, uint16 op2)
{
ptrdiff_t offset = EmitCheck(cx, cg, op, 5);
if (offset >= 0) {
jsbytecode *next = CG_NEXT(cg);
next[0] = (jsbytecode)op;
next[1] = UINT16_HI(op1);
next[2] = UINT16_LO(op1);
next[3] = UINT16_HI(op2);
next[4] = UINT16_LO(op2);
CG_NEXT(cg) = next + 5;
UpdateDepth(cx, cg, offset);
}
return offset;
}
ptrdiff_t
js_EmitN(JSContext *cx, JSCodeGenerator *cg, JSOp op, size_t extra)
{
ptrdiff_t length = 1 + (ptrdiff_t)extra;
ptrdiff_t offset = EmitCheck(cx, cg, op, length);
if (offset >= 0) {
jsbytecode *next = CG_NEXT(cg);
*next = (jsbytecode)op;
memset(next + 1, 0, BYTECODE_SIZE(extra));
CG_NEXT(cg) = next + length;
/*
* Don't UpdateDepth if op's use-count comes from the immediate
* operand yet to be stored in the extra bytes after op.
*/
if (js_CodeSpec[op].nuses >= 0)
UpdateDepth(cx, cg, offset);
}
return offset;
}
/* XXX too many "... statement" L10N gaffes below -- fix via js.msg! */
const char js_with_statement_str[] = "with statement";
const char js_finally_block_str[] = "finally block";
const char js_script_str[] = "script";
static const char *statementName[] = {
"label statement", /* LABEL */
"if statement", /* IF */
"else statement", /* ELSE */
"destructuring body", /* BODY */
"switch statement", /* SWITCH */
"block", /* BLOCK */
js_with_statement_str, /* WITH */
"catch block", /* CATCH */
"try block", /* TRY */
js_finally_block_str, /* FINALLY */
js_finally_block_str, /* SUBROUTINE */
"do loop", /* DO_LOOP */
"for loop", /* FOR_LOOP */
"for/in loop", /* FOR_IN_LOOP */
"while loop", /* WHILE_LOOP */
};
JS_STATIC_ASSERT(JS_ARRAY_LENGTH(statementName) == STMT_LIMIT);
static const char *
StatementName(JSCodeGenerator *cg)
{
if (!cg->topStmt)
return js_script_str;
return statementName[cg->topStmt->type];
}
static void
ReportStatementTooLarge(JSContext *cx, JSCodeGenerator *cg)
{
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_NEED_DIET,
StatementName(cg));
}
/**
Span-dependent instructions in JS bytecode consist of the jump (JOF_JUMP)
and switch (JOF_LOOKUPSWITCH, JOF_TABLESWITCH) format opcodes, subdivided
into unconditional (gotos and gosubs), and conditional jumps or branches
(which pop a value, test it, and jump depending on its value). Most jumps
have just one immediate operand, a signed offset from the jump opcode's pc
to the target bytecode. The lookup and table switch opcodes may contain
many jump offsets.
Mozilla bug #80981 (http://bugzilla.mozilla.org/show_bug.cgi?id=80981) was
fixed by adding extended "X" counterparts to the opcodes/formats (NB: X is
suffixed to prefer JSOP_ORX thereby avoiding a JSOP_XOR name collision for
the extended form of the JSOP_OR branch opcode). The unextended or short
formats have 16-bit signed immediate offset operands, the extended or long
formats have 32-bit signed immediates. The span-dependency problem consists
of selecting as few long instructions as possible, or about as few -- since
jumps can span other jumps, extending one jump may cause another to need to
be extended.
Most JS scripts are short, so need no extended jumps. We optimize for this
case by generating short jumps until we know a long jump is needed. After
that point, we keep generating short jumps, but each jump's 16-bit immediate
offset operand is actually an unsigned index into cg->spanDeps, an array of
JSSpanDep structs. Each struct tells the top offset in the script of the
opcode, the "before" offset of the jump (which will be the same as top for
simplex jumps, but which will index further into the bytecode array for a
non-initial jump offset in a lookup or table switch), the after "offset"
adjusted during span-dependent instruction selection (initially the same
value as the "before" offset), and the jump target (more below).
Since we generate cg->spanDeps lazily, from within js_SetJumpOffset, we must
ensure that all bytecode generated so far can be inspected to discover where
the jump offset immediate operands lie within CG_CODE(cg). But the bonus is
that we generate span-dependency records sorted by their offsets, so we can
binary-search when trying to find a JSSpanDep for a given bytecode offset,
or the nearest JSSpanDep at or above a given pc.
To avoid limiting scripts to 64K jumps, if the cg->spanDeps index overflows
65534, we store SPANDEP_INDEX_HUGE in the jump's immediate operand. This
tells us that we need to binary-search for the cg->spanDeps entry by the
jump opcode's bytecode offset (sd->before).
Jump targets need to be maintained in a data structure that lets us look
up an already-known target by its address (jumps may have a common target),
and that also lets us update the addresses (script-relative, a.k.a. absolute
offsets) of targets that come after a jump target (for when a jump below
that target needs to be extended). We use an AVL tree, implemented using
recursion, but with some tricky optimizations to its height-balancing code
(see http://www.cmcrossroads.com/bradapp/ftp/src/libs/C++/AvlTrees.html).
A final wrinkle: backpatch chains are linked by jump-to-jump offsets with
positive sign, even though they link "backward" (i.e., toward lower bytecode
address). We don't want to waste space and search time in the AVL tree for
such temporary backpatch deltas, so we use a single-bit wildcard scheme to
tag true JSJumpTarget pointers and encode untagged, signed (positive) deltas
in JSSpanDep.target pointers, depending on whether the JSSpanDep has a known
target, or is still awaiting backpatching.
Note that backpatch chains would present a problem for BuildSpanDepTable,
which inspects bytecode to build cg->spanDeps on demand, when the first
short jump offset overflows. To solve this temporary problem, we emit a
proxy bytecode (JSOP_BACKPATCH; JSOP_BACKPATCH_POP for branch ops) whose
nuses/ndefs counts help keep the stack balanced, but whose opcode format
distinguishes its backpatch delta immediate operand from a normal jump
offset.
*/
static int
BalanceJumpTargets(JSJumpTarget **jtp)
{
JSJumpTarget *jt, *jt2, *root;
int dir, otherDir, heightChanged;
JSBool doubleRotate;
jt = *jtp;
JS_ASSERT(jt->balance != 0);
if (jt->balance < -1) {
dir = JT_RIGHT;
doubleRotate = (jt->kids[JT_LEFT]->balance > 0);
} else if (jt->balance > 1) {
dir = JT_LEFT;
doubleRotate = (jt->kids[JT_RIGHT]->balance < 0);
} else {
return 0;
}
otherDir = JT_OTHER_DIR(dir);
if (doubleRotate) {
jt2 = jt->kids[otherDir];
*jtp = root = jt2->kids[dir];
jt->kids[otherDir] = root->kids[dir];
root->kids[dir] = jt;
jt2->kids[dir] = root->kids[otherDir];
root->kids[otherDir] = jt2;
heightChanged = 1;
root->kids[JT_LEFT]->balance = -JS_MAX(root->balance, 0);
root->kids[JT_RIGHT]->balance = -JS_MIN(root->balance, 0);
root->balance = 0;
} else {
*jtp = root = jt->kids[otherDir];
jt->kids[otherDir] = root->kids[dir];
root->kids[dir] = jt;
heightChanged = (root->balance != 0);
jt->balance = -((dir == JT_LEFT) ? --root->balance : ++root->balance);
}
return heightChanged;
}
typedef struct AddJumpTargetArgs {
JSContext *cx;
JSCodeGenerator *cg;
ptrdiff_t offset;
JSJumpTarget *node;
} AddJumpTargetArgs;
static int
AddJumpTarget(AddJumpTargetArgs *args, JSJumpTarget **jtp)
{
JSJumpTarget *jt;
int balanceDelta;
jt = *jtp;
if (!jt) {
JSCodeGenerator *cg = args->cg;
jt = cg->jtFreeList;
if (jt) {
cg->jtFreeList = jt->kids[JT_LEFT];
} else {
JS_ARENA_ALLOCATE_CAST(jt, JSJumpTarget *, &args->cx->tempPool,
sizeof *jt);
if (!jt) {
js_ReportOutOfScriptQuota(args->cx);
return 0;
}
}
jt->offset = args->offset;
jt->balance = 0;
jt->kids[JT_LEFT] = jt->kids[JT_RIGHT] = NULL;
cg->numJumpTargets++;
args->node = jt;
*jtp = jt;
return 1;
}
if (jt->offset == args->offset) {
args->node = jt;
return 0;
}
if (args->offset < jt->offset)
balanceDelta = -AddJumpTarget(args, &jt->kids[JT_LEFT]);
else
balanceDelta = AddJumpTarget(args, &jt->kids[JT_RIGHT]);
if (!args->node)
return 0;
jt->balance += balanceDelta;
return (balanceDelta && jt->balance)
? 1 - BalanceJumpTargets(jtp)
: 0;
}
#ifdef DEBUG_brendan
static int AVLCheck(JSJumpTarget *jt)
{
int lh, rh;
if (!jt) return 0;
JS_ASSERT(-1 <= jt->balance && jt->balance <= 1);
lh = AVLCheck(jt->kids[JT_LEFT]);
rh = AVLCheck(jt->kids[JT_RIGHT]);
JS_ASSERT(jt->balance == rh - lh);
return 1 + JS_MAX(lh, rh);
}
#endif
static JSBool
SetSpanDepTarget(JSContext *cx, JSCodeGenerator *cg, JSSpanDep *sd,
ptrdiff_t off)
{
AddJumpTargetArgs args;
if (off < JUMPX_OFFSET_MIN || JUMPX_OFFSET_MAX < off) {
ReportStatementTooLarge(cx, cg);
return JS_FALSE;
}
args.cx = cx;
args.cg = cg;
args.offset = sd->top + off;
args.node = NULL;
AddJumpTarget(&args, &cg->jumpTargets);
if (!args.node)
return JS_FALSE;
#ifdef DEBUG_brendan
AVLCheck(cg->jumpTargets);
#endif
SD_SET_TARGET(sd, args.node);
return JS_TRUE;
}
#define SPANDEPS_MIN 256
#define SPANDEPS_SIZE(n) ((n) * sizeof(JSSpanDep))
#define SPANDEPS_SIZE_MIN SPANDEPS_SIZE(SPANDEPS_MIN)
static JSBool
AddSpanDep(JSContext *cx, JSCodeGenerator *cg, jsbytecode *pc, jsbytecode *pc2,
ptrdiff_t off)
{
uintN index;
JSSpanDep *sdbase, *sd;
size_t size;
index = cg->numSpanDeps;
if (index + 1 == 0) {
ReportStatementTooLarge(cx, cg);
return JS_FALSE;
}
if ((index & (index - 1)) == 0 &&
(!(sdbase = cg->spanDeps) || index >= SPANDEPS_MIN)) {
size = sdbase ? SPANDEPS_SIZE(index) : SPANDEPS_SIZE_MIN / 2;
sdbase = (JSSpanDep *) cx->realloc(sdbase, size + size);
if (!sdbase)
return JS_FALSE;
cg->spanDeps = sdbase;
}
cg->numSpanDeps = index + 1;
sd = cg->spanDeps + index;
sd->top = pc - CG_BASE(cg);
sd->offset = sd->before = pc2 - CG_BASE(cg);
if (js_CodeSpec[*pc].format & JOF_BACKPATCH) {
/* Jump offset will be backpatched if off is a non-zero "bpdelta". */
if (off != 0) {
JS_ASSERT(off >= 1 + JUMP_OFFSET_LEN);
if (off > BPDELTA_MAX) {
ReportStatementTooLarge(cx, cg);
return JS_FALSE;
}
}
SD_SET_BPDELTA(sd, off);
} else if (off == 0) {
/* Jump offset will be patched directly, without backpatch chaining. */
SD_SET_TARGET(sd, 0);
} else {
/* The jump offset in off is non-zero, therefore it's already known. */
if (!SetSpanDepTarget(cx, cg, sd, off))
return JS_FALSE;
}
if (index > SPANDEP_INDEX_MAX)
index = SPANDEP_INDEX_HUGE;
SET_SPANDEP_INDEX(pc2, index);
return JS_TRUE;
}
static jsbytecode *
AddSwitchSpanDeps(JSContext *cx, JSCodeGenerator *cg, jsbytecode *pc)
{
JSOp op;
jsbytecode *pc2;
ptrdiff_t off;
jsint low, high;
uintN njumps, indexlen;
op = (JSOp) *pc;
JS_ASSERT(op == JSOP_TABLESWITCH || op == JSOP_LOOKUPSWITCH);
pc2 = pc;
off = GET_JUMP_OFFSET(pc2);
if (!AddSpanDep(cx, cg, pc, pc2, off))
return NULL;
pc2 += JUMP_OFFSET_LEN;
if (op == JSOP_TABLESWITCH) {
low = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
high = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
njumps = (uintN) (high - low + 1);
indexlen = 0;
} else {
njumps = GET_UINT16(pc2);
pc2 += UINT16_LEN;
indexlen = INDEX_LEN;
}
while (njumps) {
--njumps;
pc2 += indexlen;
off = GET_JUMP_OFFSET(pc2);
if (!AddSpanDep(cx, cg, pc, pc2, off))
return NULL;
pc2 += JUMP_OFFSET_LEN;
}
return 1 + pc2;
}
static JSBool
BuildSpanDepTable(JSContext *cx, JSCodeGenerator *cg)
{
jsbytecode *pc, *end;
JSOp op;
const JSCodeSpec *cs;
ptrdiff_t off;
pc = CG_BASE(cg) + cg->spanDepTodo;
end = CG_NEXT(cg);
while (pc != end) {
JS_ASSERT(pc < end);
op = (JSOp)*pc;
cs = &js_CodeSpec[op];
switch (JOF_TYPE(cs->format)) {
case JOF_TABLESWITCH:
case JOF_LOOKUPSWITCH:
pc = AddSwitchSpanDeps(cx, cg, pc);
if (!pc)
return JS_FALSE;
break;
case JOF_JUMP:
off = GET_JUMP_OFFSET(pc);
if (!AddSpanDep(cx, cg, pc, pc, off))
return JS_FALSE;
/* FALL THROUGH */
default:
pc += cs->length;
break;
}
}
return JS_TRUE;
}
static JSSpanDep *
GetSpanDep(JSCodeGenerator *cg, jsbytecode *pc)
{
uintN index;
ptrdiff_t offset;
int lo, hi, mid;
JSSpanDep *sd;
index = GET_SPANDEP_INDEX(pc);
if (index != SPANDEP_INDEX_HUGE)
return cg->spanDeps + index;
offset = pc - CG_BASE(cg);
lo = 0;
hi = cg->numSpanDeps - 1;
while (lo <= hi) {
mid = (lo + hi) / 2;
sd = cg->spanDeps + mid;
if (sd->before == offset)
return sd;
if (sd->before < offset)
lo = mid + 1;
else
hi = mid - 1;
}
JS_ASSERT(0);
return NULL;
}
static JSBool
SetBackPatchDelta(JSContext *cx, JSCodeGenerator *cg, jsbytecode *pc,
ptrdiff_t delta)
{
JSSpanDep *sd;
JS_ASSERT(delta >= 1 + JUMP_OFFSET_LEN);
if (!cg->spanDeps && delta < JUMP_OFFSET_MAX) {
SET_JUMP_OFFSET(pc, delta);
return JS_TRUE;
}
if (delta > BPDELTA_MAX) {
ReportStatementTooLarge(cx, cg);
return JS_FALSE;
}
if (!cg->spanDeps && !BuildSpanDepTable(cx, cg))
return JS_FALSE;
sd = GetSpanDep(cg, pc);
JS_ASSERT(SD_GET_BPDELTA(sd) == 0);
SD_SET_BPDELTA(sd, delta);
return JS_TRUE;
}
static void
UpdateJumpTargets(JSJumpTarget *jt, ptrdiff_t pivot, ptrdiff_t delta)
{
if (jt->offset > pivot) {
jt->offset += delta;
if (jt->kids[JT_LEFT])
UpdateJumpTargets(jt->kids[JT_LEFT], pivot, delta);
}
if (jt->kids[JT_RIGHT])
UpdateJumpTargets(jt->kids[JT_RIGHT], pivot, delta);
}
static JSSpanDep *
FindNearestSpanDep(JSCodeGenerator *cg, ptrdiff_t offset, int lo,
JSSpanDep *guard)
{
int num, hi, mid;
JSSpanDep *sdbase, *sd;
num = cg->numSpanDeps;
JS_ASSERT(num > 0);
hi = num - 1;
sdbase = cg->spanDeps;
while (lo <= hi) {
mid = (lo + hi) / 2;
sd = sdbase + mid;
if (sd->before == offset)
return sd;
if (sd->before < offset)
lo = mid + 1;
else
hi = mid - 1;
}
if (lo == num)
return guard;
sd = sdbase + lo;
JS_ASSERT(sd->before >= offset && (lo == 0 || sd[-1].before < offset));
return sd;
}
static void
FreeJumpTargets(JSCodeGenerator *cg, JSJumpTarget *jt)
{
if (jt->kids[JT_LEFT])
FreeJumpTargets(cg, jt->kids[JT_LEFT]);
if (jt->kids[JT_RIGHT])
FreeJumpTargets(cg, jt->kids[JT_RIGHT]);
jt->kids[JT_LEFT] = cg->jtFreeList;
cg->jtFreeList = jt;
}
static JSBool
OptimizeSpanDeps(JSContext *cx, JSCodeGenerator *cg)
{
jsbytecode *pc, *oldpc, *base, *limit, *next;
JSSpanDep *sd, *sd2, *sdbase, *sdlimit, *sdtop, guard;
ptrdiff_t offset, growth, delta, top, pivot, span, length, target;
JSBool done;
JSOp op;
uint32 type;
size_t size, incr;
jssrcnote *sn, *snlimit;
JSSrcNoteSpec *spec;
uintN i, n, noteIndex;
JSTryNode *tryNode;
#ifdef DEBUG_brendan
int passes = 0;
#endif
base = CG_BASE(cg);
sdbase = cg->spanDeps;
sdlimit = sdbase + cg->numSpanDeps;
offset = CG_OFFSET(cg);
growth = 0;
do {
done = JS_TRUE;
delta = 0;
top = pivot = -1;
sdtop = NULL;
pc = NULL;
op = JSOP_NOP;
type = 0;
#ifdef DEBUG_brendan
passes++;
#endif
for (sd = sdbase; sd < sdlimit; sd++) {
JS_ASSERT(JT_HAS_TAG(sd->target));
sd->offset += delta;
if (sd->top != top) {
sdtop = sd;
top = sd->top;
JS_ASSERT(top == sd->before);
pivot = sd->offset;
pc = base + top;
op = (JSOp) *pc;
type = JOF_OPTYPE(op);
if (JOF_TYPE_IS_EXTENDED_JUMP(type)) {
/*
* We already extended all the jump offset operands for
* the opcode at sd->top. Jumps and branches have only
* one jump offset operand, but switches have many, all
* of which are adjacent in cg->spanDeps.
*/
continue;
}
JS_ASSERT(type == JOF_JUMP ||
type == JOF_TABLESWITCH ||
type == JOF_LOOKUPSWITCH);
}
if (!JOF_TYPE_IS_EXTENDED_JUMP(type)) {
span = SD_SPAN(sd, pivot);
if (span < JUMP_OFFSET_MIN || JUMP_OFFSET_MAX < span) {
ptrdiff_t deltaFromTop = 0;
done = JS_FALSE;
switch (op) {
case JSOP_GOTO: op = JSOP_GOTOX; break;
case JSOP_IFEQ: op = JSOP_IFEQX; break;
case JSOP_IFNE: op = JSOP_IFNEX; break;
case JSOP_OR: op = JSOP_ORX; break;
case JSOP_AND: op = JSOP_ANDX; break;
case JSOP_GOSUB: op = JSOP_GOSUBX; break;
case JSOP_CASE: op = JSOP_CASEX; break;
case JSOP_DEFAULT: op = JSOP_DEFAULTX; break;
case JSOP_TABLESWITCH: op = JSOP_TABLESWITCHX; break;
case JSOP_LOOKUPSWITCH: op = JSOP_LOOKUPSWITCHX; break;
default:
ReportStatementTooLarge(cx, cg);
return JS_FALSE;
}
*pc = (jsbytecode) op;
for (sd2 = sdtop; sd2 < sdlimit && sd2->top == top; sd2++) {
if (sd2 <= sd) {
/*
* sd2->offset already includes delta as it stood
* before we entered this loop, but it must also
* include the delta relative to top due to all the
* extended jump offset immediates for the opcode
* starting at top, which we extend in this loop.
*
* If there is only one extended jump offset, then
* sd2->offset won't change and this for loop will
* iterate once only.
*/
sd2->offset += deltaFromTop;
deltaFromTop += JUMPX_OFFSET_LEN - JUMP_OFFSET_LEN;
} else {
/*
* sd2 comes after sd, and won't be revisited by
* the outer for loop, so we have to increase its
* offset by delta, not merely by deltaFromTop.
*/
sd2->offset += delta;
}
delta += JUMPX_OFFSET_LEN - JUMP_OFFSET_LEN;
UpdateJumpTargets(cg->jumpTargets, sd2->offset,
JUMPX_OFFSET_LEN - JUMP_OFFSET_LEN);
}
sd = sd2 - 1;
}
}
}
growth += delta;
} while (!done);
if (growth) {
#ifdef DEBUG_brendan
TokenStream *ts = &cg->parser->tokenStream;
printf("%s:%u: %u/%u jumps extended in %d passes (%d=%d+%d)\n",
ts->filename ? ts->filename : "stdin", cg->firstLine,
growth / (JUMPX_OFFSET_LEN - JUMP_OFFSET_LEN), cg->numSpanDeps,
passes, offset + growth, offset, growth);
#endif
/*
* Ensure that we have room for the extended jumps, but don't round up
* to a power of two -- we're done generating code, so we cut to fit.
*/
limit = CG_LIMIT(cg);
length = offset + growth;
next = base + length;
if (next > limit) {
JS_ASSERT(length > BYTECODE_CHUNK);
size = BYTECODE_SIZE(limit - base);
incr = BYTECODE_SIZE(length) - size;
JS_ARENA_GROW_CAST(base, jsbytecode *, cg->codePool, size, incr);
if (!base) {
js_ReportOutOfScriptQuota(cx);
return JS_FALSE;
}
CG_BASE(cg) = base;
CG_LIMIT(cg) = next = base + length;
}
CG_NEXT(cg) = next;
/*
* Set up a fake span dependency record to guard the end of the code
* being generated. This guard record is returned as a fencepost by
* FindNearestSpanDep if there is no real spandep at or above a given
* unextended code offset.
*/
guard.top = -1;
guard.offset = offset + growth;
guard.before = offset;
guard.target = NULL;
}
/*
* Now work backwards through the span dependencies, copying chunks of
* bytecode between each extended jump toward the end of the grown code
* space, and restoring immediate offset operands for all jump bytecodes.